forked from predixdesignsystem/px-vis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
px-vis-pie.html
451 lines (406 loc) · 13.3 KB
/
px-vis-pie.html
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
<!--
Copyright (c) 2018, General Electric
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.
-->
<link rel="import" href="../polymer/polymer.html"/>
<link rel="import" href="px-vis-behavior-common.html" />
<link rel="import" href="px-vis-behavior-d3.html" />
<link rel="import" href="px-vis-behavior-colors.html" />
<link rel="import" href="css/px-vis-pie-styles.html">
<!--
### Usage
<px-vis-pie
svg="[[svg]]"
clip-path="[[clipPath]]"
series-id="[[item.name]]"
series-number="[[index]]"
chart-data="[[item]]"
x="[[x]]"
y="[[y]]"
muted-series="[[mutedSeries]]">
</px-vis-pie>
### Styling
The following custom properties are available for styling:
Custom property | Description
:----------------|:-------------
`--px-vis-pie-empty-color` | The color for an empty pie chart
`--px-vis-pie-title-color` | The color for the title name
`--px-vis-pie-title-font-size` | The size for the title name
`--px-vis-pie-title-value-color` | The color for the title data value
`--px-vis-pie-title-value-font-size` | The size for the title data value
@element px-vis-pie
@blurb Creates an interactive pie or donut chart
@homepage index.html
@demo demo.html
-->
<dom-module id="px-vis-pie">
<template>
<style include="px-vis-pie-styles"></style>
</template>
</dom-module>
<script>
Polymer({
is: 'px-vis-pie',
behaviors: [
PxVisBehavior.observerCheck,
PxVisBehaviorD3.svg,
PxVisBehavior.dataset,
PxVisBehavior.mutedSeries,
PxVisBehavior.commonMethods,
PxVisBehavior.sizing,
PxVisBehavior.dataset,
PxVisBehavior.completeSeriesConfig,
PxColorsBehavior.getSeriesColors,
PxColorsBehavior.dataVisColorTheming,
PxVisBehavior.updateStylesOverride
],
/**
* Fired when the pie finishes rotating, for centering on a slice.
* detail: { datum: datumRelativeToSlice}
* @event px-vis-pie-centered-on-slice
*/
/**
* Fired when the mouse enters a pie slice.
* detail: { datum: datumRelativeToSlice, rotatedDatum: DatumUsedToDrawTheSlice}
* @event px-vis-pie-mouse-enter-slice
*/
/**
* Fired when the mouse leaves a pie slice.
* detail: { datum: datumRelativeToSlice}
* @event px-vis-pie-mouse-leave-slice
*/
/**
* Fired when a pie slice is clicked.
* detail: { datum: datumRelativeToSlice}
* @event px-vis-pie-slice-clicked
*/
/**
* Properties block, expose attribute values to the DOM via 'reflect'
*
* @property properties
* @type Object
*/
properties: {
/**
* Whether to draw an empty pie chart when data is empty/null.
*/
empty: {
type: Boolean,
value: false,
observer: '_emptyChanged'
},
/**
* An index of the series used for calculating its color.
*
* @property scatterNumber
* @type String
*/
seriesNumber:{
type:Number,
value:0
},
/**
* Number between 0 and 1 defining how much of the inner pie should be cut.
* Typically at 0 this is a pie chart, at 0.5 a donut chart and at 1 all
* the chart is cut (i.e. not visible).
*
*/
innerRadius: {
type: Number,
value: 0
},
/**
* The actual inner radius value in pixels which will be used internally to draw the chart.
*/
_innerRadiusPx: {
type: Number,
computed: '_calcInnerRadiusPx(innerRadius, radius, donut)'
},
/**
* Whether the chart should be displayed as a donut rather than a pie.
* If displayed as a donut, it will by default use 30px as the ring size.
* This can be overridden by using the "innerRadius" property (between 0 and 1).
*/
donut: {
type: Boolean,
value: false
},
/**
* A holder object for the series object.
*
* @property linePath
* @type String
*/
pieGroup:{
type:Object,
value: function() {return{};}
},
/**
* Total value of all slices.
*/
total: {
Type: Number,
value: 0
},
/**
* Radius of the pie chart.
*
*/
radius: {
type: Number
},
/**
* The current arc definitions.
*/
_arcs: {
type: Object
},
/**
* How much the pie is currently rotated in radians.
*/
_currentRotationAngle: {
type:Number,
value:0
},
/**
* Whether the values should be displayed in percent.
*/
usePercentage: {
type: Boolean,
value: false
},
/**
* By default the pie chart slices will be ordered by value.
* Set to false to keep the data order.
*/
preserveDataOrder: {
type: Boolean,
value: false
}
},
observers: [
'drawElement(radius,svg,chartData.*,completeSeriesConfig, usePercentage, donut, innerRadius, _stylesUpdated)'
],
/**
* Draws or updates the pie element.
* Called from an observer watching for data and the necessary d3 objects.
*
* @method drawElement
*/
drawElement: function() {
if(this.hasUndefinedArguments(arguments)) {
return;
}
this._checkInitialGroupCreation();
this._updateDrawing();
},
/**
* Checks whether the group holding all of the slices has been created,
* and creates it if necessary.
*/
_checkInitialGroupCreation: function() {
// checks to see if the group already exists. If not, create; if so, update
if(this._isObjEmpty(this.pieGroup)){
// draw the path and move it so the ie is centered
this.pieGroup = this.svg.append('g')
.attr('series-id', 'pie_')
.attr('class', 'pie-slice');
}
},
/**
* Updates drawing when adding, removing or updating data.
*/
_updateDrawing: function() {
this.debounce('_updateDrawing', function() {
var _this = this,
data = this.chartData,
isFirstDrawing = this._arcs ? false : true;
xKey = this.empty ? '' : this.completeSeriesConfig[Object.keys(this.completeSeriesConfig)[0]].x;
//generate the pie data
if(this.empty) {
this._pie = Px.d3.pie()([1]);
} else {
var gen = Px.d3.pie().value(function(d){return d[xKey];});
//don't sort by value if required
if(this.preserveDataOrder) {
gen.sort(null).sortValues(null);
}
this._pie = gen(data);
}
//use new values
this._arcs = this.pieGroup
.selectAll('.slice')
//store previous data so that we can interpolate
//between old and new data for animation
.property('_previousData', function(d) {
return {
startAngle: d.startAngle,
endAngle: d.endAngle,
innerRadius: d.innerRadius,
outerRadius: d.outerRadius
};
})
.data(this._pie, function(d) {
//map slices based on "y" in the data (name)
return d.data.y;
});
//function used to interpolate values between initial and final state. Used during
//transitioning
var tweenArc = function tweenArc(b) {
//update radius values
b.innerRadius = _this._innerRadiusPx;
b.outerRadius = _this.radius;
//initialise new slices
if(!this._previousData) {
this._previousData = {
startAngle: isFirstDrawing ? 0 : b.startAngle,
endAngle: isFirstDrawing ? 0 : b.startAngle,
innerRadius: b.innerRadius ? b.innerRadius : 0,
outerRadius: b.outerRadius ? b.outerRadius : _this._radius
};
}
//create function allowing us to interpolate values for data being updated
var interpolate = Px.d3.interpolateObject(this._previousData, b);
return function(t) {
return Px.d3.arc()(interpolate(t));
};
};
//removed data, delete slices
this._arcs.exit().remove();
//new data, create new slices
this._arcs.enter()
.append('svg:path')
.attr('class', 'slice')
.on('tap', this._onSliceClick.bind(this))
.on('mouseenter', this._sliceMouseEnter.bind(this))
.on('mouseleave', this._mouseLeaveSlice.bind(this))
//new + update
.merge(this._arcs)
.attr('fill', function(d, i) {
d.innerRadius = this._innerRadiusPx;
d.outerRadius = this._radius;
return this.empty ?
this._checkThemeVariable( "--px-vis-pie-empty-color", 'rgb(0,0,0)') :
this._getColor(d.data.colorIndex);
}.bind(this))
.attr('opacity', this.empty ? 0.5 : 1)
.transition()
.duration(750)
.attrTween('d', tweenArc);
//apply color depending on the chart "emptiness"
if(this.empty) {
this._arcs.selectAll('path')
.attr('fill', this._checkThemeVariable( "--px-vis-pie-empty-color", 'rgb(0,0,0)'));
} else {
this._arcs.selectAll('path')
.attr('fill', function(d, i) {
return this._getColor(d.data.colorIndex);
}.bind(this));
}
//make sure we're in the right pos
this._positionChart(0);
}.bind(this), 5);
},
/**
* Function used to display a tooltip for a specific slice.
*
* @method _sliceMouseEnter
*/
_sliceMouseEnter: function(datum, index, group) {
//take current rotation into account
var rotatedDatum = {
startAngle: datum.startAngle + this._currentRotationAngle,
endAngle: datum.endAngle + this._currentRotationAngle,
innerRadius: this._innerRadiusPx,
outerRadius: this.radius
};
this.fire('px-vis-pie-mouse-enter-slice', {datum: datum, rotatedDatum: rotatedDatum});
},
_mouseLeaveSlice: function(datum, index, group) {
this.fire('px-vis-pie-mouse-leave-slice', {datum: datum});
},
/**
* Position the chart given the rotation angle.
*/
_positionChart: function(transitionTime) {
//then add rotation
this.pieGroup
.transition()
.duration(transitionTime)
.attr('transform', 'rotate(' + this._radToDeg(this._currentRotationAngle) + ')');
},
/**
* Emits px-vis-pie-slice-clicked event with selected slice data.
*
* @method _onSliceClick
*/
_onSliceClick: function (datum, index, group) {
this.fire('px-vis-pie-slice-clicked', {datum: datum});
this._centerOnSlice(datum, index, group);
},
/**
* Transforms the svg to show the slice at the top (12 o'clock).
*
* @method _centerOnSlice
*/
_centerOnSlice: function(datum, index, group) {
if(!this.empty) {
this.set('_currentRotationAngle', this._getRotationAngle(datum));
this._positionChart(750);
//display a popover after the rotation
window.setTimeout(function() {
this.fire('px-vis-pie-centered-on-slice', {datum: datum});
}.bind(this), 750);
}
},
/**
* Converts radians to degrees.
*
* @method _radToDeg
*/
_radToDeg: function(angle) {
return angle * 180 / Math.PI;
},
/**
* Calculates the appropriate rotation angle for the slice to be displayed at 12 o'clock.
*
* @method _getRotationAngle
*/
_getRotationAngle: function(slice) {
//get angle to middle of slice, then adjust rotation direction
var start = slice.startAngle,
end = slice.endAngle,
mid = start + (end - start)/2,
adjusted = mid < Math.PI ? -mid : Math.PI * 2 - mid;
return adjusted;
},
_calcInnerRadiusPx: function() {
if(this.hasUndefinedArguments(arguments)) {
return;
}
if(this.donut) {
//if no inner radius defined used 30px by default
return this.innerRadius === 0 ? (this.radius - 30) : this.innerRadius * this.radius;
} else {
//no donut
return 0;
}
},
_emptyChanged: function() {
if(this.hasUndefinedArguments(arguments)) {
return;
}
if(this.empty) {
this.drawElement();
}
}
});
</script>