Debian Codegraph @

bqplot/js/src/MarketMap.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 widgets from '@jupyter-widgets/base';
17 import * as _ from 'underscore';
18
19 import { MessageLoop } from '@lumino/messaging';
20
21 import { Widget } from '@lumino/widgets';
22
23 import * as d3 from 'd3';
24 // var d3 =Object.assign({}, require("d3-array"), require("d3-format"), require("d3-selection"), require("d3-selection-multi"), require("d3-shape"));
25 import { Figure } from './Figure';
26 import { Tooltip } from './Tooltip';
27 import { Scale } from './Scale';
28 import { ColorScale } from './ColorScale';
29 import * as popperreference from './PopperReference';
30 import popper from 'popper.js';
31 import { applyAttrs, applyStyles, getLuminoWidget } from './utils';
32
33 export class MarketMap extends Figure {
34 protected renderImpl() {
35 const figureSize = this.getFigureSize();
36 this.width = figureSize.width;
37 this.height = figureSize.height;
38
39 this.id = widgets.uuid();
40
41 this.scales = {};
42 this.set_top_el_style();
43
44 this.margin = this.model.get('map_margin');
45 this.num_rows = this.model.get('rows');
46 this.num_cols = this.model.get('cols');
47 this.row_groups = this.model.get('row_groups');
48 this.enable_select = this.model.get('enable_select');
49
50 this.update_data();
51 // set the number of rows and columns in the map
52 this.set_area_dimensions(this.data.length);
53
54 if (this.model.get('theme')) {
55 this.svg.classed(this.model.get('theme'), true);
56 }
57 this.fig = this.svg
58 .append('g')
59 .attr(
60 'transform',
61 'translate(' + this.margin.left + ',' + this.margin.top + ')'
62 );
63
64 this.fig_map = this.fig.append('g');
65 this.fig_axes = this.fig.append('g');
66 this.fig_click = this.fig.append('g');
67 this.fig_hover = this.fig.append('g');
68 this.fig_names = this.fig
69 .append('g')
70 .style('display', this.model.get('show_groups') ? 'inline' : 'none');
71
72 this.fig_map.classed('g-map', true);
73 this.fig_axes.classed('g-axes', true);
74 this.fig_click.classed('g-click', true);
75 this.fig_hover.classed('g-hover', true);
76 this.fig_names.classed('g-names', true);
77
78 // code for tool tip to be displayed
79 this.tooltip_div = d3
80 .select(document.createElement('div'))
81 .attr('class', 'mark_tooltip');
82 applyStyles(this.tooltip_div, { opacity: 0, 'pointer-events': 'none' });
83
84 const freeze_tooltip_loc = this.model.get('freeze_tooltip_location');
85 if (freeze_tooltip_loc) {
86 this.popper_reference = new popperreference.ElementReference(
87 this.svg.node()
88 );
89 } else {
90 this.popper_reference = new popperreference.PositionReference({
91 x: 0,
92 y: 0,
93 width: 20,
94 height: 20,
95 });
96 }
97 this.popper = new popper(this.popper_reference, this.tooltip_div.node(), {
98 placement: 'auto',
99 });
100
101 this.update_default_tooltip();
102
103 this.selected_stroke = this.model.get('selected_stroke');
104 this.hovered_stroke = this.model.get('hovered_stroke');
105
106 this.update_plotarea_dimensions();
107
108 this.title = this.fig
109 .append('text')
110 .attr('class', 'mainheading')
111 .text(this.model.get('title'));
112 applyAttrs(this.title, {
113 x: 0.5 * this.plotarea_width,
114 y: -(this.margin.top / 2.0),
115 dy: '1em',
116 });
117 applyStyles(this.title, this.model.get('title_style'));
118
119 return this.create_scale_views().then(() => {
120 this.create_listeners();
121
122 this.axis_views = new widgets.ViewList(this.add_axis, null, this);
123 const axis_views_updated = this.axis_views.update(this.model.get('axes'));
124 this.model.on('change:axes', (model, value, options) => {
125 this.axis_views.update(value);
126 });
127
128 this.draw_map();
129 document.body.appendChild(this.tooltip_div.node());
130 this.create_tooltip_widget();
131
132 // In the classic notebook, we should relayout the figure on
133 // resize of the main window.
134 window.addEventListener('resize', this.debouncedRelayout);
135 this.once('remove', () => {
136 window.removeEventListener('resize', this.debouncedRelayout);
137 });
138
139 return Promise.all([Promise.resolve(), axis_views_updated]);
140 });
141 }
142
143 set_top_el_style() {
144 this.el.style['user-select'] = 'none';
145 this.el.style['ms-user-select'] = 'none';
146 this.el.style['moz-user-select'] = 'none';
147 this.el.style['khtml-user-select'] = 'none';
148 this.el.style['webkit-user-select'] = 'none';
149 }
150
151 update_plotarea_dimensions() {
152 this.plotarea_width = this.width - this.margin.left - this.margin.right;
153 this.plotarea_height = this.height - this.margin.top - this.margin.bottom;
154 this.column_width = parseFloat(
155 (this.plotarea_width / this.num_cols).toFixed(2)
156 );
157 this.row_height = parseFloat(
158 (this.plotarea_height / this.num_rows).toFixed(2)
159 );
160 }
161
162 reset_drawing_controls() {
163 // Properties useful in drawing the map
164 this.prev_x = 0;
165 this.prev_y = -1;
166 this.y_direction = 1; // for y direction 1 means going to the right
167 this.x_direction = 1; // for x direction 1 means going down
168 this.group_iter = 1;
169 }
170
171 create_listeners() {
172 this.listenTo(this.model, 'change:scales', this.create_scale_views);
173 this.listenTo(this.model, 'change:color', this.recolor_chart);
174 this.listenTo(this.model, 'change:colors', this.colors_updated);
175 this.listenTo(this.model, 'change:show_groups', this.show_groups);
176 this.listenTo(
177 this.model,
178 'change:selected_stroke',
179 this.update_selected_stroke
180 );
181 this.listenTo(
182 this.model,
183 'change:hovered_stroke',
184 this.update_hovered_stroke
185 );
186 this.listenTo(this.model, 'change:font_style', this.update_font_style);
187 this.model.on_some_change(
188 ['title', 'title_style'],
189 this.update_title,
190 this
191 );
192 this.listenTo(this.model, 'change:selected', function () {
193 this.clear_selected();
194 this.apply_selected();
195 });
196 this.model.on_some_change(
197 ['names', 'groups', 'ref_data'],
198 function () {
199 this.update_data();
200 this.compute_dimensions_and_draw();
201 },
202 this
203 );
204 this.listenTo(this.model, 'change:rows', function (model, value) {
205 this.num_rows = value;
206 this.compute_dimensions_and_draw();
207 });
208 this.listenTo(this.model, 'change:cols', function (model, value) {
209 this.num_cols = value;
210 this.compute_dimensions_and_draw();
211 });
212 this.listenTo(this.model, 'change:row_groups', function (model, value) {
213 this.row_groups = value;
214 this.compute_dimensions_and_draw();
215 });
216 this.listenTo(
217 this.model,
218 'change:tooltip_widget',
219 this.create_tooltip_widget
220 );
221 this.listenTo(
222 this.model,
223 'change:tooltip_fields',
224 this.update_default_tooltip
225 );
226 this.listenTo(
227 this.model,
228 'change:tooltip_formats',
229 this.update_default_tooltip
230 );
231 }
232
233 update_title(model, value) {
234 this.title.text(this.model.get('title'));
235 applyStyles(this.title, this.model.get('title_style'));
236 }
237
238 relayout() {
239 const that = this;
240
241 const figureSize = this.getFigureSize();
242 this.width = figureSize.width;
243 this.height = figureSize.height;
244
245 window.requestAnimationFrame(() => {
246 // update ranges
247 that.margin = that.model.get('map_margin');
248 that.update_plotarea_dimensions();
249
250 // transform figure
251 that.fig.attr(
252 'transform',
253 'translate(' + that.margin.left + ',' + that.margin.top + ')'
254 );
255 applyAttrs(that.title, {
256 x: 0.5 * that.plotarea_width,
257 y: -(that.margin.top / 2.0),
258 dy: '1em',
259 });
260
261 that.draw_map();
262
263 // Drawing the selected cells
264 that.clear_selected();
265 that.apply_selected();
266
267 // When map is expanded or contracted, there should not be any
268 // accidental hovers. To prevent this, the following call is made.
269 that.fig_hover.selectAll('rect').remove();
270 that.hide_tooltip();
271 that.trigger('margin_updated');
272 });
273 }
274
275 update_data() {
276 const that = this;
277 this.model.set('selected', []);
278 this.data = this.model.get('names') || [];
279 this.ref_data = this.model.get('ref_data');
280 this.group_data = this.model.get('groups');
281 this.groups = _.uniq(this.group_data, true);
282 let display_text = this.model.get('display_text');
283 display_text =
284 display_text === null || display_text.length === 0
285 ? this.data
286 : display_text;
287
288 this.colors = this.model.get('colors');
289 const num_colors = this.colors.length;
290 this.colors_map = function (d) {
291 return that.get_color(d, num_colors);
292 };
293 const color_data = this.model.get('color');
294 const mapped_data = _.map(this.data, (d, i) => {
295 return {
296 display: display_text[i],
297 name: d,
298 color: Number.isNaN(color_data[i]) ? undefined : color_data[i],
299 group: this.group_data[i],
300 ref_data:
301 this.ref_data === null || this.ref_data === undefined
302 ? null
303 : this.ref_data[i],
304 };
305 });
306
307 this.update_domains();
308 this.grouped_data = _.groupBy(mapped_data, (d, i) => {
309 return that.group_data[i];
310 });
311 this.groups = [];
312 this.running_sums = [];
313 this.running_sums[0] = 0;
314 let count = 0;
315 for (const key in this.grouped_data) {
316 this.groups.push(key);
317 count += this.grouped_data[key].length;
318 this.running_sums.push(count);
319 }
320 this.running_sums.pop();
321 }
322
323 update_domains() {
324 const color_scale_model = this.model.get('scales').color;
325 const color_data = this.model.get('color');
326 if (color_scale_model && color_data.length > 0) {
327 color_scale_model.compute_and_set_domain(color_data, this.model.model_id);
328 }
329 }
330
331 set_area_dimensions(num_items) {
332 this.num_rows = this.model.get('rows');
333 this.num_cols = this.model.get('cols');
334 this.row_groups = this.model.get('row_groups');
335
336 if (
337 this.num_cols !== undefined &&
338 this.num_cols !== null &&
339 this.num_cols !== 0
340 ) {
341 // When the number of row groups is greater than 1, the number
342 // of columns has to be an odd number. This is to
343 // ensure the continuity of the waffles when groups are spread
344 // across multiple row groups
345 if (this.row_groups > 1 && this.num_cols % 2 === 0) {
346 this.num_cols++;
347 }
348 this.num_rows = Math.floor(num_items / this.num_cols);
349 this.num_rows =
350 num_items % this.num_cols === 0 ? this.num_rows : this.num_rows + 1;
351 } else if (
352 this.num_rows !== undefined &&
353 this.num_rows !== null &&
354 this.num_rows !== 0
355 ) {
356 this.num_cols = Math.floor(num_items / this.num_rows);
357 this.num_cols =
358 num_items % this.num_rows === 0 ? this.num_cols : this.num_cols + 1;
359 if (this.row_groups > 1 && this.num_cols % 2 === 0) {
360 this.num_cols++;
361 }
362 } else {
363 this.num_cols = Math.floor(Math.sqrt(num_items));
364 if (this.row_groups > 1 && this.num_cols % 2 === 0) {
365 this.num_cols++;
366 }
367 this.num_rows = Math.floor(num_items / this.num_cols);
368 this.num_rows =
369 num_items % this.num_cols === 0 ? this.num_rows : this.num_rows + 1;
370 }
371
372 // row_groups cannot be greater than the number of rows
373 this.row_groups = Math.min(this.row_groups, this.num_rows);
374 // if there is only one row_group, then the number of columns are
375 // not necessarily equal to the variable this.num_cols as we draw
376 // row first. So we need to adjust the this.num_cols variable
377 // according to the num_rows.
378 if (this.row_groups == 1) {
379 this.num_cols = Math.floor(num_items / this.num_rows);
380 this.num_cols =
381 num_items % this.num_rows === 0 ? this.num_cols : this.num_cols + 1;
382 }
383 // depending on the number of rows, we need to decide when to
384 // switch direction. The below functions tells us where to switch
385 // direction.
386 this.set_row_limits();
387 }
388
389 compute_dimensions_and_draw() {
390 this.set_area_dimensions(this.data.length);
391 this.update_plotarea_dimensions();
392 this.draw_map();
393
394 this.clear_selected();
395 this.apply_selected();
396
397 // when data is changed
398 this.fig_hover.selectAll('rect').remove();
399 this.hide_tooltip();
400 }
401
402 update_default_tooltip() {
403 this.tooltip_fields = this.model.get('tooltip_fields');
404 const formats = this.model.get('tooltip_formats');
405 this.tooltip_formats = this.tooltip_fields.map((field, index) => {
406 const fmt = formats[index];
407 if (fmt === undefined || fmt === '') {
408 return (d) => d;
409 } else {
410 return d3.format(fmt) as (d: number) => string;
411 }
412 });
413 }
414
415 create_scale_views() {
416 for (const key in this.scales) {
417 this.stopListening(this.scales[key]);
418 }
419 const scale_models = this.model.get('scales');
420 const that = this;
421 const scale_promises = {};
422 _.each(scale_models, (model: widgets.WidgetModel, key) => {
423 scale_promises[key] = that.create_child_view(model);
424 });
425 return widgets
426 .resolvePromisesDict(scale_promises)
427 .then((d: { [key: string]: Scale }) => {
428 that.scales = d;
429 that.set_scales();
430 });
431 }
432
433 set_scales() {
434 const that = this;
435 const color_scale = this.scales.color as ColorScale;
436 if (color_scale) {
437 color_scale.set_range();
438 color_scale.on('color_scale_range_changed', that.update_map_colors, that);
439 this.update_domains();
440 this.listenTo(color_scale, 'domain_changed', () => {
441 that.update_map_colors();
442 });
443 this.update_map_colors();
444 }
445 }
446
447 show_groups(model, value) {
448 this.fig_names.style('display', value ? 'inline' : 'none');
449 this.fig_map
450 .selectAll('.market_map_text')
451 .style('opacity', value ? 0.2 : 1);
452 this.fig_map
453 .selectAll('.market_map_rect')
454 .style('stroke-opacity', value ? 0.2 : 1);
455 }
456
457 draw_map() {
458 this.reset_drawing_controls();
459 // Removing pre existing elements from the map
460 this.fig_map.selectAll('.element_group').remove();
461 this.fig_names.selectAll('.names_object').remove();
462 this.rect_groups = this.fig_map
463 .selectAll('.element_group')
464 .data(this.groups);
465 const color_scale = this.scales.color;
466
467 const that = this;
468 this.rect_groups = this.rect_groups
469 .enter()
470 .append('g')
471 .attr('class', 'element_group')
472 .attr('transform', (d, i) => {
473 return that.get_group_transform(i);
474 })
475 .merge(
476 this.rect_groups as d3.Selection<
477 SVGGElement,
478 any,
479 SVGGraphicsElement,
480 any
481 >
482 );
483
484 this.rect_groups.exit().remove();
485 this.end_points = [];
486 this.rect_groups.nodes().forEach((d, i) => {
487 const data = that.grouped_data[that.groups[i]];
488 const return_arr = that.get_new_cords();
489 const ends = that.get_end_points(
490 return_arr[2],
491 data.length,
492 return_arr[0],
493 return_arr[1],
494 return_arr[3],
495 return_arr[4]
496 );
497 ends.forEach((point) => {
498 that.end_points.push(point);
499 });
500 const element_count = that.running_sums[i];
501
502 let groups = d3
503 .select(d)
504 .selectAll<SVGGElement, undefined>('.rect_element')
505 .data(data);
506
507 // Appending the <g> <rect> and <text> elements to the newly
508 // added nodes
509 const new_groups = groups
510 .enter()
511 .append('g')
512 .classed('rect_element', true);
513
514 new_groups
515 .append('rect')
516 .attr('x', 0)
517 .attr('y', 0)
518 .classed('market_map_rect', true);
519
520 // Grouping calls to style into a single call to styles
521 // leads to build error despite the import of d3-selection-multi
522 new_groups
523 .append('text')
524 .classed('market_map_text', true)
525 .style('text-anchor', 'middle')
526 .style('pointer-events', 'none')
527 .style('dominant-baseline', 'central');
528
529 groups = new_groups.merge(groups);
530
531 // Update the attributes of the entire set of nodes
532 groups
533 .attr('transform', (data, ind) => {
534 return that.get_cell_transform(ind);
535 })
536 .on('click', function (data, ind) {
537 that.cell_click_handler(data, element_count + ind, this);
538 })
539 .on('mouseover', function (data, ind) {
540 that.mouseover_handler(data, element_count + ind, this);
541 })
542 .on('mousemove', (data) => {
543 that.mousemove_handler();
544 })
545 .on('mouseout', function (data, ind) {
546 that.mouseout_handler(data, element_count + ind, this);
547 })
548 .attr('class', function (data, index) {
549 return (
550 d3.select(this).attr('class') +
551 ' ' +
552 'rect_' +
553 (element_count + index)
554 );
555 });
556
557 groups
558 .selectAll('.market_map_rect')
559 .attr('width', that.column_width)
560 .attr('height', that.row_height)
561 .style('stroke-opacity', that.model.get('show_groups') ? 0.2 : 1.0)
562 .style('stroke', that.model.get('stroke'))
563 .style('fill', (elem: any, j) => {
564 return color_scale && elem.color !== undefined && elem.color !== null
565 ? color_scale.scale(elem.color)
566 : that.colors_map(i);
567 });
568
569 groups
570 .selectAll('.market_map_text')
571 .attr('x', that.column_width / 2.0)
572 .attr('y', that.row_height / 2.0)
573 .text((data: any, j) => {
574 return data.display;
575 })
576 .style('opacity', that.model.get('show_groups') ? 0.2 : 1.0);
577
578 // Removing the old nodes
579 groups.exit().remove();
580 that.create_bounding_path(d, ends);
581 const min_x = d3.min(ends, (end_point: any) => {
582 return end_point.x;
583 });
584 const min_y = d3.min(ends, (end_point: any) => {
585 return end_point.y;
586 });
587
588 const obj = that.fig_names
589 .append('foreignObject')
590 .attr('class', 'names_object')
591 .attr('x', min_x)
592 .attr('y', min_y)
593 .append('xhtml:div')
594 .attr('class', 'names_div')
595 .text(that.groups[i]);
596 applyStyles(obj, {
597 display: 'flex',
598 'flex-direction': 'row',
599 'align-content': 'center',
600 'align-items': 'center',
601 width: '100%',
602 height: '100%',
603 'justify-content': 'center',
604 'word-wrap': 'break-word',
605 font: '24px sans-serif',
606 color: 'black',
607 });
608 });
609 this.update_font_style();
610 this.draw_group_names();
611 }
612
613 draw_group_names() {
614 // Get all the bounding rects of the paths around each of the
615 // sectors. Get their client bounding rect.
616 const paths = this.svg
617 .selectAll('.bounding_path')
618 .nodes() as SVGPathElement[];
619 const clientRects = paths.map((path) => {
620 return path.getBoundingClientRect();
621 });
622 const text_elements = this.fig_names
623 .selectAll('.names_object')
624 .data(clientRects);
625 text_elements
626 .attr('width', (d) => {
627 return d.width;
628 })
629 .attr('height', (d) => {
630 return d.height;
631 });
632 }
633
634 recolor_chart() {
635 const that = this;
636 this.update_data();
637 this.rect_groups = this.fig.selectAll('.element_group').data(this.groups);
638 const color_scale = this.scales.color;
639
640 this.rect_groups.nodes().forEach((d, i) => {
641 const data = that.grouped_data[that.groups[i]];
642 d3.select(d)
643 .selectAll('.rect_element')
644 .data(data)
645 .select('rect')
646 .style('stroke', that.model.get('stroke'))
647 .style('fill', (elem: any, j) => {
648 return color_scale && elem.color !== undefined && elem.color !== null
649 ? color_scale.scale(elem.color)
650 : that.colors_map(i);
651 });
652 });
653 }
654
655 update_font_style() {
656 // This is a bit awkward because we did not figure out how to get
657 // Typescript to recognize the d3-select-multi typings.
658 const x: any = this.svg.selectAll('.market_map_text');
659 applyStyles(x, this.model.get('font_style'));
660 }
661
662 update_map_colors() {
663 if (this.rect_groups !== undefined && this.rect_groups !== null) {
664 this.recolor_chart();
665 }
666 }
667
668 cell_click_handler(data, id, cell) {
669 if (this.model.get('enable_select')) {
670 const selected = Object.assign(
671 this.model.get('selected').slice(),
672 this.model.get('selected')
673 );
674 const index = selected.indexOf(data.name);
675 if (index == -1) {
676 // not already selected, so add to selected
677 selected.push(data.name);
678 } else {
679 // already in selected list, so delete from selected
680 selected.splice(index, 1);
681 }
682 this.model.set('selected', selected);
683 this.touch();
684 }
685 }
686
687 apply_selected() {
688 const selected = this.model.get('selected');
689 const that = this;
690 if (selected === undefined || selected === null || selected.length === 0) {
691 this.clear_selected();
692 } else {
693 selected.forEach((data) => {
694 const selected_cell = that.fig_map
695 .selectAll('.rect_element')
696 .filter((d: any, i) => {
697 return d.name === data;
698 });
699
700 const rect = that.fig_click
701 .append('rect')
702 .data(selected_cell.data())
703 .attr('transform', selected_cell.attr('transform'))
704 .attr('x', 0)
705 .attr('y', 0)
706 .attr('width', that.column_width)
707 .attr('height', that.row_height);
708 applyStyles(rect, {
709 stroke: that.selected_stroke,
710 'stroke-width': '3px',
711 fill: 'none',
712 });
713 });
714 }
715 }
716
717 clear_selected() {
718 this.fig_click.selectAll('rect').remove();
719 }
720
721 mouseover_handler(data, id, cell) {
722 const transform = d3.select(cell).attr('transform');
723 if (this.model.get('enable_hover')) {
724 const rect = this.fig_hover
725 .append('rect')
726 .attr('class', 'hover_' + id)
727 .attr('transform', transform)
728 .attr('x', 0)
729 .attr('y', 0)
730 .attr('width', this.column_width)
731 .attr('height', this.row_height);
732 applyStyles(rect, {
733 stroke: this.hovered_stroke,
734 'stroke-width': '3px',
735 fill: 'none',
736 'pointer-events': 'none',
737 });
738 this.show_tooltip(d3.event, data);
739 this.send({ event: 'hover', data: data.name, ref_data: data.ref_data });
740 }
741 }
742
743 update_selected_stroke(model, value) {
744 this.selected_stroke = value;
745 this.fig_click.selectAll('rect').style('stroke', value);
746 }
747
748 update_hovered_stroke(model, value) {
749 this.hovered_stroke = value;
750 // I do not need to update anything else because when hovered color
751 // is being updated you are not hovering over anything.
752 }
753
754 mouseout_handler(data, id, cell) {
755 this.fig_hover.select('.hover_' + id).remove();
756 this.hide_tooltip();
757 }
758
759 show_tooltip(event, data) {
760 const that = this;
761 if (
762 !this.tooltip_view &&
763 (!this.tooltip_fields || this.tooltip_fields.length == 0)
764 ) {
765 return;
766 } else {
767 const tooltip_div = this.tooltip_div;
768 tooltip_div.transition().style('opacity', 0.9).style('display', null);
769
770 this.move_tooltip();
771 tooltip_div.select('table').remove();
772
773 const ref_data = data.ref_data;
774 if (!this.tooltip_view) {
775 const tooltip_table = tooltip_div
776 .append('table')
777 .selectAll('tr')
778 .data(this.tooltip_fields);
779
780 tooltip_table.exit().remove();
781 const table_rows = tooltip_table.enter().append('tr');
782
783 table_rows
784 .append('td')
785 .attr('class', 'tooltiptext')
786 .text((datum) => {
787 return datum;
788 });
789
790 table_rows
791 .append('td')
792 .attr('class', 'tooltiptext')
793 .text((datum, index) => {
794 if (ref_data === null || ref_data === undefined) {
795 return null;
796 }
797
798 if (ref_data[datum] === null || ref_data[datum] === undefined) {
799 return 'N/A';
800 }
801
802 return that.tooltip_formats[index](ref_data[datum]);
803 });
804 }
805 this.popper.enableEventListeners();
806 this.move_tooltip();
807 }
808 }
809
810 mousemove_handler() {
811 this.move_tooltip();
812 }
813
814 move_tooltip() {
815 (this.popper_reference as any).x = d3.event.clientX;
816 (this.popper_reference as any).y = d3.event.clientY;
817 this.popper.scheduleUpdate();
818 }
819
820 hide_tooltip() {
821 this.tooltip_div.style('pointer-events', 'none');
822 this.tooltip_div.transition().style('opacity', 0).style('display', 'none');
823 this.popper.disableEventListeners();
824 }
825
826 create_tooltip_widget() {
827 const tooltip_model = this.model.get('tooltip_widget');
828 if (this.tooltip_view !== null && this.tooltip_view !== undefined) {
829 //remove the previous tooltip
830 this.tooltip_view.remove();
831 this.tooltip_view = null;
832 }
833 const that = this;
834 if (tooltip_model) {
835 const tooltip_widget_creation_promise =
836 this.create_child_view(tooltip_model);
837 tooltip_widget_creation_promise.then((view) => {
838 that.tooltip_view = view as Tooltip;
839
840 MessageLoop.sendMessage(getLuminoWidget(view), Widget.Msg.BeforeAttach);
841 that.tooltip_div.node().appendChild(view.el);
842 MessageLoop.sendMessage(getLuminoWidget(view), Widget.Msg.AfterAttach);
843 });
844 }
845 }
846
847 get_group_transform(index) {
848 return 'translate(' + '0' + ', 0)';
849 }
850
851 get_cell_transform(index) {
852 if (!this.past_border_y()) {
853 if (this.past_border_x()) {
854 this.y_direction = -1 * this.y_direction;
855 this.prev_x += this.x_direction;
856 } else {
857 this.x_direction = -1 * this.x_direction;
858 this.prev_y += this.y_direction;
859 this.group_iter += 1;
860 }
861 } else {
862 this.prev_y += this.y_direction;
863 }
864 return (
865 'translate(' +
866 this.prev_x * this.column_width +
867 ', ' +
868 this.prev_y * this.row_height +
869 ')'
870 );
871 }
872
873 get_new_cords() {
874 let new_x = this.prev_x;
875 let new_y = this.prev_y;
876 let y_direction = this.y_direction;
877 let x_direction = this.x_direction;
878 let group_iter = this.group_iter;
879 if (!this.past_border_y()) {
880 if (this.past_border_x()) {
881 y_direction = -1 * this.y_direction;
882 new_x += this.x_direction;
883 } else {
884 x_direction = -1 * this.x_direction;
885 new_y += this.y_direction;
886 group_iter += 1;
887 }
888 } else {
889 new_y += this.y_direction;
890 }
891 return [
892 new_x,
893 new_y,
894 group_iter,
895 x_direction,
896 y_direction,
897 new_x * this.column_width,
898 new_y * this.row_height,
899 ];
900 }
901
902 past_border_y() {
903 if (this.y_direction == 1) {
904 return this.prev_y + 1 < this.row_limits[this.group_iter];
905 } else {
906 return this.prev_y - 1 > this.row_limits[this.group_iter - 1] - 1;
907 }
908 }
909
910 past_border_x() {
911 if (this.x_direction == 1) {
912 return this.prev_x + 1 < this.num_cols;
913 } else {
914 return this.prev_x - 1 > -1;
915 }
916 }
917
918 colors_updated() {
919 this.colors = this.model.get('colors');
920 this.recolor_chart();
921 }
922
923 get_color(index, length) {
924 return this.colors[index % length];
925 }
926
927 set_row_limits() {
928 const step = Math.floor(this.num_rows / this.row_groups);
929 this.row_limits = [];
930 for (let iter = this.row_groups - 1; iter > -1; iter--) {
931 this.row_limits.unshift(iter * step);
932 }
933 this.row_limits[this.row_groups] = this.num_rows;
934 }
935
936 get_end_points(
937 group_iter,
938 num_cells,
939 start_col,
940 start_row,
941 x_direction,
942 y_direction
943 ) {
944 //start_row is the 0-based index and not a 1-based index, i.e., it
945 //is not the column number in the truest sense
946 // Function to get the end points of the rectangle representing the
947 // groups.
948 // Requires the direction variables to be updated before this
949 // function is called
950 let top_row = this.row_limits[group_iter - 1];
951 let bottom_row = this.row_limits[group_iter];
952 let across = false;
953
954 let init_x = x_direction;
955 let init_y = y_direction;
956 const end_points = [];
957 let current_row;
958
959 const rows_remaining =
960 init_y == 1 ? bottom_row - start_row : start_row - top_row + 1;
961 let cols_remaining =
962 init_x == 1 ? this.num_cols - 1 - start_col : start_col; // this is the num of columns remaining
963 //after the cuirrent column has been filled
964 let elem_remaining = num_cells;
965 //this holds the number of continuous cols that will be filled
966 //between the current top and bottom rows
967 let num_rows = bottom_row - top_row;
968
969 if (elem_remaining !== 0) {
970 // starting corner of the path
971 this.calc_end_point_source(start_col, start_row, init_x, init_y).forEach(
972 (d) => {
973 end_points.push(d);
974 }
975 );
976 const elem_filled = Math.min(rows_remaining, elem_remaining);
977
978 if (elem_filled === elem_remaining) {
979 // There are enough elements only to fill one column
980 // partially. We add the three end points and exit
981 // The adjacent corner from the starting corner. This is
982 // required because the elements are filled in the first
983 // row itself.
984 this.calc_end_point_source(
985 start_col,
986 start_row,
987 -1 * init_x,
988 init_y
989 ).forEach((d) => {
990 end_points.push(d);
991 });
992
993 current_row = start_row + (elem_remaining - 1) * init_y;
994 this.calc_end_point_dest(
995 start_col,
996 current_row,
997 -1 * init_x,
998 init_y
999 ).forEach((e) => {
1000 end_points.push(e);
1001 });
1002 this.calc_end_point_dest(
1003 start_col,
1004 current_row,
1005 init_x,
1006 init_y
1007 ).forEach((e) => {
1008 end_points.push(e);
1009 });
1010
1011 /*
1012 console.log("new set");
1013 end_points.forEach(function(point) { console.log(point); });
1014 console.log("end set");
1015 */
1016
1017 return end_points;
1018 }
1019 elem_remaining = elem_remaining - elem_filled;
1020 if (cols_remaining === 0) {
1021 // Since this is the last column, the adjacent corner from
1022 // the starting corner is added here too
1023 this.calc_end_point_source(
1024 start_col,
1025 start_row,
1026 init_x * -1,
1027 init_y
1028 ).forEach((d) => {
1029 end_points.push(d);
1030 });
1031 } else if (rows_remaining !== bottom_row - top_row) {
1032 // If the starting row is not the starting row of a group,
1033 // the poirnt adjacent to the starting point needs to be
1034 // added.
1035 this.calc_end_point_source(
1036 start_col,
1037 start_row,
1038 init_x * -1,
1039 init_y
1040 ).forEach((d) => {
1041 end_points.push(d);
1042 });
1043
1044 if (elem_remaining > num_rows) {
1045 // If next row is completely filled, then the top row
1046 // element of the next column is an end point. That is
1047 // being added here.
1048 this.calc_end_point_dest(
1049 start_col + init_x,
1050 init_y == 1 ? top_row : bottom_row - 1,
1051 init_x * -1,
1052 init_y * -1
1053 ).forEach((d) => {
1054 end_points.push(d);
1055 });
1056 }
1057 } else if (elem_remaining < num_rows) {
1058 // one continuous row in this case
1059 this.calc_end_point_source(
1060 start_col,
1061 start_row,
1062 -1 * init_x,
1063 init_y
1064 ).forEach((d) => {
1065 end_points.push(d);
1066 });
1067 }
1068 start_row = start_row + init_y * (elem_filled - 1);
1069 //first set of end points are added here
1070 this.calc_end_point_dest(
1071 start_col,
1072 start_row,
1073 -1 * init_x,
1074 init_y
1075 ).forEach((d) => {
1076 end_points.push(d);
1077 });
1078 if (elem_remaining === 0) {
1079 this.calc_end_point_dest(start_col, start_row, init_x, init_y).forEach(
1080 (d) => {
1081 end_points.push(d);
1082 }
1083 );
1084
1085 /*
1086 console.log("new set");
1087 end_points.forEach(function(point) { console.log(point); });
1088 console.log("end set");
1089 */
1090
1091 return end_points;
1092 }
1093 if (cols_remaining !== 0 && elem_remaining > num_rows) {
1094 start_col = start_col + init_x;
1095 }
1096 }
1097
1098 while (elem_remaining > num_rows) {
1099 let no_cont_cols;
1100 if (num_rows * cols_remaining < elem_remaining) {
1101 no_cont_cols = cols_remaining;
1102 const leftover_elem = elem_remaining - no_cont_cols * num_rows;
1103 no_cont_cols += Math.floor(
1104 leftover_elem /
1105 (this.row_limits[group_iter + 1] - this.row_limits[group_iter])
1106 );
1107 } else {
1108 no_cont_cols = Math.floor(elem_remaining / num_rows);
1109 }
1110
1111 if (no_cont_cols > cols_remaining) {
1112 start_col = init_x === 1 ? this.num_cols - 1 : 0;
1113 if (cols_remaining !== 0) {
1114 this.calc_end_point_dest(start_col, top_row, init_x, -1).forEach(
1115 (d) => {
1116 end_points.push(d);
1117 }
1118 );
1119 }
1120 no_cont_cols = cols_remaining;
1121 cols_remaining = this.num_cols;
1122 group_iter += 1;
1123 top_row = bottom_row;
1124 bottom_row = this.row_limits[group_iter];
1125 start_row = top_row;
1126 init_x = -1 * init_x;
1127 init_y = Math.pow(-1, no_cont_cols) * init_y * -1;
1128 this.calc_end_point_dest(
1129 start_col,
1130 bottom_row - 1,
1131 -1 * init_x,
1132 1
1133 ).forEach((d) => {
1134 end_points.push(d);
1135 });
1136 } else if (no_cont_cols === cols_remaining) {
1137 start_col = init_x === 1 ? this.num_cols - 1 : 0;
1138 if (cols_remaining !== 0) {
1139 this.calc_end_point_dest(start_col, top_row, init_x, -1).forEach(
1140 (d) => {
1141 end_points.push(d);
1142 }
1143 );
1144 }
1145 no_cont_cols = cols_remaining;
1146 cols_remaining = this.num_cols;
1147 group_iter += 1;
1148 if (group_iter < this.row_limits.length) {
1149 top_row = bottom_row;
1150 bottom_row = this.row_limits[group_iter];
1151 start_row = top_row;
1152 init_x = -1 * init_x;
1153 init_y = Math.pow(-1, no_cont_cols) * init_y * -1;
1154 across = true;
1155 } else {
1156 init_y = 1;
1157 init_x = 1;
1158 }
1159 } else {
1160 // The number of elements are such that the row group is
1161 // not exhausted.
1162 init_y = Math.pow(-1, no_cont_cols) * init_y;
1163 //As I am moving down this time, next time I will move up
1164 //and I might not reach the top row, it might be an end
1165 //point.
1166 start_row = init_y === 1 ? top_row : bottom_row - 1;
1167 start_col = start_col + init_x * (no_cont_cols - 1);
1168 this.calc_end_point_source(
1169 start_col,
1170 start_row,
1171 -1 * init_x,
1172 init_y
1173 ).forEach((d) => {
1174 end_points.push(d);
1175 });
1176 }
1177 elem_remaining -= no_cont_cols * num_rows;
1178 num_rows = bottom_row - top_row;
1179 //reset direction
1180 //this is an end point
1181 }
1182 //all elements are exhausted
1183 if (elem_remaining === 0) {
1184 // The column is exactly filled. In this case, the only end
1185 // point I need to add is the outer edge w.r.t. the direction
1186 // in which we are travelling
1187 start_row = init_y === 1 ? bottom_row - 1 : top_row;
1188 init_x = across ? -1 * init_x : init_x;
1189 this.calc_end_point_dest(start_col, start_row, init_x, init_y).forEach(
1190 (d) => {
1191 end_points.push(d);
1192 }
1193 );
1194 } else {
1195 // The previous column was exactly filled and the last column
1196 // is partially filled
1197 init_y = -1 * init_y; // Since we are in the next column, the direction of y has to be reversed
1198 start_row = init_y === 1 ? top_row : bottom_row - 1;
1199 start_col = across ? start_col : start_col + init_x;
1200
1201 // this is the outer edge of the start of the last column w.r.t
1202 // the current direction of travel.
1203 this.calc_end_point_source(
1204 start_col,
1205 start_row,
1206 init_x * -1,
1207 init_y
1208 ).forEach((d) => {
1209 end_points.push(d);
1210 });
1211
1212 // The points corresponding to the cell at which we stop.
1213 current_row = start_row + (elem_remaining - 1) * init_y; // this is the row in which we end
1214 // Two points need to be added. The boundary of the last cell
1215 // in the y-direction.
1216 this.calc_end_point_dest(start_col, current_row, init_x, init_y).forEach(
1217 (d) => {
1218 end_points.push(d);
1219 }
1220 );
1221 this.calc_end_point_dest(
1222 start_col,
1223 current_row,
1224 -1 * init_x,
1225 init_y
1226 ).forEach((d) => {
1227 end_points.push(d);
1228 });
1229 }
1230
1231 /*
1232 console.log("new set");
1233 end_points.forEach(function(point) { console.log(point); });
1234 console.log("end set");
1235 */
1236
1237 return end_points;
1238 }
1239
1240 create_bounding_path(elem, end_points) {
1241 const values = [];
1242 const editing_copy = end_points.slice();
1243 values.push(end_points[0]);
1244 editing_copy.splice(0, 1);
1245 //do union based on which direction you are trying to move in and
1246 //draw the path
1247 //best way seems to be horizaontal followed by vertical
1248 const props = ['x', 'y'];
1249 let iter = 0;
1250 let prop = props[iter % 2];
1251 let other_prop = props[(iter + 1) % 2];
1252 const curr_elem = values[0];
1253 let match = curr_elem[prop];
1254 let dim = curr_elem[other_prop];
1255 let max_iter = 2 * editing_copy.length;
1256 let final_val = 0;
1257 while (editing_copy.length > 1 && max_iter > 0) {
1258 const filtered_array = editing_copy.filter((elem) => {
1259 return elem[prop] == match;
1260 });
1261 if (filtered_array.length > 0) {
1262 iter++;
1263 const min_elem = d3.min(filtered_array, (elem) => {
1264 return elem[other_prop] as number;
1265 });
1266 const max_elem = d3.max(filtered_array, (elem) => {
1267 return elem[other_prop] as number;
1268 });
1269 if (min_elem < dim && max_elem > dim) {
1270 if (prop == 'y') {
1271 if (this.x_direction == 1) {
1272 final_val = max_elem;
1273 } else {
1274 final_val = min_elem;
1275 }
1276 } else {
1277 // There are elements greater than and lesser than
1278 // reference value. I am trying to see if there are
1279 // multiple elements greater or lesser. If there is
1280 // only one in one of the directions, that is the
1281 // direction I draw the line in.
1282 const lesser_arr = filtered_array.filter((elem) => {
1283 return elem[other_prop] < dim;
1284 });
1285 const greater_arr = filtered_array.filter((elem) => {
1286 return elem[other_prop] > dim;
1287 });
1288
1289 if (lesser_arr.length == 1) {
1290 final_val = min_elem;
1291 } else if (greater_arr.length == 1) {
1292 final_val = max_elem;
1293 } else {
1294 final_val = d3.max(lesser_arr, (elem) => {
1295 return elem[other_prop] as number;
1296 });
1297 }
1298 }
1299 } else {
1300 if (min_elem > dim) {
1301 final_val = min_elem;
1302 } else {
1303 final_val = max_elem;
1304 }
1305 }
1306 const match_elem = editing_copy.filter((elem) => {
1307 return elem[prop] == match && elem[other_prop] == final_val;
1308 });
1309 match_elem.forEach((elem) => {
1310 editing_copy.splice(editing_copy.indexOf(elem), 1);
1311 });
1312 const value = {};
1313 value[prop] = match;
1314 value[other_prop] = final_val;
1315 values.push(value);
1316 } else {
1317 final_val = dim;
1318 }
1319 //swap prop and other_prop
1320 const temp = prop;
1321 prop = other_prop;
1322 other_prop = temp;
1323
1324 dim = match;
1325 match = final_val;
1326 max_iter--;
1327 }
1328 if (editing_copy.length > 0) {
1329 values.push(editing_copy[0]);
1330 }
1331 values.push(end_points[0]);
1332 const line = d3
1333 .line()
1334 .curve(d3.curveLinear)
1335 .x((d: any) => {
1336 return d.x;
1337 })
1338 .y((d: any) => {
1339 return d.y;
1340 });
1341 const bounding_path = d3
1342 .select(elem)
1343 .append('path')
1344 .attr('class', 'bounding_path')
1345 .attr('d', () => {
1346 return line(values);
1347 })
1348 .attr('fill', 'none')
1349 .style('stroke', this.model.get('group_stroke'))
1350 .style('stroke-width', 3);
1351 return bounding_path;
1352 }
1353
1354 calc_end_point_source(curr_x, curr_y, x_direction, y_direction) {
1355 curr_y = y_direction == 1 ? curr_y : curr_y + 1;
1356 curr_x = x_direction == 1 ? curr_x : curr_x + 1;
1357 return [{ x: curr_x * this.column_width, y: curr_y * this.row_height }];
1358 }
1359
1360 calc_end_point_dest(curr_x, curr_y, x_direction, y_direction) {
1361 curr_y = y_direction == -1 ? curr_y : curr_y + 1;
1362 curr_x = x_direction == -1 ? curr_x : curr_x + 1;
1363 return [{ x: curr_x * this.column_width, y: curr_y * this.row_height }];
1364 }
1365
1366 scales: { [key: string]: Scale };
1367 num_rows: number;
1368 num_cols: number;
1369 row_groups: number;
1370 enable_select: boolean;
1371 data: string[];
1372 fig_map: d3.Selection<SVGGElement, any, any, any>;
1373 fig_click: d3.Selection<SVGGElement, any, any, any>;
1374 fig_hover: d3.Selection<SVGGElement, any, any, any>;
1375 fig_names: d3.Selection<SVGGElement, any, any, any>;
1376 selected_stroke: string;
1377 hovered_stroke: string;
1378 column_width: number;
1379 row_height: number;
1380 prev_x: number;
1381 prev_y: number;
1382 y_direction: number;
1383 x_direction: number;
1384 group_iter: number;
1385 ref_data: any[];
1386 group_data: number[];
1387 groups: any[];
1388 colors: string[];
1389 colors_map: any;
1390 grouped_data: { [key: string]: { [key: string]: any }[] };
1391 running_sums: number[];
1392 tooltip_fields: (number | string)[];
1393 tooltip_formats: ((d: number | string) => number | string)[];
1394 rect_groups: d3.Selection<d3.BaseType, any, SVGGraphicsElement, any>;
1395 end_points: number[];
1396 tooltip_view: Tooltip;
1397 row_limits: number[];
1398 }