Debian Codegraph @

bqplot/js/src/Graph.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 { GraphModel, LinkData, NodeData } from './GraphModel';
21 import { applyStyles } from './utils';
22
23 const arrowSize = 10;
24
25 const rotateVector = (
26 vec: { x: number; y: number },
27 ang: number
28 ): { x: number; y: number } => {
29 const cos = Math.cos(-ang);
30 const sin = Math.sin(-ang);
31 return {
32 x: vec.x * cos - vec.y * sin,
33 y: vec.x * sin + vec.y * cos,
34 };
35 };
36
37 export class Graph extends Mark {
38 async render() {
39 const base_creation_promise = super.render();
40
41 this.selected_style = this.model.get('selected_style');
42 this.unselected_style = this.model.get('unselected_style');
43 this.selected_indices = this.model.get('selected');
44
45 this.hovered_style = this.model.get('hovered_style');
46 this.unhovered_style = this.model.get('unhovered_style');
47 this.hovered_index = !this.model.get('hovered_point')
48 ? null
49 : [this.model.get('hovered_point')];
50
51 this.display_el_classes = ['element'];
52 this.event_metadata = {
53 mouse_over: {
54 msg_name: 'hover',
55 lookup_data: false,
56 hit_test: true,
57 },
58 element_clicked: {
59 msg_name: 'element_click',
60 lookup_data: false,
61 hit_test: true,
62 },
63 parent_clicked: {
64 msg_name: 'background_click',
65 hit_test: false,
66 },
67 };
68 this.displayed.then(() => {
69 this.parent.tooltip_div.node().appendChild(this.tooltip_div.node());
70 this.create_tooltip();
71 });
72
73 this.d3el.attr('class', 'network');
74
75 this.parent.svg
76 .append('defs')
77 .append('marker')
78 .attr('id', 'arrow')
79 .attr('refX', 0)
80 .attr('refY', 3)
81 .attr('markerWidth', arrowSize)
82 .attr('markerHeight', arrowSize)
83 .attr('orient', 'auto')
84 .append('path')
85 .attr('class', 'linkarrow')
86 .attr('d', 'M0,0 L0,6 L9,3 z');
87
88 await base_creation_promise;
89
90 this.event_listeners = {};
91 this.process_interactions();
92 this.create_listeners();
93 this.compute_view_padding();
94 this.draw();
95 }
96
97 set_ranges() {
98 if (this.scales.x) {
99 this.scales.x.set_range(
100 this.parent.padded_range('x', this.scales.x.model)
101 );
102 }
103 if (this.scales.y) {
104 this.scales.y.set_range(
105 this.parent.padded_range('y', this.scales.y.model)
106 );
107 }
108 }
109
110 set_positional_scales() {
111 this.listenTo(
112 this.scales.x || this.parent.scale_x,
113 'domain_changed',
114 function () {
115 if (!this.model.dirty) {
116 this.updatePosition();
117 }
118 }
119 );
120 this.listenTo(
121 this.scales.y || this.parent.scale_y,
122 'domain_changed',
123 function () {
124 if (!this.model.dirty) {
125 this.updatePosition();
126 }
127 }
128 );
129 }
130
131 relayout() {
132 this.updatePosition();
133 }
134
135 private updatePosition() {
136 this.set_ranges();
137
138 if (this.scales.x && this.scales.y) {
139 // set x and y positions on mark data manually
140 // and redraw the force layout
141 this.model.mark_data.forEach((d) => {
142 d.x = this.scales.x.scale(d.xval) + this.scales.x.offset;
143 d.y = this.scales.y.scale(d.yval) + this.scales.y.offset;
144 });
145
146 if (this.force_layout) {
147 this.force_layout
148 .nodes(this.model.mark_data)
149 .force(
150 'link',
151 d3
152 .forceLink(this.model.link_data)
153 .distance(this.model.get('link_distance'))
154 );
155
156 if (this.links) {
157 this.links.data(this.model.link_data);
158 }
159 if (this.nodes) {
160 this.nodes.data(this.force_layout.nodes());
161 }
162
163 if (this.nodes && this.links) {
164 this.tick();
165 }
166 }
167 }
168 }
169
170 initialize_additional_scales() {
171 const colorScale = this.scales.color;
172 if (colorScale) {
173 this.listenTo(colorScale, 'domain_changed', this.colorScaleUpdated);
174 colorScale.on('color_scale_range_changed', this.colorScaleUpdated, this);
175 }
176
177 const linkColorScale = this.scales.link_color;
178 if (linkColorScale) {
179 this.listenTo(
180 linkColorScale,
181 'domain_changed',
182 this.linkColorScaleUpdated
183 );
184 }
185 }
186
187 create_listeners() {
188 super.create_listeners();
189 this.d3el
190 .on('mouseover', () => {
191 this.event_dispatcher('mouse_over');
192 })
193 .on('mousemove', () => {
194 this.event_dispatcher('mouse_move');
195 })
196 .on('mouseout', () => {
197 this.event_dispatcher('mouse_out');
198 });
199
200 this.listenTo(this.model, 'change:charge', this.updateCharge);
201 this.listenTo(this.model, 'change:static', this.updateStatic);
202 this.listenTo(this.model, 'change:link_type', this.tick);
203 this.listenTo(this.model, 'change:directed', this.tick);
204 this.listenTo(this.model, 'change:link_distance', this.updateLinkDistance);
205 this.listenTo(this.model, 'data_updated', this.relayout);
206 this.listenTo(this.model, 'change:tooltip', this.create_tooltip);
207 this.listenTo(this.model, 'change:enable_hover', this.hide_tooltip);
208 this.listenTo(this.model, 'change:interactions', this.process_interactions);
209 this.listenTo(this.model, 'change:selected', this.update_selected);
210 this.listenTo(this.model, 'change:hovered_point', this.update_hovered);
211 this.listenTo(
212 this.model,
213 'change:hovered_style',
214 this.hovered_style_updated
215 );
216 this.listenTo(
217 this.model,
218 'change:unhovered_style',
219 this.unhovered_style_updated
220 );
221
222 this.listenTo(this.parent, 'bg_clicked', function () {
223 this.event_dispatcher('parent_clicked');
224 });
225 }
226
227 draw() {
228 this.set_ranges();
229 const x_scale = this.scales.x;
230 const y_scale = this.scales.y;
231 const link_color_scale = this.scales.link_color;
232
233 // clean up the old graph
234 this.d3el.selectAll('.node').remove();
235 this.d3el.selectAll('.link').remove();
236
237 if (x_scale && y_scale) {
238 //set x and y on mark data manually
239 this.model.mark_data.forEach((d) => {
240 d.x = x_scale.scale(d.xval) + x_scale.offset;
241 d.y = y_scale.scale(d.yval) + y_scale.offset;
242 });
243 }
244
245 const box = this.parent.fig.node().getBBox();
246 const width = box.width;
247 const height = box.height;
248 this.force_layout = d3
249 .forceSimulation<NodeData>()
250 .force('center', d3.forceCenter(width / 2, height / 2))
251 .force(
252 'forceX',
253 d3
254 .forceX()
255 .strength(0.1)
256 .x(width / 2)
257 )
258 .force(
259 'forceY',
260 d3
261 .forceY()
262 .strength(0.1)
263 .y(height / 2)
264 );
265
266 if (!x_scale && !y_scale) {
267 this.force_layout
268 .force('charge', d3.forceManyBody().strength(this.model.get('charge')))
269 .on('tick', this.tick.bind(this));
270 }
271
272 this.links = this.d3el
273 .selectAll('.link')
274 .data(this.model.link_data)
275 .enter()
276 .append('path')
277 .attr('class', 'link')
278 .style('stroke', (d) => {
279 return link_color_scale ? link_color_scale.scale(d.value) : null;
280 })
281 .style('stroke-width', (d: any) => {
282 return d.link_width;
283 })
284 .attr('marker-end', this.model.directed ? 'url(#arrow)' : null);
285
286 this.force_layout
287 .nodes(this.model.mark_data)
288 .force(
289 'link',
290 d3
291 .forceLink(this.model.link_data)
292 .distance(this.model.get('link_distance'))
293 );
294
295 this.nodes = this.d3el
296 .selectAll('.node')
297 .data(this.force_layout.nodes())
298 .enter()
299 .append('g')
300 .attr('class', 'node')
301 .call(
302 d3
303 .drag()
304 .on('start', this.dragstarted.bind(this))
305 .on('drag', this.dragged.bind(this))
306 .on('end', this.dragended.bind(this))
307 );
308
309 this.nodes
310 .append((d) => {
311 return document.createElementNS(d3.namespaces.svg, d.shape);
312 })
313 .attr('class', 'element')
314 .each(function (d) {
315 const node = d3.select(this);
316 for (const key in d.shape_attrs) {
317 node.attr(key, d.shape_attrs[key]);
318 }
319 })
320 .style('fill', this.get_mark_color.bind(this));
321
322 this.nodes
323 .append('text')
324 .attr('class', 'label')
325 .attr('text-anchor', (d) => {
326 return d.label_display === 'center' ? 'middle' : 'start';
327 })
328 .attr('x', (d) => {
329 let xloc = 0;
330 if (d.label_display === 'outside') {
331 switch (d.shape) {
332 case 'rect':
333 xloc = d.shape_attrs.width / 2 + 5;
334 break;
335 case 'circle':
336 xloc = d.shape_attrs.r + 5;
337 break;
338 case 'ellipse':
339 xloc = d.shape_attrs.rx + 5;
340 break;
341 default:
342 xloc = 0;
343 }
344 }
345 return xloc;
346 })
347 .attr('y', '.31em')
348 .text((d) => {
349 return d.label;
350 })
351 .style('display', (d) => {
352 return d.label_display === 'none' ? 'none' : 'inline';
353 });
354
355 this.nodes.on('click', (d, i) => {
356 this.event_dispatcher('element_clicked', { data: d, index: i });
357 });
358 this.nodes.on('mouseover', (d, i) => {
359 this.hover_handler({ data: d, index: i });
360 });
361 this.nodes.on('mouseout', () => {
362 this.reset_hover_points();
363 });
364
365 if (this.model.static) {
366 this.force_layout.tick(100);
367 this.force_layout.stop();
368 this.tick();
369 }
370 }
371
372 private dragstarted(d: NodeData) {
373 if (this.model.static) return;
374 if (!d3GetEvent().active) {
375 this.force_layout.alphaTarget(0.4).restart();
376 }
377 d.fx = d.x;
378 d.fy = d.y;
379 }
380
381 private dragged(d: NodeData) {
382 if (this.model.static) return;
383 d.fx = d3GetEvent().x;
384 d.fy = d3GetEvent().y;
385 }
386
387 private dragended(d: NodeData) {
388 if (this.model.static) return;
389 if (!d3GetEvent().active) {
390 this.force_layout.alphaTarget(0.4);
391 }
392 d.fx = null;
393 d.fy = null;
394 }
395
396 private colorScaleUpdated() {
397 this.nodes
398 .selectAll('.element')
399 .style('fill', this.get_mark_color.bind(this));
400 }
401
402 private linkColorScaleUpdated() {
403 const link_color_scale = this.scales.link_color;
404
405 this.links.style('stroke', (d) => {
406 return link_color_scale ? link_color_scale.scale(d.value) : null;
407 });
408 }
409
410 process_click(interaction) {
411 super.process_click(interaction);
412 if (interaction === 'select') {
413 this.event_listeners.parent_clicked = this.reset_selection;
414 this.event_listeners.element_clicked = this.click_handler;
415 }
416 }
417
418 reset_hover_points() {
419 this.links.style('opacity', 1);
420 this.model.set('hovered_point', null);
421 this.hovered_index = null;
422 this.touch();
423 }
424
425 hover_handler(args) {
426 const data = args.data;
427 const index = args.index;
428 const highlight_links = this.model.get('highlight_links');
429
430 if (highlight_links) {
431 this.links.style('opacity', (d) => {
432 return d.source.label === data.label || d.target.label === data.label
433 ? 1
434 : 0.1;
435 });
436 } else {
437 this.links.style('opacity', 1);
438 }
439
440 this.model.set('hovered_point', index, { updated_view: this });
441 this.touch();
442 }
443
444 reset_selection() {
445 this.model.set('selected', null);
446 this.selected_indices = null;
447 this.touch();
448 }
449
450 click_handler(args) {
451 const index = args.index;
452 const idx = this.model.get('selected') || [];
453 let selected = Array.from(idx);
454 const elem_index = selected.indexOf(index);
455 // Replacement for "Accel" modifier.
456 const accelKey = d3GetEvent().ctrlKey || d3GetEvent().metaKey;
457
458 if (elem_index > -1 && accelKey) {
459 // if the index is already selected and if accel key is
460 // pressed, remove the node from the list
461 selected.splice(elem_index, 1);
462 } else {
463 if (accelKey) {
464 //If accel is pressed and the bar is not already selected
465 //add the bar to the list of selected bars.
466 selected.push(index);
467 }
468 // updating the array containing the bar indexes selected
469 // and updating the style
470 else {
471 //if accel is not pressed, then clear the selected ones
472 //and set the current node to the selected
473 selected = [];
474 selected.push(index);
475 }
476 }
477 this.model.set('selected', selected.length === 0 ? null : selected, {
478 updated_view: this,
479 });
480 this.touch();
481 let e = d3GetEvent();
482 if (!e) {
483 e = window.event;
484 }
485 if (e.cancelBubble !== undefined) {
486 // IE
487 e.cancelBubble = true;
488 }
489 if (e.stopPropagation) {
490 e.stopPropagation();
491 }
492 e.preventDefault();
493 }
494
495 hovered_style_updated(model, style) {
496 this.hovered_style = style;
497 this.clear_style(model.previous('hovered_style'), this.hovered_index);
498 this.style_updated(style, this.hovered_index);
499 }
500
501 unhovered_style_updated(model, style) {
502 this.unhovered_style = style;
503 const hov_indices = this.hovered_index;
504 const unhovered_indices = hov_indices
505 ? _.range(this.model.mark_data.length).filter((index) => {
506 return hov_indices.indexOf(index) === -1;
507 })
508 : [];
509 this.clear_style(model.previous('unhovered_style'), unhovered_indices);
510 this.style_updated(style, unhovered_indices);
511 }
512
513 update_selected(model, value) {
514 this.selected_indices = value;
515 this.apply_styles();
516 }
517
518 update_hovered(model, value) {
519 this.hovered_index = value === null ? value : [value];
520 this.apply_styles();
521 }
522
523 apply_styles(style_arr?) {
524 if (style_arr === undefined || style_arr === null) {
525 style_arr = [
526 this.selected_style,
527 this.unselected_style,
528 this.hovered_style,
529 this.unhovered_style,
530 ];
531 }
532 super.apply_styles(style_arr);
533
534 const all_indices = _.range(this.model.mark_data.length);
535
536 this.set_style_on_elements(this.hovered_style, this.hovered_index);
537 const unhovered_indices = !this.hovered_index
538 ? []
539 : _.difference(all_indices, this.hovered_index);
540 this.set_style_on_elements(this.unhovered_style, unhovered_indices);
541 }
542
543 clear_style(style_dict, indices) {
544 let nodes = this.d3el.selectAll('.element');
545 if (indices) {
546 nodes = nodes.filter((d, index) => {
547 return indices.indexOf(index) !== -1;
548 });
549 }
550 const clearing_style = {};
551 for (const key in style_dict) {
552 clearing_style[key] = null;
553 }
554 applyStyles(nodes, clearing_style);
555 }
556
557 set_style_on_elements(style, indices) {
558 // If the index array is undefined or of length=0, exit the
559 // function without doing anything
560 if (!indices || indices.length === 0) {
561 return;
562 }
563 // Also, return if the style object itself is blank
564 if (style !== undefined && Object.keys(style).length === 0) {
565 return;
566 }
567 let nodes = this.d3el.selectAll('.element');
568 nodes = nodes.filter((data, index) => {
569 return indices.indexOf(index) !== -1;
570 });
571 applyStyles(nodes, style);
572 }
573
574 compute_view_padding() {
575 const xPadding = d3.max<number>(
576 this.model.mark_data.map(function (d) {
577 return (
578 (d.shape_attrs.r || d.shape_attrs.width / 2 || d.shape_attrs.rx) + 1.0
579 );
580 })
581 );
582
583 const yPadding = d3.max<number>(
584 this.model.mark_data.map((d) => {
585 return (
586 (d.shape_attrs.r || d.shape_attrs.height / 2 || d.shape_attrs.ry) +
587 1.0
588 );
589 })
590 );
591
592 if (xPadding !== this.xPadding || yPadding !== this.yPadding) {
593 this.xPadding = xPadding;
594 this.yPadding = xPadding;
595 this.trigger('mark_padding_updated');
596 }
597 }
598
599 private updateLinkDistance() {
600 const x_scale = this.scales.x,
601 y_scale = this.scales.y;
602
603 const link_dist = this.model.get('link_distance');
604 if (!x_scale && !y_scale) {
605 (this.force_layout as any).linkDistance(link_dist).start();
606 }
607 }
608
609 private updateCharge() {
610 const x_scale = this.scales.x,
611 y_scale = this.scales.y;
612
613 const charge = this.model.get('charge');
614 if (!x_scale && !y_scale) {
615 (this.force_layout as any).charge(charge).start();
616 }
617 }
618
619 private updateStatic() {
620 if (this.model.static) {
621 this.force_layout.stop();
622 } else {
623 this.force_layout.restart();
624 }
625 }
626
627 private linkArc(d: LinkData) {
628 const source = d.source;
629 const target = d.target;
630 const dx = target.x - source.x;
631 const dy = target.y - source.y;
632 const rotationRadius = Math.sqrt(dx * dx + dy * dy);
633
634 if (!this.model.directed) {
635 return `M${source.x},${source.y}A${rotationRadius},${rotationRadius} 0 0,1 ${target.x},${target.y}`;
636 }
637
638 const targetRadius =
639 d.target.shape_attrs.r ||
640 d.target.shape_attrs.width / 2 ||
641 d.target.shape_attrs.rx;
642
643 const sourceToTarget = { x: dx, y: dy };
644 const sourceToRotationCenter = rotateVector(sourceToTarget, -Math.PI / 3);
645 const center = {
646 x: source.x + sourceToRotationCenter.x,
647 y: source.y + sourceToRotationCenter.y,
648 };
649 const centerToTarget = {
650 x: target.x - center.x,
651 y: target.y - center.y,
652 };
653
654 const theta = Math.atan((targetRadius + arrowSize) / rotationRadius);
655 const centerToArrow = rotateVector(centerToTarget, theta);
656 const actualTarget = {
657 x: center.x + centerToArrow.x,
658 y: center.y + centerToArrow.y,
659 };
660
661 return `M${source.x},${source.y}A${rotationRadius},${rotationRadius} 0 0,1 ${actualTarget.x},${actualTarget.y}`;
662 }
663
664 private linkLine(d: LinkData) {
665 const source = d.source;
666 const target = d.target;
667
668 if (!this.model.directed) {
669 return `M${source.x},${source.y}L${target.x},${target.y}`;
670 }
671
672 const targetRadius =
673 d.target.shape_attrs.r ||
674 d.target.shape_attrs.width / 2 ||
675 d.target.shape_attrs.rx;
676
677 const dx = target.x - source.x;
678 const dy = target.y - source.y;
679
680 const theta = Math.atan2(dy, dx);
681
682 const actualTarget = {
683 x: target.x - (targetRadius + arrowSize) * Math.cos(theta),
684 y: target.y - (targetRadius + arrowSize) * Math.sin(theta),
685 };
686
687 return `M${source.x},${source.y}L${actualTarget.x},${actualTarget.y}`;
688 }
689
690 private linkSlantLine(d: LinkData) {
691 const source = d.source;
692 const target = d.target;
693
694 let midx = (d.source.x + d.target.x) / 2;
695
696 if (!this.model.directed) {
697 return `M${source.x},${source.y}L${midx},${target.y}L${target.x},${target.y}`;
698 }
699
700 const targetRadius =
701 d.target.shape_attrs.r ||
702 d.target.shape_attrs.width / 2 ||
703 d.target.shape_attrs.rx;
704 let actualTargetX: number;
705
706 if (midx < target.x - (targetRadius + arrowSize)) {
707 actualTargetX = target.x - (targetRadius + arrowSize);
708 } else if (midx > target.x + (targetRadius + arrowSize)) {
709 actualTargetX = target.x + (targetRadius + arrowSize);
710 } else if (midx <= target.x) {
711 midx = target.x - (targetRadius + arrowSize);
712 actualTargetX = target.x - (targetRadius + arrowSize);
713 } else {
714 // midx > target.x
715 midx = target.x + (targetRadius + arrowSize);
716 actualTargetX = target.x + (targetRadius + arrowSize);
717 }
718
719 return `M${source.x},${source.y}L${midx},${target.y}L${actualTargetX},${target.y}`;
720 }
721
722 private tick() {
723 const link_type = this.model.get('link_type');
724
725 this.nodes.attr('transform', (d: NodeData) => {
726 return `translate(${d.x},${d.y})`;
727 });
728
729 // move rects to center since x, y of rect is at the corner
730 this.nodes.select('rect').attr('transform', (d: NodeData) => {
731 return `translate(${-d.shape_attrs.width / 2},${
732 -d.shape_attrs.height / 2
733 })`;
734 });
735
736 let link_path_func = this.linkArc;
737 switch (link_type) {
738 case 'arc':
739 link_path_func = this.linkArc;
740 break;
741 case 'line':
742 link_path_func = this.linkLine;
743 break;
744 case 'slant_line':
745 link_path_func = this.linkSlantLine;
746 break;
747 default:
748 link_path_func = this.linkArc;
749 }
750
751 this.links.attr('d', link_path_func.bind(this));
752 }
753
754 set_default_style(indices) {}
755
756 hovered_style: { [key: string]: string };
757 unhovered_style: { [key: string]: string };
758 hovered_index: number[];
759 private force_layout: d3.Simulation<NodeData, any>;
760 private links: d3.Selection<SVGPathElement, LinkData, HTMLElement, any>;
761 private nodes: d3.Selection<SVGGElement, any, HTMLElement, any>;
762
763 model: GraphModel;
764 }