forked from dc-js/dc.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdc.js
5348 lines (4350 loc) · 162 KB
/
dc.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
/*!
* dc 1.6.0-dev
* http://nickqizhu.github.io/dc.js/
* Copyright 2012 Nick Zhu and other contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
dc = (function(){
'use strict';
/**
#### Version 1.6.0-dev
The entire dc.js library is scoped under **dc** name space. It does not introduce anything else into the global
name space.
* [Base Chart [abstract]](#base-chart)
* [Color Chart [abstract]](#color-chart)
* [Stackable Chart [abstract]](#stackable-chart)
* [Coordinate Grid Chart [abstract] < Color Chart < Base Chart](#coordinate-grid-chart)
* [Pie Chart [concrete] < Color Chart < Base Chart](#pie-chart)
* [Row Chart [concrete] < Color Chart < Base chart](#row-chart)
* [Bar Chart [concrete] < Stackable Chart < CoordinateGrid Chart](#bar-chart)
* [Line Chart [concrete] < Stackable Chart < CoordinateGrid Chart](#line-chart)
* [Composite Chart [concrete] < CoordinateGrid Chart](#composite-chart)
* [Abstract Bubble Chart [abstract] < Color Chart](#abstract-bubble-chart)
* [Bubble Chart [concrete] < Abstract Bubble Chart < CoordinateGrid Chart](#bubble-chart)
* [Bubble Overlay Chart [concrete] < Abstract Bubble Chart < Base Chart](#bubble-overlay-chart)
* [Geo Choropleth Chart [concrete] < Color Chart < Base Chart](#geo-choropleth-chart)
* [Data Count Widget [concrete] < Base Chart](#data-count)
* [Data Table Widget [concrete] < Base Chart](#data-table)
* [Legend [concrete]](#legend)
* [Listeners](#listeners)
* [Utilities](#util)
#### Function Chain
Majority of dc functions are designed to allow function chaining, meaning it will return the current chart instance
whenever it is appropriate. Therefore configuration of a chart can be written in the following style.
```js
chart.width(300)
.height(300)
.filter("sunday")
```
The API references will highlight the fact if a particular function is not chainable.
**/
var dc = {
version: "1.6.0-dev",
constants: {
CHART_CLASS: "dc-chart",
DEBUG_GROUP_CLASS: "debug",
STACK_CLASS: "stack",
DESELECTED_CLASS: "deselected",
SELECTED_CLASS: "selected",
NODE_INDEX_NAME: "__index__",
GROUP_INDEX_NAME: "__group_index__",
DEFAULT_CHART_GROUP: "__default_chart_group__",
EVENT_DELAY: 40,
NEGLIGIBLE_NUMBER: 1e-10
},
_renderlet: null
};
dc.chartRegistry = function() {
// chartGroup:string => charts:array
var _chartMap = {};
function initializeChartGroup(group) {
if (!group)
group = dc.constants.DEFAULT_CHART_GROUP;
if (!_chartMap[group])
_chartMap[group] = [];
return group;
}
return {
has: function(chart) {
for (var e in _chartMap) {
if (_chartMap[e].indexOf(chart) >= 0)
return true;
}
return false;
},
register: function(chart, group) {
group = initializeChartGroup(group);
_chartMap[group].push(chart);
},
clear: function() {
_chartMap = {};
},
list: function(group) {
group = initializeChartGroup(group);
return _chartMap[group];
}
};
}();
dc.registerChart = function(chart, group) {
dc.chartRegistry.register(chart, group);
};
dc.hasChart = function(chart) {
return dc.chartRegistry.has(chart);
};
dc.deregisterAllCharts = function() {
dc.chartRegistry.clear();
};
/**
## <a name="util" href="#util">#</a> Utilities
**/
/**
#### dc.filterAll([chartGroup])
Clear all filters on every chart within the given chart group. If the chart group is not given then only charts that
belong to the default chart group will be reset.
**/
dc.filterAll = function(group) {
var charts = dc.chartRegistry.list(group);
for (var i = 0; i < charts.length; ++i) {
charts[i].filterAll();
}
};
/**
#### dc.renderAll([chartGroup])
Re-render all charts belong to the given chart group. If the chart group is not given then only charts that belong to
the default chart group will be re-rendered.
**/
dc.renderAll = function(group) {
var charts = dc.chartRegistry.list(group);
for (var i = 0; i < charts.length; ++i) {
charts[i].render();
}
if(dc._renderlet !== null)
dc._renderlet(group);
};
/**
#### dc.redrawAll([chartGroup])
Redraw all charts belong to the given chart group. If the chart group is not given then only charts that belong to the
default chart group will be re-drawn. Redraw is different from re-render since when redrawing dc charts try to update
the graphic incrementally instead of starting from scratch.
**/
dc.redrawAll = function(group) {
var charts = dc.chartRegistry.list(group);
for (var i = 0; i < charts.length; ++i) {
charts[i].redraw();
}
if(dc._renderlet !== null)
dc._renderlet(group);
};
dc.transition = function(selections, duration, callback) {
if (duration <= 0 || duration === undefined)
return selections;
var s = selections
.transition()
.duration(duration);
if (callback instanceof Function) {
callback(s);
}
return s;
};
dc.units = {};
/**
#### dc.units.integers
This function can be used to in [Coordinate Grid Chart](#coordinate-grid-chart) to define units on x axis.
dc.units.integers is the default x unit scale used by [Coordinate Grid Chart](#coordinate-grid-chart) and should be
used when x range is a sequential of integers.
**/
dc.units.integers = function(s, e) {
return Math.abs(e - s);
};
/**
#### dc.units.ordinal
This function can be used to in [Coordinate Grid Chart](#coordinate-grid-chart) to define ordinal units on x axis.
Usually this function is used in combination with d3.scale.ordinal() on x axis.
**/
dc.units.ordinal = function(s, e, domain){
return domain;
};
/**
#### dc.units.fp.precision(precision)
This function generates xunit function in floating-point numbers with the given precision. For example if the function
is invoked with 0.001 precision then the function created will devide a range [0.5, 1.0] with 500 units.
**/
dc.units.fp = {};
dc.units.fp.precision = function(precision){
var _f = function(s, e){
var d = Math.abs((e-s)/_f.resolution);
if(dc.utils.isNegligible(d - Math.floor(d)))
return Math.floor(d);
else
return Math.ceil(d);
};
_f.resolution = precision;
return _f;
};
dc.round = {};
dc.round.floor = function(n) {
return Math.floor(n);
};
dc.round.ceil = function(n) {
return Math.ceil(n);
};
dc.round.round = function(n) {
return Math.round(n);
};
dc.override = function(obj, functionName, newFunction) {
var existingFunction = obj[functionName];
obj["_" + functionName] = existingFunction;
obj[functionName] = newFunction;
};
dc.renderlet = function(_){
if(!arguments.length) return dc._renderlet;
dc._renderlet = _;
return dc;
};
dc.instanceOfChart = function (o) {
return o instanceof Object && o.__dc_flag__;
};
dc.errors = {};
dc.errors.Exception = function(msg) {
var _msg = msg !== undefined ? msg : "Unexpected internal error";
this.message = _msg;
this.toString = function(){
return _msg;
};
};
dc.errors.InvalidStateException = function() {
dc.errors.Exception.apply(this, arguments);
};
dc.dateFormat = d3.time.format("%m/%d/%Y");
dc.printers = {};
dc.printers.filters = function (filters) {
var s = "";
for (var i = 0; i < filters.length; ++i) {
if (i > 0) s += ", ";
s += dc.printers.filter(filters[i]);
}
return s;
};
dc.printers.filter = function (filter) {
var s = "";
if (filter) {
if (filter instanceof Array) {
if (filter.length >= 2)
s = "[" + dc.utils.printSingleValue(filter[0]) + " -> " + dc.utils.printSingleValue(filter[1]) + "]";
else if (filter.length >= 1)
s = dc.utils.printSingleValue(filter[0]);
} else {
s = dc.utils.printSingleValue(filter);
}
}
return s;
};
dc.utils = {};
dc.utils.printSingleValue = function (filter) {
var s = "" + filter;
if (filter instanceof Date)
s = dc.dateFormat(filter);
else if (typeof(filter) == "string")
s = filter;
else if (dc.utils.isFloat(filter))
s = dc.utils.printSingleValue.fformat(filter);
else if (dc.utils.isInteger(filter))
s = Math.round(filter);
return s;
};
dc.utils.printSingleValue.fformat = d3.format(".2f");
dc.utils.add = function (l, r) {
if (typeof r === "string")
r = r.replace("%", "");
if (l instanceof Date) {
if (typeof r === "string") r = +r;
var d = new Date();
d.setTime(l.getTime());
d.setDate(l.getDate() + r);
return d;
} else if (typeof r === "string") {
var percentage = (+r / 100);
return l > 0 ? l * (1 + percentage) : l * (1 - percentage);
} else {
return l + r;
}
};
dc.utils.subtract = function (l, r) {
if (typeof r === "string")
r = r.replace("%", "");
if (l instanceof Date) {
if (typeof r === "string") r = +r;
var d = new Date();
d.setTime(l.getTime());
d.setDate(l.getDate() - r);
return d;
} else if (typeof r === "string") {
var percentage = (+r / 100);
return l < 0 ? l * (1 + percentage) : l * (1 - percentage);
} else {
return l - r;
}
};
dc.utils.GroupStack = function () {
var _dataLayers = [[ ]];
var _groups = [];
var _defaultAccessor;
function initializeDataLayer(i) {
if (!_dataLayers[i])
_dataLayers[i] = [];
}
this.setDataPoint = function (layerIndex, pointIndex, data) {
initializeDataLayer(layerIndex);
_dataLayers[layerIndex][pointIndex] = data;
};
this.getDataPoint = function (x, y) {
initializeDataLayer(x);
var dataPoint = _dataLayers[x][y];
if (dataPoint === undefined)
dataPoint = 0;
return dataPoint;
};
this.addGroup = function (group, accessor) {
if (!accessor)
accessor = _defaultAccessor;
_groups.push([group, accessor]);
return _groups.length - 1;
};
this.getGroupByIndex = function (index) {
return _groups[index][0];
};
this.getAccessorByIndex = function (index) {
return _groups[index][1];
};
this.size = function () {
return _groups.length;
};
this.clear = function () {
_dataLayers = [];
_groups = [];
};
this.setDefaultAccessor = function (retriever) {
_defaultAccessor = retriever;
};
this.getDataLayers = function () {
return _dataLayers;
};
this.toLayers = function () {
var layers = [];
for (var i = 0; i < _dataLayers.length; ++i) {
var layer = {index: i, points: []};
var dataPoints = _dataLayers[i];
for (var j = 0; j < dataPoints.length; ++j)
layer.points.push(dataPoints[j]);
layers.push(layer);
}
return layers;
};
};
dc.utils.isNumber = function(n) {
return n===+n;
};
dc.utils.isFloat = function (n) {
return n===+n && n!==(n|0);
};
dc.utils.isInteger = function (n) {
return n===+n && n===(n|0);
};
dc.utils.isNegligible = function (max) {
return max === undefined || (max < dc.constants.NEGLIGIBLE_NUMBER && max > -dc.constants.NEGLIGIBLE_NUMBER);
};
dc.utils.groupMax = function (group, accessor) {
var max = d3.max(group.all(), function (e) {
return accessor(e);
});
if (dc.utils.isNegligible(max)) max = 0;
return max;
};
dc.utils.groupMin = function (group, accessor) {
var min = d3.min(group.all(), function (e) {
return accessor(e);
});
if (dc.utils.isNegligible(min)) min = 0;
return min;
};
dc.utils.nameToId = function (name) {
return name.toLowerCase().replace(/[\s]/g, "_").replace(/[\.']/g, "");
};
dc.utils.appendOrSelect = function (parent, name) {
var element = parent.select(name);
if (element.empty()) element = parent.append(name);
return element;
};
dc.utils.createLegendable = function (chart, group, index, accessor) {
var legendable = {name: chart.getGroupName(group, accessor), data: group};
if (typeof chart.colors === 'function') legendable.color = chart.colors()(index);
return legendable;
};
dc.utils.safeNumber = function(n){return dc.utils.isNumber(+n)?+n:0;};
dc.events = {
current: null
};
/**
#### dc.events.trigger(function[, delay])
This function is design to trigger throttled event function optionally with certain amount of delay(in milli-seconds).
Events that are triggered repetitively due to user interaction such as the dragging of the brush might over flood
library and cause too much rendering being scheduled. In this case, using this function to wrap your event function
allows the library to smooth out the rendering by throttling event flood and only respond to the most recent event.
```js
chart.renderlet(function(chart){
// smooth the rendering through event throttling
dc.events.trigger(function(){
// focus some other chart to the range selected by user on this chart
someOtherChart.focus(chart.filter());
});
})
```
**/
dc.events.trigger = function(closure, delay) {
if (!delay){
closure();
return;
}
dc.events.current = closure;
setTimeout(function() {
if (closure == dc.events.current)
closure();
}, delay);
};
dc.cumulative = {};
dc.cumulative.Base = function() {
this._keyIndex = [];
this._map = {};
this.sanitizeKey = function(key) {
key = key + "";
return key;
};
this.clear = function() {
this._keyIndex = [];
this._map = {};
};
this.size = function() {
return this._keyIndex.length;
};
this.getValueByKey = function(key) {
key = this.sanitizeKey(key);
var value = this._map[key];
return value;
};
this.setValueByKey = function(key, value) {
key = this.sanitizeKey(key);
return this._map[key] = value;
};
this.indexOfKey = function(key) {
key = this.sanitizeKey(key);
return this._keyIndex.indexOf(key);
};
this.addToIndex = function(key) {
key = this.sanitizeKey(key);
this._keyIndex.push(key);
};
this.getKeyByIndex = function(index) {
return this._keyIndex[index];
};
};
dc.cumulative.Sum = function() {
dc.cumulative.Base.apply(this, arguments);
this.add = function(key, value) {
if (!value)
value = 0;
if (this.getValueByKey(key) === undefined) {
this.addToIndex(key);
this.setValueByKey(key, value);
} else {
this.setValueByKey(key, this.getValueByKey(key) + value);
}
};
this.minus = function(key, value) {
this.setValueByKey(key, this.getValueByKey(key) - value);
};
this.cumulativeSum = function(key) {
var keyIndex = this.indexOfKey(key);
if (keyIndex < 0) return 0;
var cumulativeValue = 0;
for (var i = 0; i <= keyIndex; ++i) {
var k = this.getKeyByIndex(i);
cumulativeValue += this.getValueByKey(k);
}
return cumulativeValue;
};
};
dc.cumulative.Sum.prototype = new dc.cumulative.Base();
dc.cumulative.CountUnique = function() {
dc.cumulative.Base.apply(this, arguments);
function hashSize(hash) {
var size = 0, key;
for (key in hash) {
if (hash.hasOwnProperty(key)) size++;
}
return size;
}
this.add = function(key, e) {
if (this.getValueByKey(key) === undefined) {
this.setValueByKey(key, {});
this.addToIndex(key);
}
if (e !== undefined) {
if (this.getValueByKey(key)[e] === undefined)
this.getValueByKey(key)[e] = 0;
this.getValueByKey(key)[e] += 1;
}
};
this.minus = function(key, e) {
this.getValueByKey(key)[e] -= 1;
if (this.getValueByKey(key)[e] <= 0)
delete this.getValueByKey(key)[e];
};
this.count = function(key) {
return hashSize(this.getValueByKey(key));
};
this.cumulativeCount = function(key) {
var keyIndex = this.indexOfKey(key);
if (keyIndex < 0) return 0;
var cumulativeCount = 0;
for (var i = 0; i <= keyIndex; ++i) {
var k = this.getKeyByIndex(i);
cumulativeCount += this.count(k);
}
return cumulativeCount;
};
};
dc.cumulative.CountUnique.prototype = new dc.cumulative.Base();
/**
## <a name="base-chart" href="#base-chart">#</a> Base Chart [Abstract]
Base chart is an abstract functional object representing a basic dc chart object for all chart and widget implementation.
Every function on base chart are also inherited available on all concrete chart implementation in dc library.
**/
dc.baseChart = function (_chart) {
_chart.__dc_flag__ = true;
var _dimension;
var _group;
var _anchor;
var _root;
var _svg;
var _width = 200, _height = 200;
var _keyAccessor = function (d) {
return d.key;
};
var _valueAccessor = function (d) {
return d.value;
};
var _ordering = function (p) {
return p.key;
};
var _label = function (d) {
return d.key;
};
var _renderLabel = false;
var _title = function (d) {
return d.key + ": " + d.value;
};
var _renderTitle = false;
var _transitionDuration = 750;
var _filterPrinter = dc.printers.filters;
var _renderlets = [];
var _chartGroup = dc.constants.DEFAULT_CHART_GROUP;
var NULL_LISTENER = function (chart) {
};
var _listeners = {
preRender: NULL_LISTENER,
postRender: NULL_LISTENER,
preRedraw: NULL_LISTENER,
postRedraw: NULL_LISTENER,
filtered: NULL_LISTENER,
zoomed: NULL_LISTENER
};
var _legend;
var _filters = [];
var _filterHandler = function (dimension, filters) {
dimension.filter(null);
if (filters.length === 0)
dimension.filter(null);
else if (filters.length === 1)
dimension.filter(filters[0]);
else
dimension.filterFunction(function (d) {
return filters.indexOf(d) >= 0;
});
return filters;
};
/**
#### .width([value])
Set or get width attribute of a chart. If the value is given, then it will be used as the new width.
If no value specified then value of the current width attribute will be returned.
**/
_chart.width = function (w) {
if (!arguments.length) return _width;
_width = w;
return _chart;
};
/**
#### .height([value])
Set or get height attribute of a chart. If the value is given, then it will be used as the new height.
If no value specified then value of the current height attribute will be returned.
**/
_chart.height = function (h) {
if (!arguments.length) return _height;
_height = h;
return _chart;
};
/**
#### .dimension([value]) - **mandatory**
Set or get dimension attribute of a chart. In dc a dimension can be any valid
[crossfilter dimension](https://github.com/square/crossfilter/wiki/API-Reference#wiki-dimension). If the value is given,
then it will be used as the new dimension.
If no value specified then the current dimension will be returned.
**/
_chart.dimension = function (d) {
if (!arguments.length) return _dimension;
_dimension = d;
_chart.expireCache();
return _chart;
};
/**
#### .group([value], [name]) - **mandatory**
Set or get group attribute of a chart. In dc a group is a
[crossfilter group](https://github.com/square/crossfilter/wiki/API-Reference#wiki-group). Usually the group should be
created from the particular dimension associated with the same chart. If the value is given, then it will be used as
the new group.
If no value specified then the current group will be returned.
If name is specified then it will be used to generate legend label.
**/
_chart.group = function (g, name) {
if (!arguments.length) return _group;
_group = g;
_chart.expireCache();
if (typeof name === 'string') _chart.setGroupName(_group, name);
return _chart;
};
function groupName(chart, g, accessor) {
var c = chart.anchor(),
k = '__names__';
if (!accessor || accessor == chart.valueAccessor())
accessor = "default";
if (!g[k]) g[k] = {};
if (!g[k][c]) g[k][c] = {a:[],n:[]};
var i = g[k][c].a.indexOf(accessor);
if (i == -1) {
i = g[k][c].a.length;
g[k][c].a[i] = accessor;
g[k][c].n[i] = {name:''};
}
return g[k][c].n[i];
}
_chart.getGroupName = function (g, accessor) {
return groupName(_chart, g, accessor).name;
};
_chart.setGroupName = function (g, name, accessor) {
groupName(_chart, g, accessor).name = name;
};
_chart.ordering = function(o) {
if (!arguments.length) return _ordering;
_ordering = o;
_chart.expireCache();
return _chart;
};
_chart.computeOrderedGroups = function(arr) {
var data = arr ? arr : _chart.group().all().slice(0); // clone
if(data.length < 2)
return data;
var sort = crossfilter.quicksort.by(_chart.ordering());
return sort(data,0,data.length);
};
/**
#### .filterAll()
Clear all filters associated with this chart.
**/
_chart.filterAll = function () {
return _chart.filter(null);
};
_chart.dataSet = function () {
return _dimension !== undefined && _group !== undefined;
};
/**
#### .select(selector)
Execute in scope d3 single selection using the given selector and return d3 selection result. Roughly the same as:
```js
d3.select("#chart-id").select(selector);
```
This function is **not chainable** since it does not return a chart instance; however the d3 selection result is chainable
from d3's perspective.
**/
_chart.select = function (s) {
return _root.select(s);
};
/**
#### .selectAll(selector)
Execute in scope d3 selectAll using the given selector and return d3 selection result. Roughly the same as:
```js
d3.select("#chart-id").selectAll(selector);
```
This function is **not chainable** since it does not return a chart instance; however the d3 selection result is
chainable from d3's perspective.
**/
_chart.selectAll = function (s) {
return _root ? _root.selectAll(s) : null;
};
_chart.anchor = function (a, chartGroup) {
if (!arguments.length) return _anchor;
if (dc.instanceOfChart(a)) {
_anchor = a.anchor();
_root = a.root();
} else {
_anchor = a;
_root = d3.select(_anchor);
_root.classed(dc.constants.CHART_CLASS, true);
dc.registerChart(_chart, chartGroup);
}
_chartGroup = chartGroup;
return _chart;
};
_chart.anchorName = function () {
var a = _chart.anchor();
if (a && a.id) return a.id;
if (a) return a.replace('#','');
return '';
};
/**
#### .root([rootElement])
Returns the root element where a chart resides. Usually it will be the parent div element where svg was created. You
can also pass in a new root element however this is usually handled as part of the dc internal. Resetting root element
on a chart outside of dc internal might have unexpected consequences.
**/
_chart.root = function (r) {
if (!arguments.length) return _root;
_root = r;
return _chart;
};
/**
#### .svg([svgElement])
Returns the top svg element for this specific chart. You can also pass in a new svg element however this is usually
handled as part of the dc internal. Resetting svg element on a chart outside of dc internal might have unexpected
consequences.
**/
_chart.svg = function (_) {
if (!arguments.length) return _svg;
_svg = _;
return _chart;
};
_chart.resetSvg = function () {
_chart.select("svg").remove();
return _chart.generateSvg();
};
_chart.generateSvg = function () {
_svg = _chart.root().append("svg")
.attr("width", _chart.width())
.attr("height", _chart.height());
return _svg;
};
/**
#### .filterPrinter([filterPrinterFunction])
Set or get filter printer function. Filter printer function is used to generate human friendly text for filter value(s)
associated with the chart instance. By default dc charts shipped with a default filter printer implementation dc.printers.filter
that provides simple printing support for both single value and ranged filters.
**/
_chart.filterPrinter = function (_) {
if (!arguments.length) return _filterPrinter;
_filterPrinter = _;
return _chart;
};
/**
#### .turnOnControls() & .turnOffControls
Turn on/off optional control elements within the root element. dc.js currently support the following html control elements.
* root.selectAll(".reset") elements are turned on if the chart has an active filter. This type of control elements are usually used to store reset link to allow user to reset filter on a certain chart. This element will be turned off automatically if the filter is cleared.
* root.selectAll(".filter") elements are turned on if the chart has an active filter. The text content of this element is then replaced with the current filter value using the filter printer function. This type of element will be turned off automatically if the filter is cleared.
**/
_chart.turnOnControls = function () {
if (_root) {
_chart.selectAll(".reset").style("display", null);
_chart.selectAll(".filter").text(_filterPrinter(_chart.filters())).style("display", null);
}
return _chart;
};
_chart.turnOffControls = function () {
if (_root) {
_chart.selectAll(".reset").style("display", "none");
_chart.selectAll(".filter").style("display", "none").text(_chart.filter());
}
return _chart;
};
/**
#### .transitionDuration([duration])
Set or get animation transition duration(in milliseconds) for specific chart instance. Default duration is 750ms.
**/
_chart.transitionDuration = function (d) {
if (!arguments.length) return _transitionDuration;
_transitionDuration = d;
return _chart;
};
/**
#### .render()
Invoke this method will force the chart to re-render everything from scratch. Generally it should be only used to
render the chart for the first time on the page or if you want to make sure everything is redrawn from scratch instead
of relying on the default incremental redrawing behaviour.
**/
_chart.render = function () {
_listeners.preRender(_chart);
if (_dimension === undefined)
throw new dc.errors.InvalidStateException("Mandatory attribute chart.dimension is missing on chart[#"
+ _chart.anchorName() + "]");
if (_group === undefined)
throw new dc.errors.InvalidStateException("Mandatory attribute chart.group is missing on chart[#"
+ _chart.anchorName() + "]");
var result = _chart.doRender();
if (_legend) _legend.render();
_chart.activateRenderlets("postRender");
return result;
};
_chart.activateRenderlets = function (event) {
if (_chart.transitionDuration() > 0 && _svg) {
_svg.transition().duration(_chart.transitionDuration())
.each("end", function () {
runAllRenderlets();
if (event) _listeners[event](_chart);
});
} else {
runAllRenderlets();
if (event) _listeners[event](_chart);
}