Debian Codegraph @

bqplot/js/src/Bars.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 { BarData, BarGroupValue, BarsModel } from './BarsModel';
21 import { applyStyles } from './utils';
22 import { LinearScale } from './LinearScale';
23 import { LogScale } from './LogScale';
24 import { isOrdinalScale } from './OrdinalScale';
25
26 export class Bars extends Mark {
27 async render() {
28 const base_creation_promise = super.render.apply(this);
29
30 // Two scales to draw the bars.
31 this.stackedScale = d3.scaleBand();
32 this.groupedScale = d3.scaleBand();
33
34 this.selected_indices = this.model.get('selected');
35 this.selected_style = this.model.get('selected_style');
36 this.unselected_style = this.model.get('unselected_style');
37
38 this.display_el_classes = ['bar', 'legendtext'];
39
40 this.displayed.then(() => {
41 this.parent.tooltip_div.node().appendChild(this.tooltip_div.node());
42 this.create_tooltip();
43 });
44
45 await base_creation_promise;
46
47 this.event_listeners = {};
48 this.process_interactions();
49 this.create_listeners();
50 this.compute_view_padding();
51 this.draw(false);
52 }
53
54 private setScaleOrientation(): void {
55 // TODO: we should probably use this.model.get("orientation")?
56 // var orient = this.model.get("orientation");
57 this.domScale = this.scales.x; //(orient === "vertical") ? this.scales.x : this.scales.y;
58 this.rangeScale = this.scales.y; //(orient === "vertical") ? this.scales.y : this.scales.x;
59 }
60
61 set_ranges(): void {
62 const orient = this.model.get('orientation');
63 this.setScaleOrientation();
64 const dom = orient === 'vertical' ? 'x' : 'y';
65 const rang = orient === 'vertical' ? 'y' : 'x';
66 if (!isOrdinalScale(this.domScale)) {
67 this.domScale.set_range(
68 this.parent.padded_range(dom, this.domScale.model)
69 );
70 } else {
71 this.domScale.set_range(
72 this.parent.padded_range(dom, this.domScale.model),
73 this.model.get('padding')
74 );
75 }
76 this.rangeScale.set_range(
77 this.parent.padded_range(rang, this.rangeScale.model)
78 );
79 // x_offset is set later by the adjustOffset method
80 // This differs because it is not constant for a scale.
81 // Changes based on the data.
82 this.domOffset = 0;
83 }
84
85 set_positional_scales(): void {
86 const x_scale = this.scales.x,
87 y_scale = this.scales.y;
88 this.listenTo(x_scale, 'domain_changed', function () {
89 if (!this.model.dirty) {
90 this.draw(true);
91 }
92 });
93 this.listenTo(y_scale, 'domain_changed', function () {
94 if (!this.model.dirty) {
95 this.draw(true);
96 }
97 });
98 }
99
100 private adjustOffset(): void {
101 // In the case of a linear scale, and when plotting ordinal data,
102 // the value have to be negatively offset by half of the width of
103 // the bars, because ordinal scales give the values corresponding
104 // to the start of the bin but linear scale gives the actual value.
105 if (!isOrdinalScale(this.domScale)) {
106 if (this.align === 'center') {
107 this.domOffset = -(this.stackedScale.bandwidth() / 2).toFixed(2);
108 } else if (this.align === 'left') {
109 this.domOffset = -this.stackedScale.bandwidth().toFixed(2);
110 } else {
111 this.domOffset = 0;
112 }
113 } else {
114 if (this.align === 'center') {
115 this.domOffset = 0;
116 } else if (this.align === 'left') {
117 this.domOffset = -(this.stackedScale.bandwidth() / 2);
118 } else {
119 this.domOffset = this.stackedScale.bandwidth() / 2;
120 }
121 }
122 }
123
124 create_listeners(): void {
125 super.create_listeners.apply(this);
126
127 this.d3el
128 .on('mouseover', () => {
129 this.event_dispatcher('mouse_over');
130 })
131 .on('mousemove', () => {
132 this.event_dispatcher('mouse_move');
133 })
134 .on('mouseout', () => {
135 this.event_dispatcher('mouse_out');
136 });
137
138 this.listenTo(this.model, 'data_updated', () => {
139 //animate bars on data update
140 const animate = true;
141 this.draw(animate);
142 });
143
144 this.listenTo(this.model, 'change:colors', this.updateColors);
145 this.listenTo(this.model, 'change:opacities', this.updateColors);
146 this.listenTo(this.model, 'colors_updated', this.updateColors);
147 this.listenTo(this.model, 'change:type', this.updateType);
148 // FIXME: These are expensive calls for changing padding and align
149 this.listenTo(this.model, 'change:align', this.relayout);
150 this.listenTo(this.model, 'change:padding', this.relayout);
151 this.listenTo(this.model, 'change:orientation', this.relayout);
152 this.listenTo(this.model, 'change:tooltip', this.create_tooltip);
153 this.model.on_some_change(
154 ['stroke', 'fill', 'stroke_width'],
155 this.apply_styles,
156 this
157 );
158 this.listenTo(this.model, 'change:selected', this.updateSelected);
159 this.listenTo(this.model, 'change:interactions', this.process_interactions);
160 this.listenTo(this.parent, 'bg_clicked', () => {
161 this.event_dispatcher('parent_clicked');
162 });
163
164 this.model.on_some_change(
165 [
166 'label_display_format',
167 'label_font_style',
168 'label_display',
169 'label_display_vertical_offset',
170 'label_display_horizontal_offset',
171 ],
172 this.draw,
173 this
174 );
175 }
176
177 process_click(interaction: string): void {
178 super.process_click(interaction);
179
180 if (interaction === 'select') {
181 this.event_listeners.parent_clicked = this.reset_selection;
182 this.event_listeners.element_clicked = this.bar_click_handler;
183 }
184 }
185
186 private drawZeroLine(): void {
187 this.setScaleOrientation();
188
189 const rangeScale = this.rangeScale.scale;
190 const orient = this.model.get('orientation');
191
192 if (orient === 'vertical') {
193 this.d3el
194 .select('.zeroLine')
195 .attr('x1', 0)
196 .attr('x2', this.parent.plotarea_width)
197 .attr('y1', rangeScale(this.model.baseValue))
198 .attr('y2', rangeScale(this.model.baseValue));
199 } else {
200 this.d3el
201 .select('.zeroLine')
202 .attr('x1', rangeScale(this.model.baseValue))
203 .attr('x2', rangeScale(this.model.baseValue))
204 .attr('y1', 0)
205 .attr('y2', this.parent.plotarea_height);
206 }
207 }
208
209 private updateInternalScales(): void {
210 this.stackedScale.rangeRound(this.set_x_range());
211 // This padding logic is duplicated from OrdinalScale
212 // and should be factorized somewhere
213 const padding = this.model.get('padding');
214 this.stackedScale.paddingInner(padding);
215 this.stackedScale.paddingOuter(padding / 2.0);
216 this.adjustOffset();
217 this.groupedScale.rangeRound([
218 0,
219 Math.round(this.stackedScale.bandwidth() * 100) / 100,
220 ]);
221 }
222
223 relayout(): void {
224 this.set_ranges();
225 this.compute_view_padding();
226 this.drawZeroLine();
227 this.updateInternalScales();
228 this.drawBars();
229 }
230
231 invert_point(pixel) {
232 if (pixel === undefined) {
233 this.model.set('selected', null);
234 this.touch();
235 return;
236 }
237
238 const abs_diff = this.xPixels.map((elem) => {
239 return Math.abs(elem - pixel);
240 });
241 this.model.set(
242 'selected',
243 new Uint32Array([abs_diff.indexOf(d3.min(abs_diff))])
244 );
245 this.touch();
246 }
247
248 selector_changed(point_selector, rect_selector) {
249 if (point_selector === undefined) {
250 this.model.set('selected', null);
251 this.touch();
252 return [];
253 }
254 const pixels = this.pixelCoords;
255 const indices = new Uint32Array(_.range(pixels.length));
256 // Here we only select bar groups. It shouldn't be too hard to select
257 // individual bars, the `selected` attribute would then be a list of pairs.
258 const selected_groups = indices.filter((index) => {
259 const bars = pixels[index];
260 for (let i = 0; i < bars.length; i++) {
261 if (rect_selector(bars[i])) {
262 return true;
263 }
264 }
265 return false;
266 });
267 this.model.set('selected', selected_groups);
268 this.touch();
269 }
270
271 private updateSelected() {
272 this.selected_indices = this.model.get('selected');
273 this.apply_styles();
274 }
275
276 draw(animate?: boolean) {
277 this.set_ranges();
278 let barGroups: d3.Selection<any, any, any, any> = this.d3el
279 .selectAll('.bargroup')
280 .data(this.model.mark_data, (d: any) => d.key);
281
282 // this.stackedScale is the ordinal scale used to draw the bars. If a linear
283 // scale is given, then the ordinal scale is created from the
284 // linear scale.
285 if (!isOrdinalScale(this.domScale)) {
286 const modelDomain = this.model.mark_data.map((elem) => elem.key);
287 this.stackedScale.domain(modelDomain);
288 } else {
289 this.stackedScale.domain(this.domScale.scale.domain());
290 }
291
292 this.updateInternalScales();
293
294 if (this.model.mark_data.length > 0) {
295 this.groupedScale
296 .domain(_.range(this.model.mark_data[0].values.length))
297 .rangeRound([0, Math.round(this.stackedScale.bandwidth() * 100) / 100]);
298 }
299
300 // Since we will assign the enter and update selection of barGroups to
301 // itself, we may remove exit selection first.
302 barGroups.exit().remove();
303
304 barGroups = barGroups
305 .enter()
306 .append('g')
307 .attr('class', 'bargroup')
308 .merge(barGroups);
309 // The below function sorts the DOM elements so that the order of
310 // the DOM elements matches the order of the data they are bound
311 // to. This is required to maintain integrity with selection.
312 barGroups.order();
313
314 barGroups.on('click', (d, i) => {
315 return this.event_dispatcher('element_clicked', { data: d, index: i });
316 });
317
318 const barsSel = barGroups.selectAll('.bar').data((d) => d.values);
319
320 // default values for width and height are to ensure smooth
321 // transitions
322 barsSel
323 .enter()
324 .append('rect')
325 .attr('class', 'bar')
326 .attr('width', 0)
327 .attr('height', 0);
328
329 barsSel.exit().remove();
330
331 if (!this.model.get('label_display')) {
332 barGroups.selectAll('text').remove();
333 }
334
335 if (this.model.get('label_display')) {
336 const barLabels = barGroups.selectAll('.bar_label').data((d) => d.values);
337
338 barLabels.exit().remove();
339
340 barLabels
341 .enter()
342 .append('text')
343 .attr('class', 'bar_label')
344 .attr('width', 0)
345 .attr('height', 0);
346 }
347
348 this.drawBars(animate);
349 // this.drawBarLabels(); TODO
350
351 this.apply_styles();
352
353 this.d3el.selectAll('.zeroLine').remove();
354 this.d3el.append('g').append('line').attr('class', 'zeroLine');
355
356 this.drawZeroLine();
357 }
358
359 private drawBars(animate?: boolean) {
360 const barGroups = this.d3el.selectAll('.bargroup');
361 const barsSel = barGroups.selectAll('.bar');
362 const animationDuration =
363 animate === true ? this.parent.model.get('animation_duration') : 0;
364
365 const domScale = this.domScale;
366 const rangeScale = this.rangeScale.scale;
367
368 const dom = this.orientation === 'vertical' ? 'x' : 'y';
369 const rang = this.orientation === 'vertical' ? 'y' : 'x';
370
371 const domControl = this.orientation === 'vertical' ? 'width' : 'height';
372 const rangeControl = this.orientation === 'vertical' ? 'height' : 'width';
373
374 if (isOrdinalScale(domScale)) {
375 const domMax = d3.max(this.parent.range(dom));
376 barGroups.attr('transform', (d: BarData) => {
377 if (this.orientation === 'vertical') {
378 return (
379 'translate(' +
380 ((domScale.scale(d.key) !== undefined
381 ? domScale.scale(d.key)
382 : domMax) +
383 this.domOffset) +
384 ', 0)'
385 );
386 } else {
387 return (
388 'translate(0, ' +
389 ((domScale.scale(d.key) !== undefined
390 ? domScale.scale(d.key)
391 : domMax) +
392 this.domOffset) +
393 ')'
394 );
395 }
396 });
397 } else {
398 barGroups.attr('transform', (d: BarData) => {
399 if (this.orientation === 'vertical') {
400 return (
401 'translate(' + (domScale.scale(d.key) + this.domOffset) + ', 0)'
402 );
403 } else {
404 return (
405 'translate(0, ' + (domScale.scale(d.key) + this.domOffset) + ')'
406 );
407 }
408 });
409 }
410
411 const isStacked = this.model.get('type') === 'stacked';
412 let bandWidth = 1.0;
413 if (isStacked) {
414 bandWidth = Math.max(1.0, this.stackedScale.bandwidth());
415 barsSel
416 .transition()
417 .duration(animationDuration)
418 .attr(dom, 0)
419 .attr(domControl, bandWidth.toFixed(2))
420 .attr(rang, (d: BarGroupValue) =>
421 rang === 'y' ? rangeScale(d.y1) : rangeScale(d.y0)
422 )
423 .attr(rangeControl, (d: BarGroupValue) =>
424 Math.abs(rangeScale(d.y0) - rangeScale(d.y1))
425 );
426 } else {
427 bandWidth = Math.max(1.0, this.groupedScale.bandwidth());
428 barsSel
429 .transition()
430 .duration(animationDuration)
431 .attr(dom, (datum, index) => this.groupedScale(index))
432 .attr(domControl, bandWidth.toFixed(2))
433 .attr(rang, (d: BarGroupValue) =>
434 d3.min([rangeScale(d.y), rangeScale(this.model.baseValue)])
435 )
436 .attr(rangeControl, (d: BarGroupValue) =>
437 Math.abs(rangeScale(this.model.baseValue) - rangeScale(d.y))
438 );
439 }
440
441 // adding/updating bar data labels
442 this.manageBarLabels(barGroups, bandWidth, dom, rang);
443
444 this.pixelCoords = this.model.mark_data.map((d) => {
445 const key = d.key;
446 const groupDom = domScale.scale(key) + this.domOffset;
447 return d.values.map((d) => {
448 const rectCoords: {
449 x: number;
450 y: number;
451 width: number;
452 height: number;
453 } = { x: 0, y: 0, width: 0, height: 0 };
454 rectCoords[dom] = isStacked
455 ? groupDom
456 : groupDom + this.groupedScale(d.subIndex);
457 rectCoords[rang] = isStacked
458 ? rang === 'y'
459 ? rangeScale(d.y1)
460 : rangeScale(d.y0)
461 : d3.min([rangeScale(d.y), rangeScale(this.model.baseValue)]);
462 rectCoords[domControl] = bandWidth;
463 rectCoords[rangeControl] = isStacked
464 ? Math.abs(rangeScale(d.y0) - rangeScale(d.y1))
465 : Math.abs(rangeScale(this.model.baseValue) - rangeScale(d.y));
466 return [
467 [rectCoords.x, rectCoords.x + rectCoords.width],
468 [rectCoords.y, rectCoords.y + rectCoords.height],
469 ];
470 });
471 });
472 this.xPixels = this.model.mark_data.map((el) => {
473 return domScale.scale(el.key) + domScale.offset;
474 });
475 }
476
477 /**
478 * Get the vertical label offset from the model
479 */
480 get offsetVertical(): number {
481 return this.model.get('label_display_vertical_offset');
482 }
483
484 /**
485 * Get the horizontal label offset from the model
486 */
487 get offsetHorizontal(): number {
488 return this.model.get('label_display_horizontal_offset');
489 }
490
491 /**
492 * Get the baseline parameter from the model
493 */
494 get baseLine(): number {
495 return this.model.get('base');
496 }
497
498 /**
499 * Get the bar chart's orientation
500 */
501 get orientation(): 'horizontal' | 'vertical' {
502 return this.model.get('orientation');
503 }
504
505 /**
506 * Get the bar chart's alignment
507 */
508 get align(): 'center' | 'left' | 'right' {
509 return this.model.get('align');
510 }
511
512 /**
513 * Main entry point function for adding bar labels
514 * @param barGroups - D3 selection for all bar groups
515 * @param bandWidth - Bandwidth of the x or y axis
516 * @param dom - X or y axis (depending on oridnetation)
517 * @param rang - X or y axis (depending on orientation)
518 */
519 private manageBarLabels(
520 barGroups: any,
521 bandWidth: number,
522 dom: string,
523 rang: string
524 ): void {
525 if (!this.model.get('label_display')) {
526 return;
527 }
528
529 // Ladding the labels
530 if (this.model.get('type') === 'stacked') {
531 this.stackedBarLabels(barGroups, bandWidth, dom, rang);
532 } else {
533 this.groupedBarLabels(barGroups, bandWidth);
534 }
535
536 // Styling the labels
537 this.updateBarLabelsStyle();
538 }
539
540 /**
541 * All bars are stacked by default. The only other value this parameter can take is 'grouped'
542 * @param barGroups - D3 selection for bar groups
543 * @param bandWidth - Bandwidth parameter for the bar dimensions
544 * @param dom - X or y axis (depending on oridnetation)
545 * @param rang - X or y axis (depending on oridnetation)
546 */
547 private stackedBarLabels(
548 barGroups: any,
549 bandWidth: number,
550 dom: string,
551 rang: string
552 ): void {
553 const barLabels = barGroups.selectAll('.bar_label');
554
555 barLabels
556 .attr(dom, (d) => 0)
557 .attr(rang, (d) => {
558 if (d.y <= this.baseLine) {
559 return this.rangeScale.scale(d.y0);
560 } else {
561 return this.rangeScale.scale(d.y1);
562 }
563 })
564 .style('font-weight', '400')
565 .style('text-anchor', (d) => this.styleBarLabelTextAnchor(d))
566 .style('dominant-baseline', (d) => this.styleBarLabelDominantBaseline(d))
567 .attr('transform', (d, i) => {
568 return this.transformBarLabel(
569 d,
570 this.offsetHorizontal,
571 this.offsetVertical,
572 bandWidth
573 );
574 });
575 }
576
577 /**
578 * Add labels for a chart with grouped bars
579 * @param barGroups - D3 selection for bar group
580 * @param bandWidth - bandwidth parameter for the X axis
581 */
582 private groupedBarLabels(barGroups: any, bandWidth: number): void {
583 const barLabels = barGroups.selectAll('.bar_label');
584
585 barLabels
586 .attr('x', (d, i) => {
587 if (this.orientation === 'horizontal') {
588 return this.rangeScale.scale(d.y);
589 } else {
590 return this.groupedScale(i);
591 }
592 })
593 .attr('y', (d, i) => {
594 if (this.orientation === 'horizontal') {
595 return this.groupedScale(i);
596 } else {
597 return this.rangeScale.scale(d.y);
598 }
599 })
600 .style('font-weight', '400')
601 .style('text-anchor', (d) => this.styleBarLabelTextAnchor(d))
602 .style('dominant-baseline', (d) => this.styleBarLabelDominantBaseline(d))
603 .attr('transform', (d) =>
604 this.transformBarLabel(
605 d,
606 this.offsetHorizontal,
607 this.offsetVertical,
608 bandWidth
609 )
610 );
611 }
612
613 /**
614 * Applies CSS translate to shift label position according
615 * to vertical/horizontal offsets
616 * @param d - Data point
617 * @param offsetHorizontal - Horizontal offset, in pixels, of the label
618 * @param offsetVertical - Vertical offset, in pixels, of the label
619 * @param bandWidth - Bandwidth parameter for the bar dimantions
620 */
621 private transformBarLabel(
622 d: BarGroupValue,
623 offsetHorizontal: number,
624 offsetVertical: number,
625 bandWidth: number
626 ): string {
627 if (this.orientation === 'horizontal') {
628 return d.y <= this.baseLine
629 ? `translate(${
630 d.y0 <= this.baseLine ? 0 - offsetVertical : 0 + offsetVertical
631 }, ${bandWidth / 2 + offsetHorizontal})`
632 : `translate(${
633 d.y1 <= this.baseLine ? 0 - offsetVertical : 0 + offsetVertical
634 }, ${bandWidth / 2 + offsetHorizontal})`;
635 } else {
636 return d.y <= this.baseLine
637 ? `translate(${bandWidth / 2 + offsetHorizontal},
638 ${
639 d.y0 <= this.baseLine
640 ? 0 - offsetVertical
641 : 0 + offsetVertical
642 })`
643 : `translate(${bandWidth / 2 + offsetHorizontal},
644 ${
645 d.y1 <= this.baseLine
646 ? 0 - offsetVertical
647 : 0 + offsetVertical
648 })`;
649 }
650 }
651
652 /**
653 * Determines the value of the text-anchor CSS attribute
654 * @param d - Data point
655 * @param i - Index number
656 */
657 private styleBarLabelTextAnchor(d: BarGroupValue): string {
658 if (this.orientation === 'horizontal') {
659 return d.y <= this.baseLine ? 'start' : 'end';
660 } else {
661 return 'middle';
662 }
663 }
664
665 /**
666 * Determines the value of the dominant-base-line CSS attribute
667 * @param d - Data point
668 * @param i - Index number
669 */
670 private styleBarLabelDominantBaseline(d: BarGroupValue): string {
671 if (this.orientation === 'horizontal') {
672 return 'central';
673 } else {
674 return d.y <= this.baseLine ? 'text-after-edge' : 'text-before-edge';
675 }
676 }
677
678 /**
679 * Adds CSS styling to the bar labels
680 */
681 private updateBarLabelsStyle(): void {
682 const displayFormatStr = this.model.get('label_display_format');
683 const displayFormat = displayFormatStr ? d3.format(displayFormatStr) : null;
684
685 let fonts = this.d3el
686 .selectAll('.bar_label')
687 .text((d: any, i) => (displayFormat ? displayFormat(d.y) : null));
688
689 const fontStyle = this.model.get('label_font_style');
690
691 for (const styleKey in fontStyle) {
692 fonts = fonts.style(styleKey, fontStyle[styleKey]);
693 }
694 }
695
696 private updateType() {
697 // We need to update domains here as the y_domain needs to be
698 // changed when we switch from stacked to grouped.
699 this.model.update_domains();
700 this.draw();
701 }
702
703 private updateColors() {
704 //the following if condition is to handle the case of single
705 //dimensional data.
706 //if y is 1-d, each bar should be of 1 color.
707 //if y is multi-dimensional, the corresponding values should be of
708 //the same color.
709 const stroke = this.model.get('stroke');
710 if (this.model.mark_data.length > 0) {
711 if (!this.model.yIs2d) {
712 this.d3el
713 .selectAll('.bar')
714 .style('fill', this.get_mark_color.bind(this))
715 .style('stroke', stroke ? stroke : this.get_mark_color.bind(this))
716 .style('opacity', this.get_mark_opacity.bind(this));
717 } else {
718 this.d3el
719 .selectAll('.bargroup')
720 .selectAll('.bar')
721 .style('fill', this.get_mark_color.bind(this))
722 .style('stroke', stroke ? stroke : this.get_mark_color.bind(this))
723 .style('opacity', this.get_mark_opacity.bind(this));
724 }
725 }
726 //legend color update
727 if (this.legendEl) {
728 this.legendEl
729 .selectAll('.legendrect')
730 .style('fill', this.get_mark_color.bind(this))
731 .style('stroke', stroke ? stroke : this.get_mark_color.bind(this))
732 .style('opacity', this.get_mark_opacity.bind(this));
733 this.legendEl
734 .selectAll('.legendtext')
735 .style('fill', this.get_mark_color.bind(this))
736 .style('stroke', stroke ? stroke : this.get_mark_color.bind(this))
737 .style('opacity', this.get_mark_opacity.bind(this));
738 }
739 }
740
741 draw_legend(elem, x_disp, y_disp, inter_x_disp, inter_y_disp) {
742 if (
743 !this.model.yIs2d &&
744 this.model.get('colors').length !== 1 &&
745 this.model.get('color_mode') !== 'element'
746 ) {
747 return [0, 0];
748 }
749
750 const legendData = this.model.mark_data[0].values.map((data) => {
751 return {
752 index: data.subIndex,
753 colorIndex: data.colorIndex,
754 opacityIndex: data.opacityIndex,
755 };
756 });
757 this.legendEl = elem.selectAll('.legend' + this.uuid).data(legendData);
758
759 const rect_dim = inter_y_disp * 0.8;
760 const legend = this.legendEl
761 .enter()
762 .append('g')
763 .attr('class', 'legend' + this.uuid)
764 .attr('transform', (d, i) => {
765 return 'translate(0, ' + (i * inter_y_disp + y_disp) + ')';
766 })
767 .on('mouseover', () => {
768 this.event_dispatcher('legend_mouse_over');
769 })
770 .on('mouseout', () => {
771 this.event_dispatcher('legend_mouse_out');
772 })
773 .on('click', () => {
774 this.event_dispatcher('legend_clicked');
775 });
776
777 legend
778 .append('rect')
779 .classed('legendrect', true)
780 .style('fill', this.get_mark_color.bind(this))
781 .attr('x', 0)
782 .attr('y', 0)
783 .attr('width', rect_dim)
784 .attr('height', rect_dim);
785
786 legend
787 .append('text')
788 .attr('class', 'legendtext')
789 .attr('x', rect_dim * 1.2)
790 .attr('y', rect_dim / 2)
791 .attr('dy', '0.35em')
792 .text((d, i) => this.model.get('labels')[i])
793 .style('fill', this.get_mark_color.bind(this));
794
795 this.legendEl = legend.merge(this.legendEl);
796
797 const max_length = d3.max(this.model.get('labels'), (d: any[]) => d.length);
798
799 this.legendEl.exit().remove();
800 return [this.model.mark_data[0].values.length, max_length];
801 }
802
803 clear_style(style, indices) {
804 if (!indices || indices.length === 0) {
805 return;
806 }
807
808 if (Object.keys(style).length === 0) {
809 return;
810 }
811
812 const elements = this.d3el.selectAll('.bargroup').filter((d, index) => {
813 return indices.indexOf(index) !== -1;
814 });
815
816 const clearing_style = {};
817 for (const key in style) {
818 clearing_style[key] = null;
819 }
820 applyStyles(elements.selectAll('.bar'), clearing_style);
821 }
822
823 set_style_on_elements(style: any, indices: number[]) {
824 if (!indices || indices.length === 0) {
825 return;
826 }
827
828 if (Object.keys(style).length === 0) {
829 return;
830 }
831
832 const elements = this.d3el.selectAll('.bargroup').filter((data, index) => {
833 return indices.indexOf(index) !== -1;
834 });
835 applyStyles(elements.selectAll('.bar'), style);
836 }
837
838 set_default_style(indices: number[]) {
839 // For all the elements with index in the list indices, the default
840 // style is applied.
841 if (!indices || indices.length === 0) {
842 return;
843 }
844
845 const fill = this.model.get('fill'),
846 stroke = this.model.get('stroke'),
847 stroke_width = this.model.get('stroke_width');
848
849 this.d3el
850 .selectAll('.bargroup')
851 .filter((data, index) => {
852 return indices.indexOf(index) !== -1;
853 })
854 .selectAll('.bar')
855 .style('fill', fill ? this.get_mark_color.bind(this) : 'none')
856 .style('stroke', stroke ? stroke : 'none')
857 .style('opacity', this.get_mark_opacity.bind(this))
858 .style('stroke-width', stroke_width);
859 }
860
861 get_mark_color(data: BarGroupValue, index: number) {
862 // Workaround for the bargroup, the color index is not the same as the bar index
863 return super.get_mark_color(data, data.colorIndex);
864 }
865
866 get_mark_opacity(data: BarGroupValue, index) {
867 // Workaround for the bargroup, the opacity index is not the same as the bar index
868 return super.get_mark_opacity(data, data.opacityIndex);
869 }
870
871 private set_x_range(): [number, number] {
872 const domScale = this.domScale;
873 if (isOrdinalScale(domScale)) {
874 return domScale.scale.range() as [number, number];
875 } else {
876 return [
877 domScale.scale(d3.min(this.stackedScale.domain())),
878 domScale.scale(d3.max(this.stackedScale.domain())),
879 ];
880 }
881 }
882
883 private bar_click_handler(args) {
884 const index = args.index;
885 const idx = this.model.get('selected') || [];
886 let selected: number[] = Array.from(idx);
887
888 // index of bar i. Checking if it is already present in the list.
889 const elem_index = selected.indexOf(index);
890 // Replacement for "Accel" modifier.
891 const accelKey = d3GetEvent().ctrlKey || d3GetEvent().metaKey;
892 if (elem_index > -1 && accelKey) {
893 // if the index is already selected and if accel key is
894 // pressed, remove the element from the list
895 selected.splice(elem_index, 1);
896 } else {
897 if (d3GetEvent().shiftKey) {
898 //If shift is pressed and the element is already
899 //selected, do not do anything
900 if (elem_index > -1) {
901 return;
902 }
903 //Add elements before or after the index of the current
904 //bar which has been clicked
905 const min_index = selected.length !== 0 ? d3.min(selected) : -1;
906 const max_index =
907 selected.length !== 0
908 ? d3.max(selected)
909 : this.model.mark_data.length;
910 if (index > max_index) {
911 _.range(max_index + 1, index + 1).forEach((i) => {
912 selected.push(i);
913 });
914 } else if (index < min_index) {
915 _.range(index, min_index).forEach((i) => {
916 selected.push(i);
917 });
918 }
919 } else if (accelKey) {
920 //If accel is pressed and the bar is not already selected
921 //add the bar to the list of selected bars.
922 selected.push(index);
923 }
924 // updating the array containing the bar indexes selected
925 // and updating the style
926 else {
927 //if accel is not pressed, then clear the selected ones
928 //and set the current element to the selected
929 selected = [];
930 selected.push(index);
931 }
932 }
933 this.model.set(
934 'selected',
935 selected.length === 0 ? null : new Uint32Array(selected),
936 { updated_view: this }
937 );
938 this.touch();
939 const e = d3GetEvent();
940 if (e.cancelBubble !== undefined) {
941 // IE
942 e.cancelBubble = true;
943 }
944 if (e.stopPropagation) {
945 e.stopPropagation();
946 }
947 e.preventDefault();
948 }
949
950 private reset_selection() {
951 this.model.set('selected', null);
952 this.selected_indices = null;
953 this.touch();
954 }
955
956 compute_view_padding() {
957 // This function returns a dictionary with keys as the scales and
958 // value as the pixel padding required for the rendering of the
959 // mark.
960 const domScale = this.domScale;
961 const orient = this.model.get('orientation');
962 let xPadding = 0;
963 const avail_space =
964 orient === 'vertical'
965 ? this.parent.plotarea_width
966 : this.parent.plotarea_height;
967 if (domScale) {
968 if (
969 this.stackedScale !== null &&
970 this.stackedScale !== undefined &&
971 this.stackedScale.domain().length !== 0
972 ) {
973 if (!isOrdinalScale(domScale)) {
974 if (this.align === 'center') {
975 xPadding =
976 avail_space / (2.0 * this.stackedScale.domain().length) + 1;
977 } else if (this.align === 'left' || this.align === 'right') {
978 xPadding = avail_space / this.stackedScale.domain().length + 1;
979 }
980 } else {
981 if (this.align === 'left' || this.align === 'right') {
982 xPadding = parseFloat(
983 (this.stackedScale.bandwidth() / 2).toFixed(2)
984 );
985 }
986 }
987 }
988 }
989 if (orient === 'vertical') {
990 if (xPadding !== this.xPadding) {
991 this.xPadding = xPadding;
992 this.trigger('mark_padding_updated');
993 //dispatch the event
994 }
995 } else {
996 if (xPadding !== this.yPadding) {
997 this.yPadding = xPadding;
998 this.trigger('mark_padding_updated');
999 //dispatch the event
1000 }
1001 }
1002 }
1003
1004 private domOffset: number;
1005 private domScale: LinearScale | LogScale;
1006 private legendEl: d3.Selection<any, any, any, any>;
1007 private pixelCoords: [[number, number], [number, number]][][];
1008 private rangeScale: LinearScale | LogScale;
1009 private stackedScale: d3.ScaleBand<any>;
1010 private groupedScale: d3.ScaleBand<any>;
1011 private xPixels: number[];
1012
1013 // Overriding super class
1014 model: BarsModel;
1015 }