Debian Codegraph @

bqplot/js/src/Pie.ts

raw
1 /* Copyright 2015 Bloomberg Finance L.P.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 import * as d3 from 'd3';
17 import { d3GetEvent } from './utils';
18 import * as _ from 'underscore';
19 import { Mark } from './Mark';
20 import { applyStyles, getDate } from './utils';
21 import { PieModel, Slice } from './PieModel';
22
23 export class Pie extends Mark {
24 async render() {
25 const base_creation_promise = super.render();
26 this.selected_indices = this.model.get('selected');
27 this.selected_style = this.model.get('selected_style');
28 this.unselected_style = this.model.get('unselected_style');
29
30 this.display_el_classes = ['slice', 'text'];
31
32 this.pieSelection = this.d3el.append('g').attr('class', 'pie');
33 this.pieSelection.append('g').attr('class', 'slices');
34 this.pieSelection.append('g').attr('class', 'labels');
35 this.pieSelection.append('g').attr('class', 'lines');
36
37 const radius = this.model.get('radius');
38 const inner_radius = this.model.get('inner_radius');
39
40 const display_labels = this.model.get('display_labels');
41
42 if (display_labels === 'outside') {
43 this.arc = d3
44 .arc()
45 .outerRadius(radius * 0.8)
46 .innerRadius(inner_radius * 0.8);
47
48 this.outerArc = d3
49 .arc()
50 .innerRadius(radius * 0.9)
51 .outerRadius(radius * 0.9);
52 } else {
53 this.arc = d3.arc().outerRadius(radius).innerRadius(inner_radius);
54 }
55
56 this.displayed.then(() => {
57 this.parent.tooltip_div.node().appendChild(this.tooltip_div.node());
58 this.create_tooltip();
59 });
60
61 await base_creation_promise;
62
63 this.event_listeners = {};
64 this.process_interactions();
65 this.create_listeners();
66 this.compute_view_padding();
67 this.draw();
68 }
69
70 set_ranges() {
71 if (this.scales.x) {
72 this.scales.x.set_range(
73 this.parent.padded_range('x', this.scales.x.model)
74 );
75 }
76
77 if (this.scales.y) {
78 this.scales.y.set_range(
79 this.parent.padded_range('y', this.scales.y.model)
80 );
81 }
82 }
83
84 set_positional_scales() {
85 // If no scale for "x" or "y" is specified, figure scales are used.
86 const x_scale = this.scales.x ? this.scales.x : this.parent.scale_x;
87 const y_scale = this.scales.y ? this.scales.y : this.parent.scale_y;
88
89 this.listenTo(x_scale, 'domain_changed', () => {
90 if (!this.model.dirty) {
91 this.draw();
92 }
93 });
94 this.listenTo(y_scale, 'domain_changed', () => {
95 if (!this.model.dirty) {
96 this.draw();
97 }
98 });
99 }
100
101 create_listeners() {
102 super.create_listeners();
103 this.d3el
104 .on('mouseover', () => {
105 this.event_dispatcher('mouse_over');
106 })
107 .on('mousemove', () => {
108 this.event_dispatcher('mouse_move');
109 })
110 .on('mouseout', () => {
111 this.event_dispatcher('mouse_out');
112 });
113
114 this.listenTo(this.model, 'data_updated', function () {
115 this.draw(true);
116 });
117 this.listenTo(this.model, 'colors_updated', this.updateSlices);
118 this.model.on_some_change(
119 ['inner_radius', 'radius'],
120 () => {
121 this.compute_view_padding();
122 this.updateRadius(true);
123 },
124 this
125 );
126 this.model.on_some_change(
127 ['colors', 'stroke', 'opacities'],
128 this.updateSlices,
129 this
130 );
131 this.model.on_some_change(
132 ['x', 'y'],
133 () => {
134 this.positionCenter(true);
135 },
136 this
137 );
138 this.model.on_some_change(
139 [
140 'display_labels',
141 'label_color',
142 'font_size',
143 'font_weight',
144 'display_values',
145 'values_format',
146 ],
147 () => {
148 this.updateLabels(true);
149 },
150 this
151 );
152 this.model.on_some_change(
153 ['start_angle', 'end_angle', 'sort'],
154 () => {
155 this.draw(true);
156 },
157 this
158 );
159
160 this.listenTo(this.model, 'labels_updated', () => {
161 this.updateLabels(true);
162 this.updatePolylines(true);
163 });
164
165 this.listenTo(this.model, 'change:selected', () => {
166 this.selected_indices = this.model.get('selected');
167 this.apply_styles();
168 });
169 this.listenTo(this.model, 'change:interactions', this.process_interactions);
170 this.listenTo(this.parent, 'bg_clicked', () => {
171 this.event_dispatcher('parent_clicked');
172 });
173 }
174
175 process_click(interaction) {
176 super.process_click(interaction);
177
178 if (interaction === 'select') {
179 this.event_listeners.parent_clicked = this.reset_selection;
180 this.event_listeners.element_clicked = this.click_handler;
181 }
182 }
183
184 relayout() {
185 this.set_ranges();
186 this.positionCenter();
187 this.updateRadius();
188 }
189
190 private positionCenter(animate?: boolean) {
191 const animation_duration =
192 animate === true ? this.parent.model.get('animation_duration') : 0;
193 const x_scale = this.scales.x ? this.scales.x : this.parent.scale_x;
194 const y_scale = this.scales.y ? this.scales.y : this.parent.scale_y;
195 const x =
196 x_scale.model.type === 'date'
197 ? getDate(this.model.get('x'))
198 : this.model.get('x');
199 const y =
200 y_scale.model.type === 'date'
201 ? getDate(this.model.get('y'))
202 : this.model.get('y');
203 const transform =
204 'translate(' +
205 (x_scale.scale(x) + x_scale.offset) +
206 ', ' +
207 (y_scale.scale(y) + y_scale.offset) +
208 ')';
209 this.pieSelection
210 .transition('positionCenter')
211 .duration(animation_duration)
212 .attr('transform', transform);
213 }
214
215 private updateRadius(animate?: boolean) {
216 const animation_duration =
217 animate === true ? this.parent.model.get('animation_duration') : 0;
218
219 const radius = this.model.get('radius');
220 const inner_radius = this.model.get('inner_radius');
221 const display_labels = this.model.get('display_labels');
222
223 if (display_labels === 'inside') {
224 this.arc.outerRadius(radius).innerRadius(inner_radius);
225 } else if (display_labels === 'outside') {
226 this.arc.outerRadius(radius * 0.8).innerRadius(inner_radius * 0.8);
227 this.outerArc.innerRadius(radius * 0.9).outerRadius(radius * 0.9);
228 }
229
230 const slices = this.pieSelection.select('.slices');
231 const labels = this.pieSelection.select('.labels');
232 const lines = this.pieSelection.select('.lines');
233
234 const that = this;
235
236 slices
237 .selectAll('.slice')
238 .transition('update_radius')
239 .duration(animation_duration)
240 .attr('d', this.arc);
241
242 if (display_labels === 'inside') {
243 labels
244 .selectAll('text')
245 .transition('update_radius')
246 .duration(animation_duration)
247 .attr('transform', (d: d3.DefaultArcObject) => {
248 return 'translate(' + that.arc.centroid(d) + ')';
249 });
250 } else if (display_labels === 'outside') {
251 labels
252 .selectAll('text')
253 .transition('update_radius')
254 .duration(animation_duration)
255 .attr('transform', (d: d3.DefaultArcObject) => {
256 const pos = that.outerArc.centroid(d);
257 pos[0] = radius * (that.midAngleLocation(d) === 'left' ? -1 : 1);
258 return 'translate(' + pos + ')';
259 });
260
261 lines
262 .selectAll('polyline')
263 .transition('update_radius')
264 .duration(animation_duration)
265 .attr('points', (d: d3.DefaultArcObject) => {
266 const pos = that.outerArc.centroid(d);
267 pos[0] =
268 radius * 0.95 * (that.midAngleLocation(d) === 'left' ? -1 : 1);
269 return [
270 that.arc.centroid(d),
271 that.outerArc.centroid(d),
272 pos,
273 ].toString();
274 });
275 }
276 }
277
278 private midAngleLocation(arc_data) {
279 // decides if the location of the mid angle of the arc is toward left or right (to aid the
280 // placement of label text)
281 const mid_angle = (arc_data.startAngle + arc_data.endAngle) / 2;
282 return mid_angle > Math.PI || (mid_angle < 0 && mid_angle > -Math.PI)
283 ? 'left'
284 : 'right';
285 }
286
287 draw(animate?: boolean) {
288 this.set_ranges();
289 this.positionCenter(animate);
290
291 this.d3Pie = d3
292 .pie<Slice>()
293 .startAngle((this.model.get('start_angle') * 2 * Math.PI) / 360)
294 .endAngle((this.model.get('end_angle') * 2 * Math.PI) / 360)
295 .value((d: Slice) => {
296 return d.size;
297 });
298
299 if (!this.model.get('sort')) {
300 this.d3Pie.sort(null);
301 }
302
303 this.updateSlices(animate);
304 this.updateLabels(animate);
305 this.updatePolylines(animate);
306 }
307
308 private updateSlices(animate?: boolean) {
309 const that = this;
310 const animation_duration =
311 animate === true ? this.parent.model.get('animation_duration') : 0;
312
313 // update pie slices
314 const slices = this.pieSelection
315 .select('.slices')
316 .selectAll('.slice')
317 .data(this.d3Pie(this.model.mark_data));
318
319 const stroke = this.model.get('stroke');
320
321 slices
322 .enter()
323 .append('path')
324 .attr('class', 'slice')
325 .each(function (d) {
326 this._current = d;
327 })
328 .on('click', (d, i) => {
329 return that.event_dispatcher('element_clicked', { data: d, index: i });
330 })
331 .merge(slices)
332 .transition('draw')
333 .duration(animation_duration)
334 .style('fill', (d, i) => that.get_mark_color(d.data, i))
335 .style('stroke', stroke)
336 .style('opacity', (d, i) => that.get_mark_opacity(d.data, i))
337 .attrTween('d', function (d) {
338 const interpolate = d3.interpolate(this._current, d);
339 this._current = d;
340 return function (t) {
341 return that.arc(interpolate(t));
342 };
343 });
344
345 slices
346 .exit()
347 .transition('remove')
348 .duration(animation_duration)
349 .style('opacity', 0)
350 .remove();
351
352 this.apply_styles();
353 }
354
355 private updateLabels(animate?: boolean) {
356 const that = this;
357 const animation_duration =
358 animate === true ? this.parent.model.get('animation_duration') : 0;
359
360 // Update labels
361 const display_labels = this.model.get('display_labels');
362 const display_values = this.model.get('display_values');
363
364 const values_format = d3.format(this.model.get('values_format'));
365
366 const labels = this.pieSelection
367 .select('.labels')
368 .selectAll('text')
369 .data(this.d3Pie(this.model.mark_data));
370
371 const labelsTransition = labels
372 .enter()
373 .append('text')
374 .classed('pie_label', true)
375 .attr('dy', '.35em')
376 .style('opacity', 0)
377 .each(function (d) {
378 this._current = d;
379 })
380 .merge(labels)
381 .transition('draw')
382 .duration(animation_duration)
383 .text((d) => {
384 if (d.data.label === '') {
385 return '';
386 }
387
388 if (display_values) {
389 return d.data.label + ': ' + values_format(d.data.size);
390 }
391
392 return d.data.label;
393 })
394 .style('font-weight', this.model.get('font_weight'))
395 .style('font-size', this.model.get('font_size'))
396 .style('opacity', (d) =>
397 display_labels === 'none' || d.value == 0 ? 0 : 1
398 );
399
400 const color = this.model.get('label_color');
401 if (color !== undefined) {
402 labelsTransition.style('fill', color);
403 }
404
405 if (display_labels === 'inside') {
406 labelsTransition
407 .attr('transform', (d) => 'translate(' + this.arc.centroid(d) + ')')
408 .style('text-anchor', 'middle');
409 } else if (display_labels === 'outside') {
410 labelsTransition
411 .attrTween('transform', function (d) {
412 const interpolate = d3.interpolate(this._current, d);
413 const _this = this;
414 return function (t) {
415 const d2 = interpolate(t);
416 _this._current = d2;
417 const pos = that.outerArc.centroid(d2);
418 pos[0] =
419 that.model.get('radius') *
420 (that.midAngleLocation(d) === 'left' ? -1 : 1);
421 return 'translate(' + pos + ')';
422 };
423 })
424 .styleTween('text-anchor', function (d) {
425 const interpolate = d3.interpolate(this._current, d);
426 return function (t) {
427 const d2 = interpolate(t);
428 return that.midAngleLocation(d2) === 'left' ? 'end' : 'start';
429 };
430 });
431 }
432
433 labels.exit().remove();
434 }
435
436 updatePolylines(animate?: boolean) {
437 const that = this;
438 const animation_duration =
439 animate === true ? this.parent.model.get('animation_duration') : 0;
440
441 const display_labels = this.model.get('display_labels');
442
443 const polylines = this.pieSelection
444 .select('.lines')
445 .selectAll('polyline')
446 .data(this.d3Pie(this.model.mark_data));
447
448 const polylinesTransition = polylines
449 .enter()
450 .append('polyline')
451 .each(function (d) {
452 this._current = d;
453 })
454 .merge(polylines)
455 .transition('draw')
456 .duration(animation_duration)
457 .style('opacity', (d: any) =>
458 display_labels !== 'outside' || d.value == 0 || d.data.label === ''
459 ? 0
460 : 1
461 );
462
463 if (display_labels === 'outside') {
464 polylinesTransition.attrTween('points', function (d: any) {
465 const interpolate = d3.interpolate(this._current, d);
466 const _this = this;
467 return function (t) {
468 const d2 = interpolate(t);
469 _this._current = d2;
470 const pos = that.outerArc.centroid(d2);
471 pos[0] =
472 that.model.get('radius') *
473 0.95 *
474 (that.midAngleLocation(d2) === 'left' ? -1 : 1);
475 return [
476 that.arc.centroid(d2),
477 that.outerArc.centroid(d2),
478 pos,
479 ].toString();
480 };
481 });
482 }
483
484 polylines.exit().remove();
485 }
486
487 clear_style(style_dict, indices?) {
488 // Function to clear the style of a dict on some or all the elements of the
489 // chart. If indices is null, clears the style on all elements. If
490 // not, clears on only the elements whose indices are matching.
491 let elements = this.pieSelection.selectAll('.slice');
492 if (indices) {
493 elements = elements.filter((d, index) => {
494 return indices.indexOf(index) !== -1;
495 });
496 }
497 const clearing_style = {};
498 for (const key in style_dict) {
499 clearing_style[key] = null;
500 }
501 applyStyles(elements, clearing_style);
502 }
503
504 set_style_on_elements(style, indices?) {
505 // If the index array is undefined or of length=0, exit the
506 // function without doing anything
507 if (indices === undefined || indices === null || indices.length === 0) {
508 return;
509 }
510 let elements = this.pieSelection.selectAll('.slice');
511 elements = elements.filter((data, index) => {
512 return indices.indexOf(index) !== -1;
513 });
514 applyStyles(elements, style);
515 }
516
517 set_default_style(indices?) {
518 // For all the elements with index in the list indices, the default
519 // style is applied.
520 const stroke = this.model.get('stroke');
521
522 // Update pie slices
523 this.pieSelection
524 .select('.slices')
525 .selectAll('.slice')
526 .style('fill', (d, i) => this.get_mark_color(d.data, i))
527 .style('stroke', stroke)
528 .style('opacity', (d, i) => this.get_mark_opacity(d.data, i));
529 }
530
531 click_handler(args) {
532 const index = args.index;
533 const that = this;
534 const idx = this.model.get('selected') || [];
535 let selected: number[] = Array.from(idx);
536 // index of slice i. Checking if it is already present in the list.
537 const elem_index = selected.indexOf(index);
538 // Replacement for "Accel" modifier.
539 const accelKey = d3GetEvent().ctrlKey || d3GetEvent().metaKey;
540 if (elem_index > -1 && accelKey) {
541 // if the index is already selected and if accel key is
542 // pressed, remove the element from the list
543 selected.splice(elem_index, 1);
544 } else {
545 if (d3GetEvent().shiftKey) {
546 //If shift is pressed and the element is already
547 //selected, do not do anything
548 if (elem_index > -1) {
549 return;
550 }
551 //Add elements before or after the index of the current
552 //slice which has been clicked
553 const min_index = selected.length !== 0 ? d3.min(selected) : -1;
554 const max_index =
555 selected.length !== 0
556 ? d3.max(selected)
557 : that.model.mark_data.length;
558 if (index > max_index) {
559 _.range(max_index + 1, index).forEach((i) => {
560 selected.push(i);
561 });
562 } else if (index < min_index) {
563 _.range(index + 1, min_index).forEach((i) => {
564 selected.push(i);
565 });
566 }
567 } else if (!accelKey) {
568 selected = [];
569 }
570 // updating the array containing the slice indexes selected
571 // and updating the style
572 selected.push(index);
573 }
574 this.model.set(
575 'selected',
576 selected.length === 0 ? null : new Uint32Array(selected),
577 { updated_view: this }
578 );
579 this.touch();
580 const e = d3GetEvent();
581 if (e.cancelBubble !== undefined) {
582 // IE
583 e.cancelBubble = true;
584 }
585 if (e.stopPropagation) {
586 e.stopPropagation();
587 }
588 e.preventDefault();
589 this.selected_indices = selected;
590 this.apply_styles();
591 }
592
593 reset_selection() {
594 this.model.set('selected', null);
595 this.touch();
596 this.selected_indices = null;
597 this.clear_style(this.selected_style);
598 this.clear_style(this.unselected_style);
599 this.set_default_style();
600 }
601
602 compute_view_padding() {
603 const scales = this.model.get('scales');
604 const r = d3.max([
605 this.model.get('radius'),
606 this.model.get('inner_radius'),
607 ]);
608
609 const xPadding = scales.x ? r + 1 : 0;
610 const yPadding = scales.y ? r + 1 : 0;
611 if (xPadding !== this.xPadding || yPadding !== this.yPadding) {
612 this.xPadding = xPadding;
613 this.yPadding = yPadding;
614 this.trigger('mark_padding_updated');
615 }
616 }
617
618 private d3Pie: d3.Pie<any, Slice>;
619 // private pieSelection: d3.Selection<SVGGElement, Slice, any, any>;
620 private pieSelection: any;
621 private arc: d3.Arc<any, d3.DefaultArcObject>;
622 private outerArc: d3.Arc<any, d3.DefaultArcObject>;
623
624 model: PieModel;
625 }