-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathchart-lib.js
1932 lines (1722 loc) · 69.4 KB
/
chart-lib.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
({
requires: [
{ 'import-type': 'builtin', 'name': 'image-lib' },
],
nativeRequires: [
'pyret-base/js/js-numbers',
'google-charts',
],
provides: {
values: {
'pie-chart': "tany",
'bar-chart': "tany",
'multi-bar-chart': "tany",
'histogram': "tany",
'box-plot': "tany",
'plot': "tany",
}
},
theModule: function (RUNTIME, NAMESPACE, uri, IMAGELIB, jsnums , google) {
'use strict';
// Load google library via editor.html to avoid loading issues
function notImp(name) {
return RUNTIME.makeFunction(() => {
throw new RUNTIME.makeMessageException(name + " not available.")
})
}
if(!google.charts) {
return RUNTIME.makeModuleReturn(
{
'pie-chart': notImp('pie-chart'),
'bar-chart': notImp('bar-chart'),
'multi-bar-chart': notImp('multi-bar-chart'),
'histogram': notImp('histogram'),
'box-plot': notImp('box-plot'),
'plot': notImp('plot'),
},
{ }
)
}
//const google = _google.google;
const isTrue = RUNTIME.isPyretTrue;
const get = RUNTIME.getField;
const toFixnum = jsnums.toFixnum;
const cases = RUNTIME.ffi.cases;
var IMAGE = get(IMAGELIB, "internal");
const ann = function(name, pred) {
return RUNTIME.makePrimitiveAnn(name, pred);
};
var checkListWith = function(checker) {
return function(val) {
if (!RUNTIME.ffi.isList(val)) return false;
var cur = val;
var gf = RUNTIME.getField;
while (RUNTIME.unwrap(RUNTIME.ffi.isLink(cur))) {
var f = gf(cur, "first");
if (!checker(f)) {
return false;
}
cur = gf(cur, "rest");
}
return true;
}
}
var checkOptionWith = function(checker) {
return function(val) {
if (!(RUNTIME.ffi.isNone(val) || RUNTIME.ffi.isSome(val))) return false;
var gf = RUNTIME.getField;
if (RUNTIME.unwrap(RUNTIME.ffi.isSome(val))) {
var f = gf(val, "value");
if (!checker(f)) {
return false;
}
}
return true;
}
}
google.charts.load('current', {'packages' : ['corechart']});
//////////////////////////////////////////////////////////////////////////////
function getPrettyNumToStringDigits(d) {
// this accepts Pyret num
return n =>
jsnums.toStringDigits(n, d, RUNTIME.NumberErrbacks).replace(/\.?0*$/, '');
}
const prettyNumToStringDigits5 = getPrettyNumToStringDigits(5);
function convertColor(v) {
function p(pred, name) {
return val => {
RUNTIME.makeCheckType(pred, name)(val);
return val;
};
}
const colorDb = IMAGE.colorDb;
const _checkColor = p(IMAGE.isColorOrColorString, 'Color');
function checkColor(val) {
let aColor = _checkColor(val);
if (colorDb.get(aColor)) {
aColor = colorDb.get(aColor);
}
return aColor;
}
function rgb2hex(rgb){
// From http://jsfiddle.net/Mottie/xcqpF/1/light/
rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
return (rgb && rgb.length === 4) ? "#" +
("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
("0" + parseInt(rgb[3],10).toString(16)).slice(-2) : '';
}
return rgb2hex(IMAGE.colorString(checkColor(v)));
}
function convertPointer(p) {
return {v: toFixnum(get(p, 'value')) , f: get(p, 'label')}
}
//////////////////////////////////////////////////////////////////////////////
function numSignificantDigits(n) {
let ns = n.toString();
let fracPart = ns.replace(/^.*\./, '');
let fracPartLength = fracPart.length;
if (fracPartLength === ns.length) {
return 0;
}
return fracPartLength;
}
function fourSig(n, targetSd = 4) {
if (targetSd > 4) { targetSd = 4; }
let sd = numSignificantDigits(n);
if (sd === 0) { return n; }
if (sd > targetSd) { n = n.toFixed(targetSd); }
let ns = n.toString();
ns = ns.replace(/0*$/, '');
return Number(ns);
}
function saneSubtract(m, n) {
let sd = Math.max(numSignificantDigits(m), numSignificantDigits(n));
return fourSig(m - n, sd);
}
//////////////////////////////////////////////////////////////////////////////
function getNewWindow(xMinC, xMaxC, yMinC, yMaxC, numSamplesC) {
return cases(RUNTIME.ffi.isOption, 'Option',
RUNTIME.string_to_number(xMinC.val()), {
none: function () {
xMinC.addClass('error-bg');
xMinC.removeClass('ok-bg');
return null;
},
some: function (xMinVal) {
xMinC.removeClass('error-bg');
xMinC.addClass('ok-bg');
return cases(RUNTIME.ffi.isOption, 'Option',
RUNTIME.string_to_number(xMaxC.val()), {
none: function () {
xMaxC.addClass('error-bg');
xMaxC.removeClass('ok-bg');
return null;
},
some: function (xMaxVal) {
xMaxC.removeClass('error-bg');
xMaxC.addClass('ok-bg');
if (jsnums.greaterThanOrEqual(xMinVal, xMaxVal,
RUNTIME.NumberErrbacks)) {
xMinC.addClass('error-bg');
xMaxC.addClass('error-bg');
xMinC.removeClass('ok-bg');
xMaxC.removeClass('ok-bg');
return null;
}
return cases(RUNTIME.ffi.isOption, 'Option',
RUNTIME.string_to_number(yMinC.val()), {
none: function () {
yMinC.addClass('error-bg');
yMinC.removeClass('ok-bg');
return null;
},
some: function (yMinVal) {
yMinC.removeClass('error-bg');
yMinC.addClass('ok-bg');
return cases(RUNTIME.ffi.isOption, 'Option',
RUNTIME.string_to_number(yMaxC.val()), {
none: function () {
yMaxC.addClass('error-bg');
yMaxC.removeClass('ok-bg');
return null;
},
some: function (yMaxVal) {
yMaxC.removeClass('error-bg');
yMaxC.addClass('ok-bg');
if (jsnums.greaterThanOrEqual(xMinVal, xMaxVal,
RUNTIME.NumberErrbacks)) {
yMinC.addClass('error-bg');
yMaxC.addClass('error-bg');
yMinC.removeClass('ok-bg');
yMaxC.removeClass('ok-bg');
return null;
}
return cases(RUNTIME.ffi.isOption, 'Option',
RUNTIME.string_to_number(numSamplesC.val()), {
none: function () {
numSamplesC.addClass('error-bg');
numSamplesC.removeClass('ok-bg');
return null;
},
some: function (numSamplesVal) {
numSamplesC.removeClass('error-bg');
numSamplesC.addClass('ok-bg');
if (!isTrue(RUNTIME.num_is_integer(numSamplesVal)) ||
jsnums.lessThanOrEqual(numSamplesVal, 1,
RUNTIME.NumberErrbacks)) {
numSamplesC.addClass('error-bg');
numSamplesC.removeClass('ok-bg');
return null;
}
return {
'x-min': RUNTIME.ffi.makeSome(xMinVal),
'x-max': RUNTIME.ffi.makeSome(xMaxVal),
'y-min': RUNTIME.ffi.makeSome(yMinVal),
'y-max': RUNTIME.ffi.makeSome(yMaxVal),
'num-samples': numSamplesVal
};
}
});
}
});
}
});
}
});
}
});
}
//////////////////////////////////////////////////////////////////////////////
/**
* Adds multiple columns with the given properties and values after data
* columns
*
* For example, if given:
* colProperties:
* {type: 'string', role: 'style'}
* colValues:
* [
* [['red', 'black'], ['white', 'blue'], ['green', 'purple']],
* []
* ]
* addNSpecialColumns will add 2 style columns after the first data column
* and no columns after the second data column.
*
* The number of columns added after a particular data column do not have to
* agree. It is possible to add one special value on one row and two
* special values on another row.
*
* https://jsfiddle.net/eyanje/u83kaf92/
*
* @param {DataTable} table a table to expand
* @param {object} colProperties an object specifying column properties
* @param {Array<Array<*>>>} colValues rows of groups of values to insert
*/
function addNSpecialColumns(table, colProperties, colValues) {
let dataColNums = [];
let nDataCols;
let groupWidths;
for (let i = 1; i < table.getNumberOfColumns(); i++) {
const role = table.getColumnRole(i);
if (role === '' || role === 'data') {
dataColNums.push(i);
}
}
nDataCols = dataColNums.length;
// Check column count
// Should never run -- Pyret checks all column counts properly
// This should be somewhat caught in the try-catch around setup(restarter),
// unless it's been moved
colValues.forEach((row, rowN) => {
if (row.length !== nDataCols) {
throw new Error(`Incorrect column count in row ${rowN}.`
+ ` Expected ${nDataCols}, given ${row.length}.`);
}
});
// Tally columns needed for each group
groupWidths = dataColNums.map(() => 0);
colValues.forEach(row => {
row.forEach((group, groupN) => {
groupWidths[groupN] = Math.max(group.length, groupWidths[groupN]);
});
});
// Add columns in reverse order
for (let groupIndex = nDataCols - 1; groupIndex >= 0; groupIndex--) {
for (let i = 0; i < groupWidths[groupIndex]; i++) {
table.insertColumn(dataColNums[groupIndex] + 1, colProperties);
}
}
// Adjust dataColNums to match expanded table
let sum = 0;
dataColNums.forEach((dataColNum, i) => {
dataColNums[i] += sum;
sum += groupWidths[i];
});
// Add columns in reverse order to avoid extra calculations
colValues.forEach((row, rowN) => {
row.forEach((group, groupN) => {
group.forEach((val, i) => {
table.setValue(rowN, dataColNums[groupN] + i + 1, val);
});
})
});
}
/**
* Adds columns with the given properties and values after data columns
*
* For example, you may use this function to add columns with properties
* {type: 'string', role: 'style'} and values
* [['red', 'black'] ['white', 'blue'], ['green', 'purple']], to add
* two style columns to a table with 3 rows and 2 columns.
*
* @param {DataTable} table a table to expand
* @param {object} colProperties an object specifying column properties
* @param {Array<Array<*>>>} colValues rows of values to insert
*/
function addSpecialColumns(table, colProperties, colValues) {
addNSpecialColumns(table, colProperties,
colValues.map(r => r.map(c => [c])));
}
function addAnnotations(table, rawData) {
const rawAnnotations = get(rawData, 'annotations').map(row =>
row.map(col =>
cases(RUNTIME.ffi.isOption, 'Option', col, {
none: function () {},
some: function (annotation) { return annotation; }
})
)
);
const colProperties = { type: 'string', role: 'annotation' };
addSpecialColumns(table, colProperties, rawAnnotations);
}
function addIntervals(table, rawData) {
const colProperties = {type: 'number', role: 'interval'};
addNSpecialColumns(table, colProperties, get(rawData, 'intervals'));
}
function selectMultipleMutator(options, globalOptions, _) {
const multiple = get(globalOptions, 'multiple');
if (multiple) {
$.extend(options, {selectionMode: 'multiple'});
} else {
$.extend(options, {selectionMode: 'single'});
}
}
function backgroundMutator(options, globalOptions, _) {
const backgroundColor = cases(RUNTIME.ffi.isOption, 'Option', get(globalOptions, 'backgroundColor'), {
none: function () {
return 'transparent';
},
some: function (color) {
return convertColor(color);
}
});
const borderColor = cases(RUNTIME.ffi.isOption, 'Option', get(globalOptions, 'borderColor'), {
none: function () {
return '#666';
},
some: function (color) {
return convertColor(color);
}
});
const borderSize = toFixnum(get(globalOptions, 'borderSize'))
$.extend(options, {
backgroundColor: {
fill: backgroundColor,
strokeWidth: borderSize,
stroke: borderColor,
}
});
}
function axesNameMutator(options, globalOptions, _) {
const hAxis = ('hAxis' in options) ? options.hAxis : {};
const vAxis = ('vAxis' in options) ? options.vAxis : {};
hAxis.title = get(globalOptions, 'x-axis');
vAxis.title = get(globalOptions, 'y-axis');
$.extend(options, {hAxis: hAxis, vAxis: vAxis});
}
function gridlinesMutator(options, globalOptions, _) {
const hAxis = ('hAxis' in options) ? options.hAxis : {};
const vAxis = ('vAxis' in options) ? options.vAxis : {};
const gridlineColor = cases(RUNTIME.ffi.isOption, 'Option', get(globalOptions, 'gridlineColor'), {
none: function () {
return '#aaa';
},
some: function (color) {
return convertColor(color);
}
});
const minorGridlineColor = cases(RUNTIME.ffi.isOption, 'Option', get(globalOptions, 'minorGridlineColor'), {
none: function () {
return '#ddd';
},
some: function (color) {
return convertColor(color);
}
});
const minorGridlineMinspacing = toFixnum(get(globalOptions, 'minorGridlineMinspacing'))
hAxis.gridlines = {color: gridlineColor};
vAxis.gridlines = {color: gridlineColor};
cases(RUNTIME.ffi.isOption, 'Option', get(globalOptions, 'gridlineMinspacing'), {
none: function () {
hAxis.gridlines.count = 5;
},
some: function (minspacing) {
hAxis.gridlines.minSpacing = toFixnum(minspacing);
}
});
if (get(globalOptions, 'show-minor-grid-lines')) {
hAxis.minorGridlines = {color: minorGridlineColor, minSpacing: minorGridlineMinspacing};
vAxis.minorGridlines = {color: minorGridlineColor, minSpacing: minorGridlineMinspacing};
} else {
hAxis.minorGridlines = {count: 0};
vAxis.minorGridlines = {count: 0};
}
$.extend(options, {hAxis: hAxis, vAxis: vAxis});
}
function yAxisRangeMutator(options, globalOptions, _) {
const vAxis = ('vAxis' in options) ? options.vAxis : {};
const viewWindow = ('viewWindow' in vAxis) ? vAxis.viewWindow : {};
cases(RUNTIME.ffi.isOption, 'Option', get(globalOptions, 'y-min'), {
none: function () {},
some: function (minValue) {
const v = toFixnum(minValue);
vAxis.minValue = v;
viewWindow.min = v;
}
});
cases(RUNTIME.ffi.isOption, 'Option', get(globalOptions, 'y-max'), {
none: function () {},
some: function (maxValue) {
const v = toFixnum(maxValue);
vAxis.maxValue = v;
viewWindow.max = v;
}
});
vAxis.viewWindow = viewWindow;
$.extend(options, {vAxis: vAxis});
}
function xAxisRangeMutator(options, globalOptions, _) {
const hAxis = ('hAxis' in options) ? options.hAxis : {};
const viewWindow = ('viewWindow' in hAxis) ? hAxis.viewWindow : {};
const minValue = get(globalOptions, 'x-min');
const maxValue = get(globalOptions, 'x-max');
cases(RUNTIME.ffi.isOption, 'Option', minValue, {
none: function () {},
some: function (realMinValue) {
hAxis.minValue = toFixnum(realMinValue);
viewWindow.min = toFixnum(realMinValue);
}
});
cases(RUNTIME.ffi.isOption, 'Option', maxValue, {
none: function () {},
some: function (realMaxValue) {
hAxis.maxValue = toFixnum(realMaxValue);
viewWindow.max = toFixnum(realMaxValue);
}
});
hAxis.viewWindow = viewWindow;
$.extend(options, {hAxis: hAxis});
}
//////////////////////////////////////////////////////////////////////////////
// Default Google Chart Colors for sequential series (Like Multi Bar Charts and Pie Charts) from
// http://there4.io/2012/05/02/google-chart-color-list/
const default_colors = ['#3366CC', '#DC3912', '#FF9900', '#109618', '#990099',
'#3B3EAC', '#0099C6', '#DD4477', '#66AA00', '#B82E2E',
'#316395', '#994499', '#22AA99', '#AAAA11', '#6633CC',
'#E67300', '#8B0707', '#329262', '#5574A6', '#3B3EAC']
function pieChart(globalOptions, rawData) {
const table = get(rawData, 'tab');
const default_colors = ['#3366CC', '#DC3912', '#FF9900', '#109618', '#990099',
'#3B3EAC', '#0099C6', '#DD4477', '#66AA00', '#B82E2E',
'#316395', '#994499', '#22AA99', '#AAAA11', '#6633CC',
'#E67300', '#8B0707', '#329262', '#5574A6', '#3B3EAC']
var colors_list = get_colors_list(rawData);
if (colors_list.length < default_colors.length) {
default_colors.splice(0, colors_list.length, ...colors_list);
colors_list = default_colors;
colors_list = colors_list.slice(0, table.length);
}
const new_colors_list = table.map(row => colors_list[row[3]])
colors_list = new_colors_list
const threeD = get(rawData, 'threeD');
const piehole = toFixnum(get(rawData, 'piehole'));
const startingAngle = toFixnum(get(rawData, 'startingAngle'));
const collapseThreshold = toFixnum(get(rawData, 'collapseThreshold'));
// ASSERT: if we're using custom images, the third column will be an object
const hasImage = typeof table[0][3] == 'object';
const data = new google.visualization.DataTable();
data.addColumn('string', 'Label');
data.addColumn('number', 'Value');
data.addRows(table.map(row => [row[0], toFixnum(row[1])]));
return {
data: data,
options: {
slices: table.map((row, i) => ({
color: hasImage? "transparent" : colors_list[i],
offset: toFixnum(row[2])
})),
legend: {
alignment: 'end'
},
is3D: threeD,
pieHole: piehole,
pieStartAngle: startingAngle,
sliceVisibilityThreshold: collapseThreshold,
},
chartType: google.visualization.PieChart,
onExit: defaultImageReturn,
mutators: [backgroundMutator],
overlay: (overlay, restarter, chart, container) => {
// If we don't have images, our work is done!
if(!hasImage) { return; }
// if custom images are defined, use the image at that location
// and overlay it atop each dot
google.visualization.events.addListener(chart, 'ready', function () {
// HACK(Emmanuel):
// The only way to hijack marker events is to walk the DOM here
// If Google changes the DOM, these lines will likely break
const svgRoot = chart.container.querySelector('svg');
// The order of SVG slices is *not* the order of the rows in the table!!
// - 1 or 2 slices: drawn in reverse order
// - More than 2 slices: the first row in the table is the first SVG
// slice, but the rest are in reverse order
let slices;
if(table.length <= 2) {
slices = Array.prototype.slice.call(svgRoot.children, 2, -1).reverse();
} else {
slices = Array.prototype.slice.call(svgRoot.children, 3, -1).reverse();
slices.unshift(svgRoot.children[2]);
}
const defs = svgRoot.children[0];
const legendImgs = svgRoot.children[1].querySelectorAll('g[column-id]');
// remove any labels that have previously been drawn
$('.__img_labels').each((idx, n) => $(n).remove());
// Render each slice under the old ones, using the image as a pattern
table.forEach((row, i) => {
const oldDot = legendImgs[i].querySelector('circle');
const oldSlice = slices[i];
// render the image to an img tag
const imgDOM = row[3].val.toDomNode();
row[3].val.render(imgDOM.getContext('2d'), 0, 0);
// make an SVGimage element from the img tag, and make it the size of the slice
const sliceBox = oldSlice.getBoundingClientRect();
const imageElt = document.createElementNS("http://www.w3.org/2000/svg", 'image');
imageElt.classList.add('__img_labels'); // tag for later garbage collection
imageElt.setAttributeNS(null, 'href', imgDOM.toDataURL());
imageElt.setAttribute('width', Math.max(sliceBox.width, sliceBox.height));
// create a pattern from that image
const patternElt = document.createElementNS("http://www.w3.org/2000/svg", 'pattern');
patternElt.setAttribute( 'x', 0);
patternElt.setAttribute( 'y', 0);
patternElt.setAttribute('width', 1);
patternElt.setAttribute('height', 1);
patternElt.setAttribute( 'id', 'pic'+i);
// make a new slice, copy elements from the old slice, and fill with the pattern
const newSlice = document.createElementNS("http://www.w3.org/2000/svg", 'path');
Object.assign(newSlice, oldSlice); // we should probably not steal *everything*...
newSlice.setAttribute( 'd', oldSlice.firstChild.getAttribute('d'));
newSlice.setAttribute( 'fill', 'url(#pic'+i+')');
// add the image to the pattern and the pattern to the defs
patternElt.appendChild(imageElt);
defs.append(patternElt);
// insert the new slice before the now-transparent old slice
oldSlice.parentNode.insertBefore(newSlice, oldSlice)
// make a new dot, then set size and position of dot to replace the old dot
const newDot = imageElt.cloneNode(true);
const radius = oldDot.r.animVal.value;
newDot.setAttribute('x', oldDot.cx.animVal.value - radius);
newDot.setAttribute('y', oldDot.cy.animVal.value - radius);
newDot.setAttribute('width', radius * 2);
newDot.setAttribute('height', radius * 2);
oldDot.parentNode.replaceChild(newDot, oldDot);
});
});
}
}
}
//////////// Bar Chart Getter Functions /////////////////
function get_colors_list(rawData) {
// Sets up the color list [Each Bar Colored Individually]
return cases(RUNTIME.ffi.isOption, 'Option', get(rawData, 'colors'), {
none: function () {
return [];
},
some: function (colors) {
return colors.map(convertColor);
}
});
}
function get_default_color(rawData) {
// Sets up the default color [Default Bar Color if not specified in color_list]
return cases(RUNTIME.ffi.isOption, 'Option', get(rawData, 'color'), {
none: function () {
return "";
},
some: function (color) {
return convertColor(color);
}
});
}
function get_pointers_list(rawData) {
// Sets up the pointers list [Coloring each group memeber/stack]
return cases(RUNTIME.ffi.isOption, 'Option', get(rawData, 'pointers'), {
none: function () {
return [];
},
some: function (pointers) {
return pointers.map(convertPointer);
}
});
}
function get_pointer_color(rawData) {
// Sets up the pointer color
return cases(RUNTIME.ffi.isOption, 'Option', get(rawData, 'pointer-color'), {
none: function () {
return 'black';
},
some: function (color) {
return convertColor(color);
}
});
}
function get_axis(rawData) {
// Sets up the calculated axis properties/data
return cases(RUNTIME.ffi.isOption, 'Option', get(rawData, 'axisdata'), {
none: function () {
return undefined;
},
some: function (axisdata) {
return {
top : toFixnum(get(axisdata, 'axisTop')),
bottom : toFixnum(get(axisdata, 'axisBottom')),
ticks : get(axisdata, 'ticks').map(convertPointer)
};
}
});
}
function get_interval_color(rawData) {
// Sets up the default interval color
return cases(RUNTIME.ffi.isOption, 'Option', get(rawData, 'default-interval-color'), {
none: function () {
return 'black';
},
some: function (color) {
return convertColor(color);
}
});
}
/////////////////////////////////////////////////////////
function barChart(globalOptions, rawData) {
// Variables and constants
const table = get(rawData, 'tab');
const horizontal = get(rawData, 'horizontal');
const axisloc = horizontal ? 'hAxes' : 'vAxes';
const data = new google.visualization.DataTable();
const colors_list = get_colors_list(rawData);
const default_color = get_default_color(rawData);
const pointers_list = get_pointers_list(rawData);
const pointer_color = get_pointer_color(rawData);
const axis = get_axis(rawData);
const interval_color = get_interval_color(rawData);
const colors_list_length = colors_list.length;
// Initializes the Columns of the data
data.addColumn('string', 'Label');
data.addColumn('number', 'Values');
data.addColumn({type: 'string', role: 'style'});
// ASSERT: if we're using custom images, there will be a 4th column
const hasImage = table[0].length == 4;
const dotChartP = get(rawData, 'dot-chart');
// Adds each row of bar data and bar_color data
table.forEach(function (row) {
let bar_color = row[2] !== undefined ? colors_list[row[2]] : default_color;
data.addRow([row[0], toFixnum(row[1]), bar_color]);
});
addAnnotations(data, rawData);
addIntervals(data, rawData);
let options = {
legend: {
position: 'none'
},
intervals: {
color : interval_color,
},
series : {
0 : { dataOpacity : (hasImage || dotChartP)? 0 : 1.0 }
}
};
options[axisloc] = {
0: {
viewWindow: { max: axis.top, min: axis.bottom },
ticks: axis.ticks
}
};
/* NOTE(John & Edward, Dec 2020):
Our goal for the part below was to add pointers (Specific Named Ticks) on another VAxis.
The Current Chart library necessitates that we assign at least one stack/bar to the
second axis in order for it to show up, and we have to fix the min/max of each axis
manually to make sure that both are consistent with each other rather than being relative
to the data. There is also a problem: When the pointers are too close to each other, one or
both of them disappear!
*/
if (pointers_list.length > 0) {
// Add and Attach Empty Data Stack/bar to 2nd axis + Color it
data.addColumn('number', 'Pointers');
options['series'] = { 1: { color: pointer_color, targetAxisIndex: 1 } };
// Update Options to include the new axis ticks consistent with the first axis
options[axisloc][1] = {
viewWindow: {
max: axis.top,
min: axis.bottom
},
gridlines: { color: pointer_color },
ticks: pointers_list,
textStyle: { color: pointer_color }
};
}
return {
data: data,
options: options,
chartType: horizontal ? google.visualization.BarChart : google.visualization.ColumnChart,
onExit: defaultImageReturn,
mutators: [backgroundMutator, axesNameMutator, yAxisRangeMutator],
overlay: (overlay, restarter, chart, container) => {
if (!hasImage && !dotChartP) return;
// if custom images are defined, use the image at that location
// and overlay it atop each dot
google.visualization.events.addListener(chart, 'ready', function () {
// HACK(Emmanuel):
// If Google changes the DOM for charts, these lines will likely break
const svgRoot = chart.container.querySelector('svg');
const rects = svgRoot.children[1].children[1].children[1].children;
$('.__img_labels').each((idx, n) => $(n).remove());
if (hasImage) {
// Render each rect above the old ones, using the image as a pattern
table.forEach(function (row, i) {
const rect = rects[i];
// make an image element for the img, from the SVG namespace
const imgDOM = row[2].val.toDomNode();
row[2].val.render(imgDOM.getContext('2d'), 0, 0);
let imageElt = document.createElementNS("http://www.w3.org/2000/svg", 'image');
imageElt.classList.add('__img_labels'); // tag for later garbage collection
imageElt.setAttributeNS(null, 'href', imgDOM.toDataURL());
// position it using the position of the corresponding rect
imageElt.setAttribute('preserveAspectRatio', 'none');
imageElt.setAttribute('x', rects[i].getAttribute('x'));
imageElt.setAttribute('y', rects[i].getAttribute('y'));
imageElt.setAttribute('width', rects[i].getAttribute('width'));
imageElt.setAttribute('height', rects[i].getAttribute('height'));
Object.assign(imageElt, rects[i]); // we should probably not steal *everything*...
svgRoot.appendChild(imageElt);
});
}
if (dotChartP) {
table.forEach(function (row, i) {
// console.log('row', i, '=', row);
const rect = rects[i];
// console.log('rect', i, '=', rect);
const num_elts = row[1];
const rect_x = Number(rect.getAttribute('x'));
const rect_y = Number(rect.getAttribute('y'));
const rect_height = Number(rect.getAttribute('height'));
const unit_height = rect_height/num_elts;
const rect_width = Number(rect.getAttribute('width'));
const rect_fill = rect.getAttribute('fill');
// const rect_fill_opacity = Number(rect.getAttribute('fill-opacity'));
// const rect_stroke = rect.getAttribute('stroke');
// const rect_stroke_width = Number(rect.getAttribute('stroke-width'));
rect.setAttribute('stroke-width', 0);
for (let j = 0; j < num_elts; j++) {
const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
circle.classList.add('__img_labels');
circle.setAttribute('r', rect_width/8);
circle.setAttribute('cx', rect_x + rect_width/2);
circle.setAttribute('cy', rect_y + (num_elts - j - 0.5)*unit_height);
circle.setAttribute('fill', rect_fill);
// circle.setAttribute('fill-opacity', rect_fill_opacity);
// circle.setAttribute('stroke', rect_stroke);
// circle.setAttribute('stroke-width', rect_stroke_width);
// console.log('adding circle elt', i, j, '=', circle);
svgRoot.appendChild(circle);
}
});
}
});
}
};
}
function multiBarChart(globalOptions, rawData) {
// Variables and Constants
const table = get(rawData, 'tab');
const legends = get(rawData, 'legends');
const horizontal = get(rawData, 'horizontal');
const axisloc = horizontal ? 'hAxes' : 'vAxes';
const data = new google.visualization.DataTable();
const pointers_list = get_pointers_list(rawData);
const pointer_color = get_pointer_color(rawData);
const axis = get_axis(rawData);
const interval_color = get_interval_color(rawData);
var colors_list = get_colors_list(rawData);
if (colors_list.length < default_colors.length) {
default_colors.splice(0, colors_list.length, ...colors_list);
colors_list = default_colors;
colors_list = colors_list.slice(0, legends.length);
}
// Initializes the Columns of the data
data.addColumn('string', 'Label');
legends.forEach(legend => data.addColumn('number', legend));
// Adds each row of bar data
data.addRows(table.map(row => [row[0]].concat(row[1].map(n => toFixnum(n)))));
addAnnotations(data, rawData);
addIntervals(data, rawData);
let options = {
isStacked: get(rawData, 'is-stacked'),
series: colors_list.map(c => ({color: c, targetAxisIndex: 0})),
legend: {
position: horizontal ? 'right' : 'top',
maxLines: data.getNumberOfColumns() - 1
},
intervals: {
color : interval_color,
}
};
options[axisloc] = {
0: {
viewWindow: { max: axis.top, min: axis.bottom },
ticks: axis.ticks
}
};
/* NOTE(John & Edward, Dec 2020):
Our goal for the part below was to add pointers (Specific Named Ticks) on another VAxis.
The Current Chart library necessitates that we assign at least one stack/bar to the
second axis in order for it to show up, and we have to fix the min/max of each axis
manually to make sure that both are consistent with each other rather than being relative
to the data. There is also a problem: When the pointers are too close to each other, one or
both of them disappear!
*/
if (pointers_list.length > 0) {
colors_list = colors_list.slice(0, legends.length);
// Add and Attach Empty Data Stack/bar to 2nd axis + Color it
data.addColumn('number', 'Pointers')
for (let i = 0; i < data.getNumberOfColumns() - 1; i++) {
if (options['series'][i] == null) {
options['series'][i] = {color: pointer_color, targetAxisIndex: 1};
}
}
// Update Options to include the new axis ticks consistent with the first axis
options[axisloc][1] = {
viewWindow: {
max: axis.top,
min: axis.bottom
},
gridlines: { color: pointer_color },
ticks: pointers_list,
textStyle: { color: pointer_color }
};
} else {
for (let i = 0; i < data.getNumberOfColumns() - 1; i++) {
if (options['series'][i] == null) {
options['series'][i] = {color: 'black', targetAxisIndex: 0};
}
}
}
return {
data: data,
options: options,
chartType: horizontal ? google.visualization.BarChart : google.visualization.ColumnChart,
onExit: defaultImageReturn,
mutators: [backgroundMutator, axesNameMutator, yAxisRangeMutator],
};
}
function boxPlot(globalOptions, rawData) {
let table = get(rawData, 'tab');
const dimension = toFixnum(get(rawData, 'height'));
// TODO: are these two supposed to be on ChartWindow or DataSeries?
const horizontal = get(rawData, 'horizontal');
const showOutliers = get(rawData, 'show-outliers');
const axisName = horizontal ? 'hAxis' : 'vAxis';
const chartType = horizontal ? google.visualization.BarChart : google.visualization.ColumnChart;
const data = new google.visualization.DataTable();
const color = cases(RUNTIME.ffi.isOption, 'Option', get(rawData, 'color'), {
none: function () {
return "#777";
},
some: function (color) {
return convertColor(color);
}
});
const intervalOptions = {