Debian Codegraph @

js/src/Mark.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 d3 from 'd3';
18
19 import { MessageLoop } from '@lumino/messaging';
20
21 import { Widget } from '@lumino/widgets';
22
23 import { d3GetEvent } from './utils';
24 import * as _ from 'underscore';
25 import { MarkModel } from './MarkModel';
26 import { Figure } from './Figure';
27 import { applyStyles } from './utils';
28
29 // Check that value is defined and not null
30 function is_defined(value) {
31 return value !== null && value !== undefined;
32 }
33
34 export abstract class Mark extends widgets.WidgetView {
35 initialize() {
36 this.display_el_classes = ['mark']; //classes on the element which
37 //trigger the tooltip to be displayed when they are hovered over
38 this.setElement(
39 document.createElementNS(d3.namespaces.svg, 'g') as HTMLElement
40 );
41 this.d3el = d3.select(this.el);
42 super.initialize.apply(this, arguments);
43 }
44
45 render() {
46 this.xPadding = 0;
47 this.yPadding = 0;
48 this.parent = this.options.parent;
49 this.uuid = widgets.uuid();
50 const scale_creation_promise = this.set_scale_views();
51 this.listenTo(this.model, 'scales_updated', () => {
52 this.set_scale_views().then(_.bind(this.draw, this));
53 });
54
55 if (this.options.clip_id && this.model.get('apply_clip')) {
56 this.d3el.attr('clip-path', 'url(#' + this.options.clip_id + ')');
57 }
58 this.tooltip_div = d3
59 .select(document.createElement('div'))
60 .attr('class', 'mark_tooltip')
61 .attr('id', 'tooltip_' + this.uuid)
62 .style('display', 'none')
63 .style('opacity', 0);
64
65 this.bisect = d3.bisector((d) => {
66 return d;
67 }).left;
68 this.d3el.style('display', this.model.get('visible') ? 'inline' : 'none');
69 this.display_el_classes = [];
70 this.event_metadata = {
71 mouse_over: {
72 msg_name: 'hover',
73 lookup_data: true,
74 hit_test: true,
75 },
76 legend_clicked: {
77 msg_name: 'legend_click',
78 hit_test: true,
79 },
80 element_clicked: {
81 msg_name: 'element_click',
82 lookup_data: true,
83 hit_test: true,
84 },
85 parent_clicked: {
86 msg_name: 'background_click',
87 hit_test: false,
88 },
89 legend_mouse_over: {
90 msg_name: 'legend_hover',
91 hit_test: true,
92 },
93 };
94
95 return scale_creation_promise;
96 }
97
98 abstract draw(animate?);
99 abstract set_ranges();
100 set_scale_views() {
101 // first, if this.scales was already defined, unregister from the
102 // old ones.
103 for (const key in this.scales) {
104 this.stopListening(this.scales[key]);
105 }
106
107 const scale_models = this.model.get('scales');
108 const that = this;
109 const scale_promises = {};
110 _.each(scale_models, (model: widgets.WidgetModel, key) => {
111 scale_promises[key] = that.create_child_view(model);
112 });
113 return widgets.resolvePromisesDict(scale_promises).then((scales) => {
114 that.scales = scales;
115 that.set_positional_scales();
116 that.initialize_additional_scales();
117 that.set_ranges();
118 that.trigger('mark_scales_updated');
119 });
120 }
121
122 set_positional_scales() {
123 // Positional scales are special in that they trigger a full redraw
124 // when their domain is changed.
125 // This should be overloaded in specific mark implementation.
126 }
127
128 initialize_additional_scales() {
129 // This function is for the extra scales that are required for
130 // rendering mark. The scale listeners are set up in this function.
131 // This should be overloaded in the specific mark implementation.
132 }
133
134 set_internal_scales() {
135 // Some marks such as Bars need to create additional scales
136 // to draw themselves. In this case, the set_internal_scales
137 // is overloaded.
138 }
139
140 create_listeners() {
141 this.listenTo(this.model, 'change:visible', this.update_visibility);
142 this.listenTo(
143 this.model,
144 'change:selected_style',
145 this.selected_style_updated
146 );
147 this.listenTo(
148 this.model,
149 'change:unselected_style',
150 this.unselected_style_updated
151 );
152
153 this.listenTo(this.parent, 'margin_updated', this.relayout);
154 this.model.on_some_change(
155 ['labels', 'display_legend'],
156 function () {
157 this.model.trigger('redraw_legend');
158 },
159 this
160 );
161 }
162
163 remove() {
164 this.model.off(null, null, this);
165 this.d3el.transition('remove').duration(0).remove();
166 this.tooltip_div.remove();
167 super.remove();
168 }
169
170 draw_legend(elem, x_disp, y_disp, inter_x_disp, inter_y_disp) {
171 elem.selectAll('.legend' + this.uuid).remove();
172 elem
173 .append('g')
174 .attr('transform', 'translate(' + x_disp + ', ' + y_disp + ')')
175 .attr('class', 'legend' + this.uuid)
176 .on('mouseover', _.bind(this.highlight_axes, this))
177 .on('mouseout', _.bind(this.unhighlight_axes, this))
178 .append('text')
179 .text(this.model.get('labels')[0]);
180 return [1, 1];
181 }
182
183 highlight_axes() {
184 _.each(this.model.get('scales'), (model: any) => {
185 model.trigger('highlight_axis');
186 });
187 }
188
189 unhighlight_axes() {
190 _.each(this.model.get('scales'), (model: any) => {
191 model.trigger('unhighlight_axis');
192 });
193 }
194
195 invert_range(start_pxl, end_pxl) {
196 return [start_pxl, end_pxl];
197 }
198
199 invert_point(pxl) {}
200
201 // TODO: is the following function really required?
202 invert_multi_range(array_pixels) {
203 return array_pixels;
204 }
205
206 update_visibility(model, visible) {
207 this.d3el.style('display', visible ? 'inline' : 'none');
208 }
209
210 get_colors(index): string {
211 // cycles over the list of colors when too many items
212 const colors = this.model.get('colors');
213 return colors[index % colors.length];
214 }
215
216 get_mark_color(data, index): string {
217 const colorScale = this.scales.color;
218
219 if (colorScale && data.color !== undefined && data.color !== null) {
220 return colorScale.scale(data.color);
221 }
222
223 return this.get_colors(index);
224 }
225
226 get_mark_opacity(data, index) {
227 const opacityScale = this.scales.opacity;
228 const defaultOpacities = this.model.get('opacities');
229
230 if (opacityScale && data.opacity !== undefined && data.opacity !== null) {
231 return opacityScale.scale(data.opacity);
232 }
233
234 return defaultOpacities[index % defaultOpacities.length];
235 }
236
237 // Style related functions
238 selected_style_updated(model, style) {
239 this.selected_style = style;
240 this.clear_style(model.previous('selected_style'), this.selected_indices);
241 this.style_updated(style, this.selected_indices);
242 }
243
244 unselected_style_updated(model, style) {
245 this.unselected_style = style;
246 const sel_indices = this.selected_indices;
247 const unselected_indices = sel_indices
248 ? _.range(this.model.mark_data.length).filter((index) => {
249 return sel_indices.indexOf(index) === -1;
250 })
251 : [];
252 this.clear_style(model.previous('unselected_style'), unselected_indices);
253 this.style_updated(style, unselected_indices);
254 }
255
256 style_updated(new_style, indices, elements?) {
257 // reset the style of the elements and apply the new style
258 this.set_default_style(indices);
259 this.set_style_on_elements(new_style, indices);
260 }
261
262 apply_styles(style_arr?) {
263 if (style_arr === undefined || style_arr == null) {
264 style_arr = [this.selected_style, this.unselected_style];
265 }
266 const all_indices = _.range(this.model.mark_data.length);
267 for (let i = 0; i < style_arr.length; i++) {
268 this.clear_style(style_arr[i]);
269 }
270
271 this.set_default_style(all_indices);
272
273 this.set_style_on_elements(
274 this.selected_style,
275 Array.from(this.selected_indices || [])
276 );
277 const unselected_indices = !this.selected_indices
278 ? []
279 : _.difference(all_indices, Array.from(this.selected_indices));
280 this.set_style_on_elements(this.unselected_style, unselected_indices);
281 }
282
283 // Abstract functions which have to be overridden by the specific mark
284 abstract clear_style(style_dict, indices?, elements?);
285
286 abstract set_default_style(indices, elements?);
287
288 abstract set_style_on_elements(style, indices, elements?);
289
290 // Called when the figure margins are updated.
291 abstract relayout();
292
293 /**
294 * This function sets the x and y view paddings for the mark using the
295 * variables xPadding and yPadding
296 */
297 abstract compute_view_padding();
298
299 show_tooltip(mouse_events?) {
300 //this function displays the tooltip at the location of the mouse
301 //event is the d3 event for the data.
302 //mouse_events is a boolean to enable mouse_events or not.
303 //If this property has never been set, it will default to false.
304 if (this.tooltip_view) {
305 if (
306 mouse_events === undefined ||
307 mouse_events === null ||
308 !mouse_events
309 ) {
310 this.tooltip_div.style('pointer-events', 'none');
311 } else {
312 this.tooltip_div.style('pointer-events', 'all');
313 }
314 applyStyles(this.tooltip_div, this.model.get('tooltip_style')).style(
315 'display',
316 null
317 );
318 MessageLoop.sendMessage(this.tooltip_view.pWidget, Widget.Msg.AfterShow);
319 this.parent.popper.enableEventListeners();
320 this.move_tooltip();
321 }
322 }
323
324 move_tooltip(mouse_events?) {
325 if (this.tooltip_view) {
326 (this.parent.popper_reference as any).x = d3GetEvent().clientX;
327 (this.parent.popper_reference as any).y = d3GetEvent().clientY;
328 this.parent.popper.scheduleUpdate();
329 }
330 }
331
332 hide_tooltip() {
333 //this function hides the tooltip. But the location of the tooltip
334 //is the last location set by a call to show_tooltip.
335 this.parent.popper.disableEventListeners();
336 this.tooltip_div.style('pointer-events', 'none');
337 this.tooltip_div.style('opacity', 0).style('display', 'none');
338 }
339
340 refresh_tooltip(tooltip_interactions = false) {
341 //the argument controls pointer interactions with the tooltip. a
342 //true value enables pointer interactions while a false value
343 //disables them
344 const el = d3.select(d3GetEvent().target);
345 if (this.is_hover_element(el)) {
346 const data: any = el.data()[0];
347 const clicked_data = this.model.get_data_dict(data, data.index);
348 this.trigger('update_tooltip', clicked_data);
349 this.show_tooltip(tooltip_interactions);
350 }
351 }
352
353 create_tooltip() {
354 //create tooltip widget. To be called after mark has been displayed
355 //and whenever the tooltip object changes
356 const tooltip_model = this.model.get('tooltip');
357 //remove previous tooltip
358 if (this.tooltip_view) {
359 this.tooltip_view.remove();
360 this.tooltip_view = null;
361 }
362 if (tooltip_model) {
363 this.create_child_view(tooltip_model).then((view) => {
364 this.tooltip_view = view;
365
366 MessageLoop.sendMessage(view.pWidget, Widget.Msg.BeforeAttach);
367 this.tooltip_div.node().appendChild(view.el);
368 MessageLoop.sendMessage(view.pWidget, Widget.Msg.AfterAttach);
369 });
370 }
371 }
372
373 event_dispatcher(event_name, data?) {
374 if (this.event_listeners[event_name] !== undefined) {
375 _.bind(this.event_listeners[event_name], this, data)();
376 }
377 // Sends a custom mssg to the python side if required
378 // This must be done after calling the event_listeners so that needed
379 // properties (like "selected") are updated
380 this.custom_msg_sender(event_name);
381 }
382
383 custom_msg_sender(event_name) {
384 const event_data = this.event_metadata[event_name];
385 if (event_data !== undefined) {
386 let data = null;
387 if (event_data.hit_test) {
388 //do a hit test to check valid element
389 const el = d3.select(d3GetEvent().target);
390 if (this.is_hover_element(el)) {
391 data = el.data()[0];
392 if (event_data.lookup_data) {
393 data = this.model.get_data_dict(data, data.index);
394 }
395 } else {
396 //do not send mssg if hit test fails
397 return;
398 }
399 }
400 this.send({ event: event_data.msg_name, data: data });
401 }
402 }
403
404 reset_click() {
405 this.event_listeners.element_clicked = function () {};
406 this.event_listeners.parent_clicked = function () {};
407 }
408
409 private reset_hover() {
410 this.event_listeners.mouse_over = function () {};
411 this.event_listeners.mouse_move = function () {};
412 this.event_listeners.mouse_out = function () {};
413 }
414
415 private reset_legend_click() {
416 this.event_listeners.legend_clicked = function () {};
417 }
418
419 private reset_legend_hover() {
420 this.event_listeners.legend_mouse_over = function () {};
421 this.event_listeners.legend_mouse_out = function () {};
422 }
423
424 process_click(interaction) {
425 const that = this;
426 if (interaction === 'tooltip') {
427 this.event_listeners.element_clicked = function () {
428 return that.refresh_tooltip(true);
429 };
430 this.event_listeners.parent_clicked = this.hide_tooltip;
431 }
432 }
433
434 process_hover(interaction) {
435 if (interaction === 'tooltip') {
436 this.event_listeners.mouse_over = this.refresh_tooltip;
437 this.event_listeners.mouse_move = this.move_tooltip;
438 this.event_listeners.mouse_out = this.hide_tooltip;
439 }
440 }
441
442 process_legend_click(interaction) {
443 const that = this;
444 if (interaction === 'tooltip') {
445 this.event_listeners.legend_clicked = function () {
446 return that.refresh_tooltip(true);
447 };
448 this.event_listeners.parent_clicked = this.hide_tooltip;
449 }
450 }
451
452 process_legend_hover(interaction) {
453 if (interaction === 'highlight_axes') {
454 this.event_listeners.legend_mouse_over = _.bind(
455 this.highlight_axes,
456 this
457 );
458 this.event_listeners.legend_mouse_out = _.bind(
459 this.unhighlight_axes,
460 this
461 );
462 }
463 }
464
465 process_interactions() {
466 //configure default interactions
467 const interactions = this.model.get('interactions');
468
469 if (is_defined(interactions.click)) {
470 this.process_click(interactions.click);
471 } else {
472 this.reset_click();
473 }
474
475 if (is_defined(interactions.hover)) {
476 this.process_hover(interactions.hover);
477 } else {
478 this.reset_hover();
479 }
480
481 if (is_defined(interactions.legend_click)) {
482 this.process_legend_click(interactions.legend_click);
483 } else {
484 this.reset_legend_click();
485 }
486 if (is_defined(interactions.legend_hover)) {
487 this.process_legend_hover(interactions.legend_hover);
488 } else {
489 this.reset_legend_hover();
490 }
491 }
492
493 mouse_over() {
494 if (this.model.get('enable_hover')) {
495 const el = d3.select(d3GetEvent().target);
496 if (this.is_hover_element(el)) {
497 const data: any = el.data()[0];
498 //make tooltip visible
499 const hovered_data = this.model.get_data_dict(data, data.index);
500 this.trigger('update_tooltip', hovered_data);
501 this.show_tooltip();
502 this.send({
503 event: 'hover',
504 point: hovered_data,
505 });
506 }
507 }
508 }
509
510 mouse_out() {
511 if (this.model.get('enable_hover')) {
512 const el = d3.select(d3GetEvent().target);
513 if (this.is_hover_element(el)) {
514 const data: any = el.data()[0];
515 const hovered_data = this.model.get_data_dict(data, data.index);
516 // make tooltip invisible
517 this.hide_tooltip();
518 this.send({
519 event: 'hover',
520 point: hovered_data,
521 });
522 }
523 }
524 }
525
526 mouse_move() {
527 if (
528 this.model.get('enable_hover') &&
529 this.is_hover_element(d3.select(d3GetEvent().target))
530 ) {
531 this.move_tooltip();
532 }
533 }
534
535 //TODO: Rename function
536 is_hover_element(elem) {
537 const hit_check = this.display_el_classes.map((class_name) => {
538 return elem.classed(class_name);
539 });
540 return _.compact(hit_check).length > 0;
541 }
542
543 // For backward-compatibility with bqplot plugins
544 // TODO Remove it when we make a backward-incompatible release
545 set x_padding(value: number) {
546 this.xPadding = value;
547 }
548
549 get x_padding(): number {
550 return this.xPadding;
551 }
552
553 set y_padding(value: number) {
554 this.yPadding = value;
555 }
556
557 get y_padding(): number {
558 return this.yPadding;
559 }
560
561 bisect: (x: number[], y: number) => number;
562 d3el: d3.Selection<HTMLElement, any, any, any>;
563 display_el_classes: string[];
564 event_listeners: {
565 element_clicked?: (args) => void;
566 parent_clicked?: (args) => void;
567 legend_mouse_out?: (args) => void;
568 legend_mouse_over?: (args) => void;
569 legend_clicked?: (args) => void;
570 mouse_out?: (args) => void;
571 mouse_move?: (args) => void;
572 mouse_over?: (args) => void;
573 };
574 event_metadata: { [key: string]: { [key: string]: any } };
575 parent: Figure;
576 scales: {
577 rotation?;
578 skew?;
579 opacity?;
580 size?;
581 x?;
582 y?;
583 color?;
584 projection?;
585 count?;
586 sample?;
587 column?;
588 row?;
589 link_color?;
590 width?;
591 };
592 selected_indices: (number | [number, number])[];
593 selected_style: { [key: string]: string };
594 tooltip_div: d3.Selection<any, any, any, any>;
595 tooltip_view: widgets.DOMWidgetView;
596 unselected_style: { [key: string]: string };
597 uuid: string;
598 xPadding: number;
599 yPadding: number;
600 // Overriding super class
601 model: MarkModel;
602 }