-
Notifications
You must be signed in to change notification settings - Fork 11.9k
/
controller.doughnut.js
396 lines (339 loc) · 11.5 KB
/
controller.doughnut.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
import DatasetController from '../core/core.datasetController.js';
import {isObject, resolveObjectKey, toPercentage, toDimension, valueOrDefault} from '../helpers/helpers.core.js';
import {formatNumber} from '../helpers/helpers.intl.js';
import {toRadians, PI, TAU, HALF_PI, _angleBetween} from '../helpers/helpers.math.js';
/**
* @typedef { import('../core/core.controller.js').default } Chart
*/
function getRatioAndOffset(rotation, circumference, cutout) {
let ratioX = 1;
let ratioY = 1;
let offsetX = 0;
let offsetY = 0;
// If the chart's circumference isn't a full circle, calculate size as a ratio of the width/height of the arc
if (circumference < TAU) {
const startAngle = rotation;
const endAngle = startAngle + circumference;
const startX = Math.cos(startAngle);
const startY = Math.sin(startAngle);
const endX = Math.cos(endAngle);
const endY = Math.sin(endAngle);
const calcMax = (angle, a, b) => _angleBetween(angle, startAngle, endAngle, true) ? 1 : Math.max(a, a * cutout, b, b * cutout);
const calcMin = (angle, a, b) => _angleBetween(angle, startAngle, endAngle, true) ? -1 : Math.min(a, a * cutout, b, b * cutout);
const maxX = calcMax(0, startX, endX);
const maxY = calcMax(HALF_PI, startY, endY);
const minX = calcMin(PI, startX, endX);
const minY = calcMin(PI + HALF_PI, startY, endY);
ratioX = (maxX - minX) / 2;
ratioY = (maxY - minY) / 2;
offsetX = -(maxX + minX) / 2;
offsetY = -(maxY + minY) / 2;
}
return {ratioX, ratioY, offsetX, offsetY};
}
export default class DoughnutController extends DatasetController {
static id = 'doughnut';
/**
* @type {any}
*/
static defaults = {
datasetElementType: false,
dataElementType: 'arc',
animation: {
// Boolean - Whether we animate the rotation of the Doughnut
animateRotate: true,
// Boolean - Whether we animate scaling the Doughnut from the centre
animateScale: false
},
animations: {
numbers: {
type: 'number',
properties: ['circumference', 'endAngle', 'innerRadius', 'outerRadius', 'startAngle', 'x', 'y', 'offset', 'borderWidth', 'spacing']
},
},
// The percentage of the chart that we cut out of the middle.
cutout: '50%',
// The rotation of the chart, where the first data arc begins.
rotation: 0,
// The total circumference of the chart.
circumference: 360,
// The outer radius of the chart
radius: '100%',
// Spacing between arcs
spacing: 0,
indexAxis: 'r',
};
static descriptors = {
_scriptable: (name) => name !== 'spacing',
_indexable: (name) => name !== 'spacing' && !name.startsWith('borderDash') && !name.startsWith('hoverBorderDash'),
};
/**
* @type {any}
*/
static overrides = {
aspectRatio: 1,
// Need to override these to give a nice default
plugins: {
legend: {
labels: {
generateLabels(chart) {
const data = chart.data;
if (data.labels.length && data.datasets.length) {
const {labels: {pointStyle, color}} = chart.legend.options;
return data.labels.map((label, i) => {
const meta = chart.getDatasetMeta(0);
const style = meta.controller.getStyle(i);
return {
text: label,
fillStyle: style.backgroundColor,
strokeStyle: style.borderColor,
fontColor: color,
lineWidth: style.borderWidth,
pointStyle: pointStyle,
hidden: !chart.getDataVisibility(i),
// Extra data used for toggling the correct item
index: i
};
});
}
return [];
}
},
onClick(e, legendItem, legend) {
legend.chart.toggleDataVisibility(legendItem.index);
legend.chart.update();
}
}
}
};
constructor(chart, datasetIndex) {
super(chart, datasetIndex);
this.enableOptionSharing = true;
this.innerRadius = undefined;
this.outerRadius = undefined;
this.offsetX = undefined;
this.offsetY = undefined;
}
linkScales() {}
/**
* Override data parsing, since we are not using scales
*/
parse(start, count) {
const data = this.getDataset().data;
const meta = this._cachedMeta;
if (this._parsing === false) {
meta._parsed = data;
} else {
let getter = (i) => +data[i];
if (isObject(data[start])) {
const {key = 'value'} = this._parsing;
getter = (i) => +resolveObjectKey(data[i], key);
}
let i, ilen;
for (i = start, ilen = start + count; i < ilen; ++i) {
meta._parsed[i] = getter(i);
}
}
}
/**
* @private
*/
_getRotation() {
return toRadians(this.options.rotation - 90);
}
/**
* @private
*/
_getCircumference() {
return toRadians(this.options.circumference);
}
/**
* Get the maximal rotation & circumference extents
* across all visible datasets.
*/
_getRotationExtents() {
let min = TAU;
let max = -TAU;
for (let i = 0; i < this.chart.data.datasets.length; ++i) {
if (this.chart.isDatasetVisible(i) && this.chart.getDatasetMeta(i).type === this._type) {
const controller = this.chart.getDatasetMeta(i).controller;
const rotation = controller._getRotation();
const circumference = controller._getCircumference();
min = Math.min(min, rotation);
max = Math.max(max, rotation + circumference);
}
}
return {
rotation: min,
circumference: max - min,
};
}
/**
* @param {string} mode
*/
update(mode) {
const chart = this.chart;
const {chartArea} = chart;
const meta = this._cachedMeta;
const arcs = meta.data;
const spacing = this.getMaxBorderWidth() + this.getMaxOffset(arcs) + this.options.spacing;
const maxSize = Math.max((Math.min(chartArea.width, chartArea.height) - spacing) / 2, 0);
const cutout = Math.min(toPercentage(this.options.cutout, maxSize), 1);
const chartWeight = this._getRingWeight(this.index);
// Compute the maximal rotation & circumference limits.
// If we only consider our dataset, this can cause problems when two datasets
// are both less than a circle with different rotations (starting angles)
const {circumference, rotation} = this._getRotationExtents();
const {ratioX, ratioY, offsetX, offsetY} = getRatioAndOffset(rotation, circumference, cutout);
const maxWidth = (chartArea.width - spacing) / ratioX;
const maxHeight = (chartArea.height - spacing) / ratioY;
const maxRadius = Math.max(Math.min(maxWidth, maxHeight) / 2, 0);
const outerRadius = toDimension(this.options.radius, maxRadius);
const innerRadius = Math.max(outerRadius * cutout, 0);
const radiusLength = (outerRadius - innerRadius) / this._getVisibleDatasetWeightTotal();
this.offsetX = offsetX * outerRadius;
this.offsetY = offsetY * outerRadius;
meta.total = this.calculateTotal();
this.outerRadius = outerRadius - radiusLength * this._getRingWeightOffset(this.index);
this.innerRadius = Math.max(this.outerRadius - radiusLength * chartWeight, 0);
this.updateElements(arcs, 0, arcs.length, mode);
}
/**
* @private
*/
_circumference(i, reset) {
const opts = this.options;
const meta = this._cachedMeta;
const circumference = this._getCircumference();
if ((reset && opts.animation.animateRotate) || !this.chart.getDataVisibility(i) || meta._parsed[i] === null || meta.data[i].hidden) {
return 0;
}
return this.calculateCircumference(meta._parsed[i] * circumference / TAU);
}
updateElements(arcs, start, count, mode) {
const reset = mode === 'reset';
const chart = this.chart;
const chartArea = chart.chartArea;
const opts = chart.options;
const animationOpts = opts.animation;
const centerX = (chartArea.left + chartArea.right) / 2;
const centerY = (chartArea.top + chartArea.bottom) / 2;
const animateScale = reset && animationOpts.animateScale;
const innerRadius = animateScale ? 0 : this.innerRadius;
const outerRadius = animateScale ? 0 : this.outerRadius;
const {sharedOptions, includeOptions} = this._getSharedOptions(start, mode);
let startAngle = this._getRotation();
let i;
for (i = 0; i < start; ++i) {
startAngle += this._circumference(i, reset);
}
for (i = start; i < start + count; ++i) {
const circumference = this._circumference(i, reset);
const arc = arcs[i];
const properties = {
x: centerX + this.offsetX,
y: centerY + this.offsetY,
startAngle,
endAngle: startAngle + circumference,
circumference,
outerRadius,
innerRadius
};
if (includeOptions) {
properties.options = sharedOptions || this.resolveDataElementOptions(i, arc.active ? 'active' : mode);
}
startAngle += circumference;
this.updateElement(arc, i, properties, mode);
}
}
calculateTotal() {
const meta = this._cachedMeta;
const metaData = meta.data;
let total = 0;
let i;
for (i = 0; i < metaData.length; i++) {
const value = meta._parsed[i];
if (value !== null && !isNaN(value) && this.chart.getDataVisibility(i) && !metaData[i].hidden) {
total += Math.abs(value);
}
}
return total;
}
calculateCircumference(value) {
const total = this._cachedMeta.total;
if (total > 0 && !isNaN(value)) {
return TAU * (Math.abs(value) / total);
}
return 0;
}
getLabelAndValue(index) {
const meta = this._cachedMeta;
const chart = this.chart;
const labels = chart.data.labels || [];
const value = formatNumber(meta._parsed[index], chart.options.locale);
return {
label: labels[index] || '',
value,
};
}
getMaxBorderWidth(arcs) {
let max = 0;
const chart = this.chart;
let i, ilen, meta, controller, options;
if (!arcs) {
// Find the outmost visible dataset
for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {
if (chart.isDatasetVisible(i)) {
meta = chart.getDatasetMeta(i);
arcs = meta.data;
controller = meta.controller;
break;
}
}
}
if (!arcs) {
return 0;
}
for (i = 0, ilen = arcs.length; i < ilen; ++i) {
options = controller.resolveDataElementOptions(i);
if (options.borderAlign !== 'inner') {
max = Math.max(max, options.borderWidth || 0, options.hoverBorderWidth || 0);
}
}
return max;
}
getMaxOffset(arcs) {
let max = 0;
for (let i = 0, ilen = arcs.length; i < ilen; ++i) {
const options = this.resolveDataElementOptions(i);
max = Math.max(max, options.offset || 0, options.hoverOffset || 0);
}
return max;
}
/**
* Get radius length offset of the dataset in relation to the visible datasets weights. This allows determining the inner and outer radius correctly
* @private
*/
_getRingWeightOffset(datasetIndex) {
let ringWeightOffset = 0;
for (let i = 0; i < datasetIndex; ++i) {
if (this.chart.isDatasetVisible(i)) {
ringWeightOffset += this._getRingWeight(i);
}
}
return ringWeightOffset;
}
/**
* @private
*/
_getRingWeight(datasetIndex) {
return Math.max(valueOrDefault(this.chart.data.datasets[datasetIndex].weight, 1), 0);
}
/**
* Returns the sum of all visible data set weights.
* @private
*/
_getVisibleDatasetWeightTotal() {
return this._getRingWeightOffset(this.chart.data.datasets.length) || 1;
}
}