-
Notifications
You must be signed in to change notification settings - Fork 5
/
infro.js
1814 lines (1513 loc) · 69.1 KB
/
infro.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
var infro = (function () {
"use strict";
/* TODO:
slidey buttons?
pull out search box?
rethink discrete
comment
remove section labels?
remove boundstorage?
alternative types of filtering other than exact match
DONEISH:
slow in ie8 and firefox :(... STILL (now less slow!)
(meh)bind data changes to function calls
WISHLIST:
request fields also toggles filterables (so can set default) - (try to guess how best to represent if not defined)
clustering of urls hierarchically - a contains filter?
turning a number of values in a row into a time graph (say: UKpop: 1960: 2, 1970: 4, 1980: 8 etc)
*/
/* d3 helpers & util */
var identity = function (item) { return item; };
var arrentity = function (item) { return [item]; };
/* borrowed from underscore */
var debounce = function (func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) { func.apply(context, args); }
};
if (immediate && !timeout) { func.apply(context, args); }
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
};
/* borrowed from underscore */
var throttle = function (func, wait) {
var context, args, timeout, throttling, more, result;
var whenDone = debounce(function(){ more = throttling = false; }, wait);
return function() {
context = this; args = arguments;
var later = function() {
timeout = null;
if (more) { func.apply(context, args); }
whenDone();
};
if (!timeout) { timeout = setTimeout(later, wait); }
if (throttling) {
more = true;
} else {
result = func.apply(context, args);
}
whenDone();
throttling = true;
return result;
};
};
var is_numeric = function (n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
var is_function = function (function_to_check) {
var get_type = {};
return function_to_check && get_type.toString.call(function_to_check) === '[object Function]';
};
var is_array = function (array_to_check){
return Object.prototype.toString.call(array_to_check) === "[object Array]";
};
var data_bind = function(selection, element, class_name, data, datakey, exit){
/* bind data to the "element.class_name"'s in selection, optional datakey and exit bind - also sets the position to abosulte to allow the positioning code to work*/
var new_selection = selection.selectAll(element+"."+class_name).data(data, datakey);
new_selection.enter().append(element).attr("class", class_name);
new_selection.style("position", "absolute");
if (exit !== false){
new_selection.exit().remove();
}
return new_selection;
};
var pluck = function(){
/* returns a function that will pluck the data out of an object, ie pluck("hi", "bye")({hi: {bye: 2}}) -> 2 */
var keys = Array.prototype.slice.call(arguments);
return function(item){
var plucked_item = item;
for (var i=0; i<keys.length; i++){
plucked_item = plucked_item[keys[i]];
}
return plucked_item;
};
};
String.prototype.contains = function(other_string) {
return this.indexOf(other_string) !== -1;
};
["height", "width"].forEach(function(dim){
/* returns the height or width value set for the selection, and removes 'px' */
d3.selection.prototype[dim] = function() {
if (this.empty()){
return 0;
}
for (var sel=0; sel<this.length; sel++){
if (this[sel].length > 0){
return this[sel][0].style.getPropertyValue(dim).slice(0, -2);
}
}
return 0;
};
});
var get = function(object, key, default_value){
/* python style dict.get */
if (object && object[key]){
return object[key];
} else {
return default_value;
}
}
/* GUI helpers... */
var get_font_size = function(width, height, type){
if (type === "title"){
return d3.max([d3.min([height/6, width/8,24]), 12]);
} else if (type === "bar_label"){
return d3.max([d3.min([height/1.6, width/14,11]), 9]);
} else if (type === "tick"){
return d3.max([d3.min([width/32, height/8, 13]), 8]);
} else if (type == "filters"){
return d3.max([d3.min([height, width/40, 30]),8]);
}
};
var metric_aggreg = function(){
return selects.aggreg.human(selects.aggreg.current).toLowerCase()+
" "+selects.metric.human(selects.metric.current).toLowerCase();
};
/* data manipulation helpers... */
var split_dataset = function(dataset, key_field){
var dataset_by_field = {};
dataset.forEach(function(item){
var field_value = item[key_field];
(dataset_by_field[field_value] || (dataset_by_field[field_value] = [])).push(item);
});
return dataset_by_field;
};
var pull_out_fields = function(dataset, fields){
/* pulls out the specified fields from each data item, returning the trimmed data items */
return dataset.map(function(item){
var new_item = {};
fields.forEach(function(field){
if (field === infro_unit){
new_item[field] = 1;
}else if (field === more_info_url){
new_item[field] = construct_more_info_url(item, user_config.more_info_url);
} else {
new_item[field] = item[field];
}
});
return new_item;
});
};
var pull_out_field = function(dataset, field){
/* pulls out the specified fields from each data item, returning the values */
return pull_out_fields(dataset, [field]).map(pluck(field))
};
var cached_distributions = {}; /* we add resetting this to data_filter's on change */
var get_distribution = function(key_field){
if (key_field in cached_distributions){
return cached_distributions[key_field];
}
var dataset = data_filter.apply();
var compare_field = data_filter.metric();
var reduce_function = data_filter.aggregation();
/* split the data set by the key_field, assumes discrete... */
var dataset_by_field = split_dataset(dataset, key_field);
/* pull out the compare_field for each data item and then apply the reduce function for each partition on key_field */
var reduced_dataset_by_field = d3.entries(dataset_by_field).map(function(field_data){
return {key: field_data.key, value: reduce_function(pull_out_field(field_data.value, compare_field))};
});
/* then return the ordered comparison */
var distribution = reduced_dataset_by_field.sort(function(a,b){return d3.descending(a.value, b.value)});
cached_distributions[key_field] = distribution;
return distribution;
};
var filter_sort_format_data = function(columns_to_show, units_sort, units_sort_order){
var filtered_data = data_filter.apply();
var type = data_filter.type(units_sort)
var filtered_rows_to_show = pull_out_fields(filtered_data, columns_to_show);
/* sort the data */
if (units_sort !== null){
filtered_rows_to_show.sort(function(a, b){
if (type === "continuous"){
return units_sort_order(Number(a[units_sort]), Number(b[units_sort]));
} else {
return units_sort_order(a[units_sort], b[units_sort]);
}
});
}
/* want to search on the /visible/ content, so we run through the formatters first */
var formatted_rows = filtered_rows_to_show.map(function(row){
return d3.entries(row).map(function(col){
if (col.key !== more_info_url){
return {key:col.key,
formatted_value: data_filter.format(col.key, col.value),
value:col.value};
}else{
return {key: more_info_url, value:col.value, formatted_value: "more"};
}
});
});
return formatted_rows;
};
/* todo: refactor :( */
var create_histogram = function(data_set, metric, no_bins, bin_width, height){
var raw_metrics = pull_out_field(data_set, metric).map(Number);
var min, max;
if (raw_metrics.length !== 0){
min = d3.min(raw_metrics); /* log(0) is undefined (we take it off when creating the filter)*/
if (min ===0){
min = 1;
}
max = d3.max(raw_metrics)+1; /* to get the highest value */
} else {
return null;
}
var metric_scale = data_filter.scale(metric);
var histo_scale = (metric_scale===d3.time.scale?d3.scale.linear:metric_scale)()
.domain([min,max]).range([0,no_bins]);
var format_min, format_max;
if (metric_scale === d3.time.scale){
format_min = new Date((min-10)*1000);
format_max = new Date((max+10)*1000);
}else{
format_min = min;
format_max = max;
}
var thresholds = d3.range(0,no_bins+1).map(histo_scale.invert);
var histo_layout = d3.layout.histogram().bins(thresholds);
/* calc histograms first as we need max frequency for scaling y axis */
var histogram = histo_layout(raw_metrics);
var maxfreqy = d3.max(histogram.map(pluck('y')));
var Y = d3.scale.pow()
.exponent(.35)
.domain([0,maxfreqy])
.range([height,0]);
var area = d3.svg.area()
.x(function(d){ return d[0];})
.y1(function(d){return d[1];})
.y0(function(d){return height;})
.interpolate("basis");
var coords = [[0,height]];
histogram.forEach(function(v,i){
coords.push([(i*bin_width)+Math.round(bin_width/2), Y(v.y)]);
});
coords.push([no_bins*bin_width, height]); /* smooth the right edge */
var path = area(coords);
var brushscale = histo_scale.copy().domain([min,max]).range([0, bin_width*no_bins]);
var axisscale = metric_scale()
.domain([format_min,format_max])
.range([0, bin_width*no_bins]);
var formatter = data_filter.formatter(metric);
var XAxis = d3.svg.axis().scale(axisscale).ticks(8, formatter).tickSubdivide(5).tickSize(2,0);
if (metric_scale !== d3.scale.log && metric_scale !== d3.time.scale){
XAxis.tickFormat(formatter);
}
var snap_to_bin = function(extent){
/* find the current_bin_nos */
var bin_no_l = histo_scale(extent[0]);
var bin_no_u = histo_scale(extent[1]);
var rounded_bins_apart = Math.round(bin_no_u - bin_no_l);
var real_bins_apart = bin_no_u - bin_no_l;
if (Math.abs(rounded_bins_apart - real_bins_apart) < 0.08){
/* If they are a multiple of bin width apart, them keep them that way */
var lower = Math.round(bin_no_l);
return [lower, lower+ rounded_bins_apart].map(histo_scale.invert);
}else {
/* otherwise snap to the closest bin (turn metric values to bin_numbers and then back to metric value) */
return extent.map(histo_scale).map(Math.round).map(histo_scale.invert);
}
};
var brush = d3.svg.brush().x(brushscale)
.on("brush.histo", function(d,i){
var old_extent = brush.extent();
var new_extent = snap_to_bin(old_extent);
d3.select(this.parentNode).select(".brush").call(brush.extent(new_extent));
if (data_filter.has(metric)){ /* so we don;t immediately move the filter up */
if (new_extent[0] === 1){
new_extent[0] -=1;
}
/* if the filter would have changed */
if (!data_filter.has(metric, new_extent)){
data_filter.add(metric, new_extent);
}
}
})
.on("brushend.histo", function(d,i){
var new_extent = snap_to_bin(d.brush.extent());
if (new_extent[0] === 1){
new_extent[0] -=1;
}
data_filter.add(metric, new_extent);
});
if (data_filter.has(metric)){
var details = data_filter.get(metric);
brush.extent(snap_to_bin([details[0]+(details[0]===0?1:0), /* cant have 0 lower detail beca use of log scales */
details[1]
])
);
}
return {formatter: formatter, filterable: metric, axis:XAxis, path:path, thresholds:thresholds, xscale:axisscale, yscale:Y, histogram:histogram, bin_width:bin_width, brush:brush};
};
var construct_more_info_url = function(unit, template){
/* returns a string with the appropriate data fields inserted into the template */
for (var key in unit){
template = template.replace("{{{"+key+"}}}", unit[key], 'g')
}
return template;
};
/* provided formatters user can specify in config */
var datasize_formatter = function (value) {
value = Math.round(value)
var endings = ["B", "KB", "MB", "GB", "TB", "PB", "EB"],
base = 1024,
magnitude;
for (magnitude=0; magnitude<endings.length; magnitude++){
if (value < base){
return value+endings[magnitude];
}
value = Math.round(value/base);
}
};
var duration_formatter = function(value){
value = Math.round(value)
var ranges = [["ms", 1000], ["s", 60], ["m", 60], ["hr", 24], ["days", 7], ["weeks", 52]],
i;
for (i=0; i < ranges.length; i++){
var metric = ranges[i][0],
bound = ranges[i][1];
if (value < bound){
return (Math.round(value * 10) / 10 )+metric;
}
value /= bound;
}
return null;
};
/* State changers. */
var FilterHolder = function(data, filterables, metric, aggreg){
var that = this;
var on_change_func;
var _filterables = filterables;
var cached_types = {};
var _data = data;
var _filters = {}
var _metric = metric;
var _aggreg = aggreg;
this.length = function(){
return _data.length;
};
this.set_aggregation = function (aggreg){
if (_aggreg !== aggreg){
_aggreg = aggreg;
change();
}
};
this.aggregation = function(){
return _aggreg;
};
this.set_metric = function(metric){
if (_metric !== metric){
_metric = metric;
change();
}
};
this.metric = function(){
return _metric;
};
this.format = function(key, value){
return that.formatter(key)(value);
};
this.formatter = function(key){
return get(_filterables[key], 'format', identity);
};
this.is_aggregable = function(key){
return get(_filterables[key], 'aggregable', false);
};
this.human = function(key){
return get(_filterables[key], 'human', key);
};
this.scale = function(key){
if (cached_types[key]){
return get(cached_types[key], 'scale', 'null');
}
return get(_filterables[key], 'scale', 'null');
};
this.type = function(key){
if (! _filterables[key]){
if (! cached_types[key]) {
/** look to see if there is continuous looking data.
cache that result
if data is continious, then also guess that the scale is linear
*/
var num = 0.0;
var key_data = pull_out_field(_data, key);
key_data.forEach(function(n){
if (is_numeric(n)){
num++;
}
});
if ((num / key_data.length) > 0.8){
cached_types[key] = {type: "continuous", scale: d3.scale.linear};
} else {
cached_types[key] = {type: "discrete"};
}
}
return cached_types[key].type;
}
return get(_filterables[key], 'type', 'discrete');
};
var change = function(){
/* call the bound callback */
if (is_function(on_change_func)){
on_change_func();
}
};
this.add = function(key, details){
/* short circuit if nothing to do */
if (key in _filters && _filters[key].details === details){ return null;}
if (is_array(details) && details[0] === details[1]){
details[1]+=1;
}
/* calculate the order of the new filter and add it */
var insert_order = (key in _filters)?_filters[key].order:d3.entries(_filters).length;
_filters[key] = {details:details, order:insert_order};
change(); /* callback */
};
this.del = function(key){
/* delete the filter and maintain the ordering */
var deleted_order = _filters[key].order;
delete _filters[key];
for (var filter in _filters){
if (_filters[filter].order > deleted_order){
_filters[filter].order -= 1;
}
}
change(); /* callback */
};
this.on_change = function(func){
on_change_func = func;
return this;
};
this.apply_upto = function(filter, include_last){
var filters = d3.entries(_filters);
var highest_order = _filters[filter].order;
var applicable_filters = filters.filter(function(f){
if (include_last){
return f.value.order <= highest_order;
}else{
return f.value.order < highest_order;
}
});
var old_filters = _filters;
/* apply all those filters */
_filters = {};
applicable_filters.forEach(function(f){_filters[f.key] = f.value;});
var filtered_dataset = that.apply();
_filters = old_filters;
return filtered_dataset
}
this.apply = function(dataset, extra_filters){
/*
* dataset expects an array of objects, each object is a data item
* filters expects an object with keys "discrete, continuous",
* each key will then have filters:
* discrete: value of filter
* continuous : [min,max]
*/
var filters_to_use = d3.entries(_filters).concat(d3.entries(extra_filters));
return _data.filter(function(item){
/* each item needs to match all discrete and continuous filters */
return filters_to_use.every(function(filter){
if (that.type(filter.key) === "discrete"){
if (filter.value.match === "contains"){
return String(item[filter.key]).contains(filter.value.details);
}
return String(item[filter.key]) === String(filter.value.details); /* javascript doesn't like integer keys... */
}else{
var item_value = item[filter.key];
return ( item_value >= filter.value.details[0] &&
item_value <= filter.value.details[1]);
}
});
});
};
this.match = function(key, detail){
if (!that.has(key)){return false;}
if (that.type(key) === "discrete"){
return detail === _filters[key].details;
} else if (that.type(key) === "continuous"){
return (detail >= _filters[key].details[0] &&
detail <= _filters[key].details[1]);
}
}
this.has = function(key, details){
if (typeof details === "undefined"){
return key in _filters;
}
if (is_array(details)){
return (key in _filters &&
details[0] === _filters[key].details[0] &&
details[1] === _filters[key].details[1])
} else {
return (key in _filters && details == _filters[key].details);
}
};
this.get = function(key){
if (!that.has(key)){return null;}
return _filters[key].details
}
this.filterables = function(){
return d3.keys(_filterables).filter(function(key){return that.type(key) === "continuous" || that.type(key) === "discrete";});
};
this.filters = function(){
return d3.keys(_filters);
};
this.fields = function(){
return d3.keys(_data[0]);
};
this.metrics = function(){
return d3.keys(_filterables).filter(function(key){
return that.type(key) === "continuous";
});
};
};
/* The meat. Renders things in a hierarchical way. infro.js */
var render_visualisation = throttle(function(){
/* The sizes */
cached_rows = null;
var viewport = function(){
var e = window
, a = 'inner';
if ( !( 'innerWidth' in window ) ) {
a = 'client';
e = document.documentElement || document.body;
}
return { width : e[ a+'Width' ] , height : e[ a+'Height' ] }
}
var width = Number(viewport().width)-10;
var height = Number(viewport().height)-10;
if (width<100 || height < 100){
/* if the visualisation isn't visible everything breaks */
return null;
}
/* where to put everything */
var div = d3.select("#"+user_config.root_div)
.style("width", width+"px")
.style("position", "absolute");
var total = data_filter.filterables().length;
var num_filters = data_filter.filters().length;
var tab_height = d3.max([20, d3.min([44, height/20])]);
var content_height = height - tab_height-30;
var filters_portion = ((num_filters/total)*(1/2));
var display_portion = 1 - filters_portion;
var display_height = content_height*display_portion;
var filters_height = content_height*filters_portion;
var content_group = data_bind(div, "div", "content", arrentity)
.style("width", width+"px")
.style("height", display_height+"px")
.style("top", (filters_height+tab_height)+30+"px");
var tab_group = data_bind(div, "div", "tab", arrentity)
.style("width", width+"px")
.style("height", tab_height+"px")
.style("top", (filters_height)+30+"px")
.classed("tab_bar", "true")
.call(render_tab_bar, /* tab stuff: */ content_group);
/* rendered last for overlapping reasons */
var filters_group = data_bind(div, "div", "filters", arrentity)
.style("width", width+"px")
.style("height", filters_height+"px")
.style("top", "30px")
.call(render_filters);
div.call(options.render)
/*
var logo = data_bind(div, "img", "logo", arrentity)
.attr("src", "images/titlebar_logo.png")
.style("left", width-150+"px"); */
}, 300);
var render_options = function(hidden_group, open){
var options = [ {callable:selects.aggreg.render, top: 0},
{callable:selects.metric.render, top: 56},
{callable:selects[display_units].render, top: 112}];
var labels = [ {text:"Aggregation type:", top: 0},
{text:"Aggregation field:", top: 56},
{text:"Visible fields:", top: 112}];
data_bind(hidden_group, "div", "option_label", labels)
.style("left", "50px")
.style("height", "50px")
.style("top", function(option){return option.top+10+"px";})
.text(pluck("text"));
data_bind(hidden_group, "div", "selects", options)
.style("left", "50px")
.style("height", "50px")
.style("top", function(option){return option.top+12+16+"px";})
.each(function(option, i){d3.select(this).call(option.callable);});
var sentence = data_bind(hidden_group, "div", "sentence", arrentity)
.style("top", hidden_group.height()-25+"px")
.style("width", hidden_group.width()-20+"px")
.style("left", 10+"px")
.style("height", "25px")
.style("font-size", "14px")
.html("Ordering by <span class='hl'>" + metric_aggreg() +
"</span> of the " + user_config.unit + " in <span class='hl'>"+selects[display_units].current.length+'</span> fields.');
var src = open?"up":"down";
var image = data_bind(hidden_group, "img", "img1", arrentity)
.style("top", hidden_group.height()-27+"px")
.style("width", "20px")
.style("left", hidden_group.width()-45+"px")
.style("height", "20px")
.attr("src", "images/button-"+src+".png"); // TODO: use css
var image = data_bind(hidden_group, "img", "img2", arrentity)
.style("top", 10+"px")
.style("left", 10+"px")
.attr("src", "images/icon-config.png"); // TODO: use css
};
/* hacky helper for column position */
var col = function(key, i){
var font_size = 12;
var columns_to_show = selects[display_units].current.slice();
if (user_config.more_info_url){
columns_to_show.unshift(more_info_url);
}
var cumu = 0;
var cumu_lengths = columns_to_show.map(function(col){
var returnee = cumu;
cumu += column_lengths[col]+1;
return returnee;
});
return {left:(cumu_lengths[i]*(font_size+3)*0.6+10)+10,
width:(column_lengths[key]*(font_size+3)*0.6+10),
show: columns_to_show,
cumu: cumu
}
};
var render_units = function(units_group_wrapper){
var ug_margin = 20;
var units_group = data_bind(units_group_wrapper, "div", "display_units_tab", arrentity)
.style("width", units_group_wrapper.width()-(ug_margin*2)+"px")
.style("height", units_group_wrapper.height()-(ug_margin*2)+"px")
.style("left", ug_margin+"px")
.style("top", ug_margin+"px");
var font_size = 12;
var row_height = font_size * 1.5;
var vertical_scroll_area = data_bind(units_group, "div", "vscroll", arrentity)
.style("width", units_group.width()-20+"px")
.style("height", (units_group.height()-(row_height*3))-20+"px")
.style("top", (row_height*2.5)+20+"px");
var render_units_scroll = function(){
vertical_scroll_area.call(render_scroll_area, render_units_data, {horizontal:[headers]}, true);
data_bind(header_cols, "div", "arrows", arrentity)
.classed("down_arrow", function(d){
return units_sort === d && units_sort_order === d3.descending;
})
.classed("up_arrow", function(d){
return units_sort === d && units_sort_order === d3.ascending;
})
.style("top", (font_size+10)/4+"px");
};
var header_wrapper = data_bind(units_group, "div", "twrapper", arrentity)
.style("top", (row_height*1.5)+20+"px");
var headers = data_bind(header_wrapper, "div", "titles", [col().show])
.style("height", font_size+10+"px");
var header_cols = data_bind(headers, "div", "units_title", identity);
header_cols
.style("left", function(d,i){return col(d, i).left+"px";})
.style("width", function(d,i){return col(d, i).width+"px";})
.text(function(key){return key !== more_info_url? data_filter.human(key):"More";})
.on("click", function(d,i){
if (d !== more_info_url){
units_sort = d;
units_sort_order = (units_sort_order===d3.ascending)?d3.descending:d3.ascending;
cached_rows = null;
render_units_scroll()
}
})
.style("cursor", "pointer")
.style("font-size", font_size+5+"px");
render_units_scroll()
/* Create the search box */
var search_box = data_bind(units_group, "input", "searchy", function(d){return [{default_text: "Search..."}];})
.attr("placeholder", function(d){return d.default_text;})
.style("width", 250+"px")
.style("left", 20+"px")
.style("top", 15+"px")
.style("height", (row_height)+"px")
.on("keyup", function(d,i){
var text;
if (d3.event.target){
text = d3.event.target.value;
}else{
text = d3.event.srcElement.value;
}
if (text !== d.default_text && text !== ""){
if (units_search !== text){
units_search = text;
render_units_scroll()
}
} else {
if (units_search !== null){
units_search = null;
render_units_scroll()
}
}
});
};
var render_units_data = function(group){
var scroll_top = group[0].parentNode.scrollTop;
var units_width = group.width();
var font_size = 12;
var row_height = font_size * 1.5;
/* we cache the rows in a global so that we don't have to recompute everything whenm we are simply scrolling... */
if (cached_rows === null){
cached_rows = filter_sort_format_data(col().show, units_sort, units_sort_order);
}
var formatted_rows = cached_rows;
/* search the data */
var searched_rows = units_search===null?formatted_rows:
formatted_rows.filter(function(row){
return row.some(function(col){
return String(col.formatted_value.toLowerCase()).contains(units_search.toLowerCase());
})
});
/* Only render visible rows.
We go through this song and dance of only rendering visible rows, because firefox
is orders of magnitude slower than chrome/ie at creating dom elements... */
var space_available = d3.select(group[0].parentNode).height();
var visible_rows = space_available/row_height;
var first_row = d3.max([0, Math.floor((scroll_top/row_height)-visible_rows/3)])
var last_row = d3.min([searched_rows.length, Math.ceil((scroll_top/row_height)+visible_rows*(4/3))])
group.style("height", ((searched_rows.length+2)*row_height)+"px");
group.style("width", ((col().cumu*(font_size+3)*0.6)-20)+"px");
var rows = data_bind(group, "div", "units_row", searched_rows.slice(first_row,last_row), identity)
.style("top", function(d,i){ return ((i+first_row)*row_height)+"px";})
.classed("even", function(d,i){return (i+first_row)%2===0;});
var cols = data_bind(rows, "div", "units_col", identity)
.style("left", function(d,i){return col(d,i).left+"px";})
.style("width", function(d,i){return col(d.key, i).width+"px";})
.text(pluck("formatted_value"))
.on("click", function(d,i){
if (d.key === more_info_url){
window.open(d.value, d.value);
}else{
/* if continuous then make continuous */
if (data_filter.type(d.key) === "continuous" ){
data_filter.add(d.key, [d.value, d.value]);
}else{
data_filter.add(d.key, d.value);
}
}
})
.style("font-size", font_size+"px")
.style("user-select", "none")
.style("cursor", "pointer")
.classed("searched_col", function(c){return units_search !== null && String(c.formatted_value).toLowerCase().contains(units_search.toLowerCase())});
};
var render_filters = function(filters_group){
var width_pad = 40;
var filters_width = filters_group.width()-width_pad;
var filters_height = filters_group.height();
var filters = data_filter.filters();
var num_filters = filters.length;
var padding = 5;
var filter_height = (filters_height/(num_filters))-padding
var min_key_chars = d3.max(filters, function(key){return data_filter.human(key).length;});
var font_size = get_font_size(filters_width/2, filter_height, 'filters');
var filter_rows = data_bind(filters_group, "div", "filter_row", filters, function(key){return key+"visrow";})
.style("top", function(d,i){return ((i)*(filter_height+padding))+"px";})
.style("width", filters_width+"px")
.style("left", (width_pad/2)+"px")
.style("height", filter_height+"px");
var set_constants = function(selection){
selection
.style("font-size", font_size+"px")
.classed("filter_text", true)
.style("top", (filter_height - font_size)/2+"px");
}
var vis_groups = data_bind(filter_rows, "div", "filter_vis", arrentity)
.style("left", (filters_width/2)-filter_height+"px")
.style("width", filters_width/2+"px")
.classed("discrete", function(key){ return data_filter.type(key) === "discrete";})
.classed("continuous", function(key){ return data_filter.type(key)=== "continuous";})
.style("height", filter_height+"px");
filter_rows.selectAll("div.continuous")
.call(render_continuous_post_filter_groups)
var percentages = data_bind(filter_rows, "div", "filter_percent", arrentity, identity)
.style("left", "5px")
.text(function(filter){
var filtered_dataset = data_filter.apply_upto(filter, true);
/* work out the proportion of data items left */
var proportion_left = filtered_dataset.length/data_filter.length();
/* return it as a percentage */
return d3.format(".2%")(proportion_left);
})
.call(set_constants)
.on("mouseover", function(){
render_hover(d3.event.clientX, d3.event.clientY+20, "The percentage of "+user_config.unit+ " remaining after applying this filter")
})
.on("mouseout", function(){
render_hover("clear");
});
var titles = data_bind(filter_rows, "div", "filter_title", arrentity, identity)
.text(data_filter.human)
.call(set_constants)
.style("left",(font_size*4.5)+5+"px");
var values = data_bind(filter_rows, "div", "filter_value", arrentity, identity)
.text(function(key){
if (data_filter.type(key) == "discrete"){
return data_filter.get(key);
} else {
return data_filter.get(key).map(data_filter.formatter(key)).join(" - ");
}
})
.call(set_constants)
.style("font-size", font_size+"px")//d3.max([font_size-10,6])+"px")
.style("left", (font_size*(min_key_chars*(3/5)+5))+5+"px");
var delete_button = data_bind(filter_rows, "img", "del_but", arrentity)
.attr("src", "images/state-error.png") // TODO: use css
.style("width", (filter_height / 2) +"px")
.style("height", (filter_height / 2) +"px")
.style("left", filters_width - ( filter_height *(3/4) ) + "px")
.style("top", filter_height *(1/4) + "px")
.style("cursor", "pointer")
.on("click", data_filter.del);
var data;
if (filters.length > 0){
data = [1]
}else{
data = []
}
data_bind(filters_group, "div", "section_label", data)