-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathget_legend_data.js
103 lines (82 loc) · 2.98 KB
/
get_legend_data.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
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var Registry = require('../../registry');
var helpers = require('./helpers');
module.exports = function getLegendData(calcdata, opts) {
var lgroupToTraces = {},
lgroups = [],
hasOneNonBlankGroup = false,
slicesShown = {},
lgroupi = 0;
var i, j;
function addOneItem(legendGroup, legendItem) {
// each '' legend group is treated as a separate group
if(legendGroup === '' || !helpers.isGrouped(opts)) {
var uniqueGroup = '~~i' + lgroupi; // TODO: check this against fullData legendgroups?
lgroups.push(uniqueGroup);
lgroupToTraces[uniqueGroup] = [[legendItem]];
lgroupi++;
}
else if(lgroups.indexOf(legendGroup) === -1) {
lgroups.push(legendGroup);
hasOneNonBlankGroup = true;
lgroupToTraces[legendGroup] = [[legendItem]];
}
else lgroupToTraces[legendGroup].push([legendItem]);
}
// build an { legendgroup: [cd0, cd0], ... } object
for(i = 0; i < calcdata.length; i++) {
var cd = calcdata[i];
var cd0 = cd[0];
var trace = cd0.trace;
var lgroup = trace.legendgroup;
if(!trace.visible || !trace.showlegend) continue;
if(Registry.traceIs(trace, 'pie')) {
if(!slicesShown[lgroup]) slicesShown[lgroup] = {};
for(j = 0; j < cd.length; j++) {
var labelj = cd[j].label;
if(!slicesShown[lgroup][labelj]) {
addOneItem(lgroup, {
label: labelj,
color: cd[j].color,
i: cd[j].i,
trace: trace
});
slicesShown[lgroup][labelj] = true;
}
}
}
else addOneItem(lgroup, cd0);
}
// won't draw a legend in this case
if(!lgroups.length) return [];
// rearrange lgroupToTraces into a d3-friendly array of arrays
var lgroupsLength = lgroups.length,
ltraces,
legendData;
if(hasOneNonBlankGroup && helpers.isGrouped(opts)) {
legendData = new Array(lgroupsLength);
for(i = 0; i < lgroupsLength; i++) {
ltraces = lgroupToTraces[lgroups[i]];
legendData[i] = helpers.isReversed(opts) ? ltraces.reverse() : ltraces;
}
}
else {
// collapse all groups into one if all groups are blank
legendData = [new Array(lgroupsLength)];
for(i = 0; i < lgroupsLength; i++) {
ltraces = lgroupToTraces[lgroups[i]][0];
legendData[0][helpers.isReversed(opts) ? lgroupsLength - i - 1 : i] = ltraces;
}
lgroupsLength = 1;
}
// needed in repositionLegend
opts._lgroupsLength = lgroupsLength;
return legendData;
};