Debian Codegraph @

bqplot/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, getLuminoWidget } 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(
319 getLuminoWidget(this.tooltip_view),
320 Widget.Msg.AfterShow
321 );
322 this.parent.popper.enableEventListeners();
323 this.move_tooltip();
324 }
325 }
326
327 move_tooltip(mouse_events?) {
328 if (this.tooltip_view) {
329 (this.parent.popper_reference as any).x = d3GetEvent().clientX;
330 (this.parent.popper_reference as any).y = d3GetEvent().clientY;
331 this.parent.popper.scheduleUpdate();
332 }
333 }
334
335 hide_tooltip() {
336 //this function hides the tooltip. But the location of the tooltip
337 //is the last location set by a call to show_tooltip.
338 this.parent.popper.disableEventListeners();
339 this.tooltip_div.style('pointer-events', 'none');
340 this.tooltip_div.style('opacity', 0).style('display', 'none');
341 }
342
343 refresh_tooltip(tooltip_interactions = false) {
344 //the argument controls pointer interactions with the tooltip. a
345 //true value enables pointer interactions while a false value
346 //disables them
347 const el = d3.select(d3GetEvent().target);
348 if (this.is_hover_element(el)) {
349 const data: any = el.data()[0];
350 const clicked_data = this.model.get_data_dict(data, data.index);
351 this.trigger('update_tooltip', clicked_data);
352 this.show_tooltip(tooltip_interactions);
353 }
354 }
355
356 create_tooltip() {
357 //create tooltip widget. To be called after mark has been displayed
358 //and whenever the tooltip object changes
359 const tooltip_model = this.model.get('tooltip');
360 //remove previous tooltip
361 if (this.tooltip_view) {
362 this.tooltip_view.remove();
363 this.tooltip_view = null;
364 }
365 if (tooltip_model) {
366 this.create_child_view(tooltip_model).then((view) => {
367 this.tooltip_view = view;
368
369 MessageLoop.sendMessage(getLuminoWidget(view), Widget.Msg.BeforeAttach);
370 this.tooltip_div.node().appendChild(view.el);
371 MessageLoop.sendMessage(getLuminoWidget(view), Widget.Msg.AfterAttach);
372 });
373 }
374 }
375
376 event_dispatcher(event_name, data?) {
377 if (this.event_listeners[event_name] !== undefined) {
378 _.bind(this.event_listeners[event_name], this, data)();
379 }
380 // Sends a custom mssg to the python side if required
381 // This must be done after calling the event_listeners so that needed
382 // properties (like "selected") are updated
383 this.custom_msg_sender(event_name);
384 }
385
386 custom_msg_sender(event_name) {
387 const event_data = this.event_metadata[event_name];
388 if (event_data !== undefined) {
389 let data = null;
390 if (event_data.hit_test) {
391 //do a hit test to check valid element
392 const el = d3.select(d3GetEvent().target);
393 if (this.is_hover_element(el)) {
394 data = el.data()[0];
395 if (event_data.lookup_data) {
396 data = this.model.get_data_dict(data, data.index);
397 }
398 } else {
399 //do not send mssg if hit test fails
400 return;
401 }
402 }
403 this.send({ event: event_data.msg_name, data: data });
404 }
405 }
406
407 reset_click() {
408 this.event_listeners.element_clicked = function () {};
409 this.event_listeners.parent_clicked = function () {};
410 }
411
412 private reset_hover() {
413 this.event_listeners.mouse_over = function () {};
414 this.event_listeners.mouse_move = function () {};
415 this.event_listeners.mouse_out = function () {};
416 }
417
418 private reset_legend_click() {
419 this.event_listeners.legend_clicked = function () {};
420 }
421
422 private reset_legend_hover() {
423 this.event_listeners.legend_mouse_over = function () {};
424 this.event_listeners.legend_mouse_out = function () {};
425 }
426
427 process_click(interaction) {
428 const that = this;
429 if (interaction === 'tooltip') {
430 this.event_listeners.element_clicked = function () {
431 return that.refresh_tooltip(true);
432 };
433 this.event_listeners.parent_clicked = this.hide_tooltip;
434 }
435 }
436
437 process_hover(interaction) {
438 if (interaction === 'tooltip') {
439 this.event_listeners.mouse_over = this.refresh_tooltip;
440 this.event_listeners.mouse_move = this.move_tooltip;
441 this.event_listeners.mouse_out = this.hide_tooltip;
442 }
443 }
444
445 process_legend_click(interaction) {
446 const that = this;
447 if (interaction === 'tooltip') {
448 this.event_listeners.legend_clicked = function () {
449 return that.refresh_tooltip(true);
450 };
451 this.event_listeners.parent_clicked = this.hide_tooltip;
452 }
453 }
454
455 process_legend_hover(interaction) {
456 if (interaction === 'highlight_axes') {
457 this.event_listeners.legend_mouse_over = _.bind(
458 this.highlight_axes,
459 this
460 );
461 this.event_listeners.legend_mouse_out = _.bind(
462 this.unhighlight_axes,
463 this
464 );
465 }
466 }
467
468 process_interactions() {
469 //configure default interactions
470 const interactions = this.model.get('interactions');
471
472 if (is_defined(interactions.click)) {
473 this.process_click(interactions.click);
474 } else {
475 this.reset_click();
476 }
477
478 if (is_defined(interactions.hover)) {
479 this.process_hover(interactions.hover);
480 } else {
481 this.reset_hover();
482 }
483
484 if (is_defined(interactions.legend_click)) {
485 this.process_legend_click(interactions.legend_click);
486 } else {
487 this.reset_legend_click();
488 }
489 if (is_defined(interactions.legend_hover)) {
490 this.process_legend_hover(interactions.legend_hover);
491 } else {
492 this.reset_legend_hover();
493 }
494 }
495
496 mouse_over() {
497 if (this.model.get('enable_hover')) {
498 const el = d3.select(d3GetEvent().target);
499 if (this.is_hover_element(el)) {
500 const data: any = el.data()[0];
501 //make tooltip visible
502 const hovered_data = this.model.get_data_dict(data, data.index);
503 this.trigger('update_tooltip', hovered_data);
504 this.show_tooltip();
505 this.send({
506 event: 'hover',
507 point: hovered_data,
508 });
509 }
510 }
511 }
512
513 mouse_out() {
514 if (this.model.get('enable_hover')) {
515 const el = d3.select(d3GetEvent().target);
516 if (this.is_hover_element(el)) {
517 const data: any = el.data()[0];
518 const hovered_data = this.model.get_data_dict(data, data.index);
519 // make tooltip invisible
520 this.hide_tooltip();
521 this.send({
522 event: 'hover',
523 point: hovered_data,
524 });
525 }
526 }
527 }
528
529 mouse_move() {
530 if (
531 this.model.get('enable_hover') &&
532 this.is_hover_element(d3.select(d3GetEvent().target))
533 ) {
534 this.move_tooltip();
535 }
536 }
537
538 //TODO: Rename function
539 is_hover_element(elem) {
540 const hit_check = this.display_el_classes.map((class_name) => {
541 return elem.classed(class_name);
542 });
543 return _.compact(hit_check).length > 0;
544 }
545
546 // For backward-compatibility with bqplot plugins
547 // TODO Remove it when we make a backward-incompatible release
548 set x_padding(value: number) {
549 this.xPadding = value;
550 }
551
552 get x_padding(): number {
553 return this.xPadding;
554 }
555
556 set y_padding(value: number) {
557 this.yPadding = value;
558 }
559
560 get y_padding(): number {
561 return this.yPadding;
562 }
563
564 bisect: (x: number[], y: number) => number;
565 d3el: d3.Selection<HTMLElement, any, any, any>;
566 display_el_classes: string[];
567 event_listeners: {
568 element_clicked?: (args) => void;
569 parent_clicked?: (args) => void;
570 legend_mouse_out?: (args) => void;
571 legend_mouse_over?: (args) => void;
572 legend_clicked?: (args) => void;
573 mouse_out?: (args) => void;
574 mouse_move?: (args) => void;
575 mouse_over?: (args) => void;
576 };
577 event_metadata: { [key: string]: { [key: string]: any } };
578 parent: Figure;
579 scales: {
580 rotation?;
581 skew?;
582 opacity?;
583 size?;
584 x?;
585 y?;
586 color?;
587 projection?;
588 count?;
589 sample?;
590 column?;
591 row?;
592 link_color?;
593 width?;
594 };
595 selected_indices: (number | [number, number])[];
596 selected_style: { [key: string]: string };
597 tooltip_div: d3.Selection<any, any, any, any>;
598 tooltip_view: widgets.DOMWidgetView;
599 unselected_style: { [key: string]: string };
600 uuid: string;
601 xPadding: number;
602 yPadding: number;
603 // Overriding super class
604 model: MarkModel;
605 }