Debian Codegraph @

js/src/Figure.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 // var d3 =Object.assign({}, require("d3-selection"), require("d3-selection-multi"));
19 import * as _ from 'underscore';
20 import * as popperreference from './PopperReference';
21 import popper from 'popper.js';
22 import * as THREE from 'three';
23 import { Dict, WidgetModel, WidgetView } from '@jupyter-widgets/base';
24 import { applyAttrs, applyStyles } from './utils';
25 import { Scale } from './Scale';
26 import { ScaleModel } from './ScaleModel';
27 import { AxisModel } from './AxisModel';
28 import { Mark } from './Mark';
29 import { MarkModel } from './MarkModel';
30 import { Interaction } from './Interaction';
31
32 THREE.ShaderChunk['scales'] =
33 require('raw-loader!../shaders/scales.glsl').default;
34
35 interface IFigureSize {
36 width: number;
37 height: number;
38 }
39
40 export class Figure extends widgets.DOMWidgetView {
41 initialize() {
42 this.debouncedRelayout = _.debounce(() => {
43 this.relayout();
44 }, 300);
45 // Internet Explorer does not support classList for svg elements
46 this.el.classList.add('bqplot');
47 this.el.classList.add('figure');
48 this.el.classList.add('jupyter-widgets');
49 this.change_theme();
50
51 const svg = document.createElementNS(
52 d3.namespaces.svg,
53 'svg'
54 ) as SVGElement;
55 svg.classList.add('svg-figure');
56 this.svg = d3.select<SVGElement, any>(svg);
57
58 const svg_background = document.createElementNS(
59 d3.namespaces.svg,
60 'svg'
61 ) as SVGElement;
62 svg_background.classList.add('svg-background');
63 this.svg_background = d3.select<SVGElement, any>(svg_background);
64
65 this.el.appendChild(svg_background);
66 this.el.appendChild(svg);
67
68 // For testing we need to know when the mark_views is created, the tests
69 // can wait for this promise.
70 this._initial_marks_created = new Promise((resolve) => {
71 this._initial_marks_created_resolve = resolve;
72 });
73
74 super.initialize.apply(this, arguments);
75 }
76
77 protected getFigureSize(): IFigureSize {
78 const figureSize: IFigureSize = this.el.getBoundingClientRect();
79 const clientRectRatio = figureSize.width / figureSize.height;
80
81 const minRatio: number = this.model.get('min_aspect_ratio');
82 const maxRatio: number = this.model.get('max_aspect_ratio');
83
84 if (clientRectRatio < minRatio) {
85 // Too much vertical space: Keep horizontal space but compute height from min aspect ratio
86 figureSize.height = figureSize.width / minRatio;
87 } else if (clientRectRatio > maxRatio) {
88 // Too much horizontal space: Keep vertical space but compute width from max aspect ratio
89 figureSize.width = figureSize.height * maxRatio;
90 }
91
92 return figureSize;
93 }
94
95 render() {
96 // we cannot use Promise.all here, since this.layoutPromise is resolved, and will be overwritten later on
97 this.displayed.then(() => {
98 // make sure we render after all layouts styles are set, since they can affect the size
99 this.layoutPromise.then(this.renderImpl.bind(this));
100 });
101 }
102
103 protected async renderImpl() {
104 const figureSize = this.getFigureSize();
105 this.width = figureSize.width;
106 this.height = figureSize.height;
107
108 this.id = widgets.uuid();
109
110 // Dictionary which contains the mapping for each of the marks id
111 // to it's padding. Dictionary is required to not recompute
112 // everything when a mark is removed.
113 this.x_pad_dict = {};
114 this.y_pad_dict = {};
115
116 // this is the net padding in pixel to be applied to the x and y.
117 // If there is no restriction on the plottable area of the figure,
118 // then these two variables are the maximum of the values in the
119 // corresponding variables x_pad_dict, y_pad_dict.
120 this.xPaddingArr = {};
121 this.yPaddingArr = {};
122 this.figure_padding_x = this.model.get('padding_x');
123 this.figure_padding_y = this.model.get('padding_y');
124 this.clip_id = 'clip_path_' + this.id;
125 this.margin = this.model.get('fig_margin');
126
127 this.update_plotarea_dimensions();
128 // we hide it when the plot area is too small
129 if (this.plotarea_width < 1 || this.plotarea_height < 1) {
130 this.el.style.visibility = 'hidden';
131 } else {
132 this.el.style.visibility = '';
133 }
134 // this.fig is the top <g> element to be impacted by a rescaling / change of margins
135
136 this.fig = this.svg
137 .append('g')
138 .attr(
139 'transform',
140 'translate(' + this.margin.left + ',' + this.margin.top + ')'
141 );
142 this.fig_background = this.svg_background
143 .append('g')
144 .attr(
145 'transform',
146 'translate(' + this.margin.left + ',' + this.margin.top + ')'
147 );
148 this.tooltip_div = d3
149 .select(document.createElement('div'))
150 .attr('class', 'tooltip_div');
151 this.popper_reference = new popperreference.PositionReference({
152 x: 0,
153 y: 0,
154 width: 20,
155 height: 20,
156 });
157 this.popper = new popper(this.popper_reference, this.tooltip_div.node(), {
158 placement: 'auto',
159 });
160
161 this.bg = this.fig_background
162 .append('rect')
163 .attr('class', 'plotarea_background')
164 .attr('x', 0)
165 .attr('y', 0)
166 .attr('width', this.plotarea_width)
167 .attr('height', this.plotarea_height)
168 .style('pointer-events', 'inherit');
169 applyStyles(this.bg, this.model.get('background_style'));
170
171 this.bg_events = this.fig
172 .append('rect')
173 .attr('class', 'plotarea_events')
174 .attr('x', 0)
175 .attr('y', 0)
176 .attr('width', this.plotarea_width)
177 .attr('height', this.plotarea_height)
178 .style('pointer-events', 'inherit');
179 this.bg_events.on('click', () => {
180 this.trigger('bg_clicked');
181 });
182
183 this.fig_axes = this.fig_background.append('g');
184 this.fig_marks = this.fig.append('g');
185 this.interaction = this.fig.append('g');
186
187 /*
188 * The following was the structure of the DOM element constructed
189 *
190 <div class="bqplot figure jupyter-widgets">
191 <svg>
192 <g class="svg-figure" transform="margin translation">
193 <g class="svg-axes"></g>
194 <g class="svg-marks"></g>
195 <g class="svg-interaction"></g>
196 </g>
197 </svg>
198 </div>
199
200 To allow the main/interaction layer on top, and also allowing us to draw
201 on top of the canvas (e.g. selectors), we create a new DOM structure.
202 When creating a screenshot/image, we collapse all this into one svg.
203
204 <div class="bqplot figure jupyter-widgets">
205 <svg class="svg-background">
206 <g transform="margin translation">
207 <g class="svg-axes"></g>
208 </g>
209 </svg>
210 <canvas>
211 </canvas>
212 <svg class="svg-figure">
213 <g transform="margin translation">
214 <g class="svg-marks"></g>
215 <g class="svg-interaction"></g>
216 </g>
217 </svg>
218 </div>
219 */
220
221 this.clip_path = this.svg
222 .append('svg:defs')
223 .append('svg:clipPath')
224 .attr('id', this.clip_id)
225 .append('rect')
226 .attr('x', 0)
227 .attr('y', 0)
228 .attr('width', this.plotarea_width)
229 .attr('height', this.plotarea_height);
230
231 this.title = this.fig
232 .append('text')
233 .attr('class', 'mainheading')
234 .attr('x', 0.5 * this.plotarea_width)
235 .attr('y', -(this.margin.top / 2.0))
236 .attr('dy', '1em');
237 applyStyles(this.title, this.model.get('title_style'));
238
239 this.title.text(this.model.get('title'));
240
241 // TODO: remove the save png event mechanism.
242 this.model.on('save_png', this.save_png, this);
243 this.model.on('save_svg', this.save_svg, this);
244 this.model.on('upload_png', this.upload_png, this);
245
246 const figure_scale_promise = this.create_figure_scales();
247
248 await figure_scale_promise;
249
250 this.mark_views = new widgets.ViewList(
251 this.add_mark,
252 this.remove_mark,
253 this
254 );
255
256 const mark_views_updated = this.mark_views
257 .update(this.model.get('marks'))
258 .then((views) => {
259 this.replace_dummy_nodes(views);
260 this.update_marks(views);
261 this.update_legend();
262 // Update Interaction layer
263 // This has to be done after the marks are created
264 this.set_interaction(this.model.get('interaction'));
265 this._initial_marks_created_resolve();
266 this.update_gl();
267 });
268
269 this.axis_views = new widgets.ViewList(this.add_axis, null, this);
270 const axis_views_updated = this.axis_views.update(this.model.get('axes'));
271
272 // TODO: move to the model
273 this.model.on_some_change(
274 ['fig_margin', 'min_aspect_ratio', 'max_aspect_ratio'],
275 this.debouncedRelayout,
276 this
277 );
278 this.model.on_some_change(
279 ['padding_x', 'padding_y'],
280 () => {
281 this.figure_padding_x = this.model.get('padding_x');
282 this.figure_padding_y = this.model.get('padding_y');
283 this.trigger('margin_updated');
284 },
285 this
286 );
287 this.model.on(
288 'change:axes',
289 (model, value, options) => {
290 this.axis_views.update(value);
291 },
292 this
293 );
294 this.model.on(
295 'change:marks',
296 (model, value, options) => {
297 this.mark_views.update(value).then((views) => {
298 this.replace_dummy_nodes(views);
299 this.update_marks(views);
300 this.update_legend();
301 this.update_gl();
302 });
303 },
304 this
305 );
306 this.model.on('change:legend_location', this.update_legend, this);
307 this.model.on('change:title', this.update_title, this);
308
309 this.model.on(
310 'change:interaction',
311 (model, value) => {
312 Promise.all(this.mark_views.views).then((views) => {
313 // Like above:
314 // This has to be done after the marks are created
315 this.set_interaction(value);
316 });
317 },
318 this
319 );
320
321 document.body.appendChild(this.tooltip_div.node());
322 this.create_listeners();
323
324 // In the classic notebook, we should relayout the figure on
325 // resize of the main window.
326 window.addEventListener('resize', this.debouncedRelayout);
327 this.once('remove', () => {
328 window.removeEventListener('resize', this.debouncedRelayout);
329 });
330
331 return Promise.all([mark_views_updated, axis_views_updated]);
332 }
333
334 createWebGLRenderer() {
335 // a shared webgl context for all marks
336 if (!this.renderer) {
337 this.renderer = new THREE.WebGLRenderer({
338 antialias: true,
339 alpha: true,
340 premultipliedAlpha: true,
341 });
342
343 this.renderer.setSize(100, 100);
344 this.renderer.setClearAlpha(0);
345 this.renderer.setPixelRatio(
346 this.model.get('pixel_ratio') || window.devicePixelRatio
347 );
348 }
349
350 if (this.renderer && !this.el.contains(this.renderer.domElement)) {
351 this.el.insertBefore(this.renderer.domElement, this.el.childNodes[1]);
352 }
353 this.layout_webgl_canvas();
354 }
355
356 replace_dummy_nodes(views: Mark[]) {
357 for (const view of views) {
358 const dummyNode = this.dummyNodes[view.cid];
359
360 // It could be that the dummy node is removed before we got a change to replace it
361 // This happens when the marks list is changed rapidly
362 if (dummyNode !== null && dummyNode.parentNode) {
363 dummyNode.parentNode.replaceChild(view.el, dummyNode);
364 this.dummyNodes[view.cid] = null;
365 this.displayed.then(() => {
366 view.trigger('displayed');
367 });
368 }
369 }
370 }
371
372 create_listeners() {
373 this.listenTo(this.model, 'change:title_style', this.title_style_updated);
374 this.listenTo(
375 this.model,
376 'change:background_style',
377 this.background_style_updated
378 );
379 this.listenTo(this.model, 'change:layout', this.change_layout);
380 this.listenTo(this.model, 'change:legend_style', this.legend_style_updated);
381 this.listenTo(this.model, 'change:legend_text', this.legend_text_updated);
382 this.listenTo(this.model, 'change:pixel_ratio', () => {
383 if (this.renderer) {
384 this.renderer.setPixelRatio(
385 this.model.get('pixel_ratio') || window.devicePixelRatio
386 );
387 this.update_gl();
388 }
389 });
390 this.listenTo(this.model, 'change:theme', this.change_theme);
391 }
392
393 title_style_updated() {
394 applyStyles(this.title, this.model.get('title_style'));
395 }
396
397 background_style_updated() {
398 applyStyles(this.bg, this.model.get('background_style'));
399 }
400
401 legend_style_updated() {
402 applyStyles(
403 this.fig_marks
404 .selectAll('.g_legend')
405 .selectAll('.axis')
406 .selectAll('rect'),
407 this.model.get('legend_style')
408 );
409 }
410
411 legend_text_updated() {
412 applyStyles(
413 this.fig_marks.selectAll('.g_legend').selectAll('text.legendtext'),
414 this.model.get('legend_text')
415 );
416 }
417
418 create_figure_scales() {
419 // Creates the absolute scales for the figure: default domain is [0,1], range is [0,width] and [0,height].
420 // See the scale_x and scale_y attributes of the python Figure
421 const that = this;
422 const x_scale_promise = this.create_child_view(
423 this.model.get('scale_x')
424 ).then((view) => {
425 that.scale_x = view as WidgetView as Scale;
426 (
427 that.scale_x.scale as
428 | d3.ScaleLinear<number, number>
429 | d3.ScaleTime<Date, number>
430 | d3.ScaleLogarithmic<number, number>
431 ).clamp(true);
432 that.scale_x.set_range([0, that.plotarea_width]);
433 });
434
435 const y_scale_promise = this.create_child_view(
436 this.model.get('scale_y')
437 ).then((view) => {
438 that.scale_y = view as WidgetView as Scale;
439 (
440 that.scale_y.scale as
441 | d3.ScaleLinear<number, number>
442 | d3.ScaleTime<Date, number>
443 | d3.ScaleLogarithmic<number, number>
444 ).clamp(true);
445 that.scale_y.set_range([that.plotarea_height, 0]);
446 });
447 return Promise.all([x_scale_promise, y_scale_promise]);
448 }
449
450 padded_range(direction: 'x' | 'y', scale_model: ScaleModel) {
451 // Functions to be called by mark which respects padding.
452 // Typically all marks do this. Axis do not do this.
453 // Also, if a mark does not set the domain, it can potentially call
454 // the unpadded ranges.
455 if (!scale_model.get('allow_padding')) {
456 return this.range(direction);
457 }
458 const scale_id = scale_model.model_id;
459
460 if (direction === 'x') {
461 const scale_padding =
462 this.xPaddingArr[scale_id] !== undefined
463 ? this.xPaddingArr[scale_id]
464 : 0;
465 const fig_padding = this.plotarea_width * this.figure_padding_x;
466 return [
467 fig_padding + scale_padding,
468 this.plotarea_width - fig_padding - scale_padding,
469 ];
470 } else if (direction === 'y') {
471 const scale_padding =
472 this.yPaddingArr[scale_id] !== undefined
473 ? this.yPaddingArr[scale_id]
474 : 0;
475 const fig_padding = this.plotarea_height * this.figure_padding_y;
476 return [
477 this.plotarea_height - scale_padding - fig_padding,
478 scale_padding + fig_padding,
479 ];
480 }
481 }
482
483 range(direction: 'x' | 'y') {
484 if (direction === 'x') {
485 return [0, this.plotarea_width];
486 } else if (direction === 'y') {
487 return [this.plotarea_height, 0];
488 }
489 }
490
491 get_mark_plotarea_height(scaleModel: ScaleModel) {
492 if (!scaleModel.get('allow_padding')) {
493 return this.plotarea_height;
494 }
495 const scale_id = scaleModel.model_id;
496 const scale_padding =
497 this.yPaddingArr[scale_id] !== undefined ? this.yPaddingArr[scale_id] : 0;
498 return (
499 this.plotarea_height * (1 - this.figure_padding_y) -
500 scale_padding -
501 scale_padding
502 );
503 }
504
505 get_mark_plotarea_width(scaleModel: ScaleModel) {
506 if (!scaleModel.get('allow_padding')) {
507 return this.plotarea_width;
508 }
509
510 const scale_id = scaleModel.model_id;
511 const scale_padding =
512 this.xPaddingArr[scale_id] !== undefined ? this.xPaddingArr[scale_id] : 0;
513 return (
514 this.plotarea_width * (1 - this.figure_padding_x) -
515 scale_padding -
516 scale_padding
517 );
518 }
519
520 async add_axis(model: AxisModel) {
521 // Called when an axis is added to the axes list.
522 const view = await this.create_child_view(model);
523
524 this.fig_axes.node().appendChild(view.el);
525 this.displayed.then(() => {
526 view.trigger('displayed');
527 });
528
529 return view;
530 }
531
532 remove_from_padding_dict(dict, mark_view: Mark, scale_model: ScaleModel) {
533 if (scale_model === undefined || scale_model === null) {
534 return;
535 }
536 const scale_id = scale_model.model_id;
537 if (dict[scale_id] !== undefined) {
538 delete dict[scale_id][mark_view.model.model_id + '_' + mark_view.cid];
539 if (Object.keys(dict[scale_id]).length === 0) {
540 delete dict[scale_id];
541 }
542 }
543 }
544
545 update_padding_dict(dict, mark_view: Mark, scale_model: ScaleModel, value) {
546 const scale_id = scale_model.model_id;
547 if (!dict[scale_id]) {
548 dict[scale_id] = {};
549 }
550 dict[scale_id][mark_view.model.model_id + '_' + mark_view.cid] = value;
551 }
552
553 mark_scales_updated(view: Mark) {
554 const model = view.model;
555 const prev_scale_models = model.previous('scales');
556 this.remove_from_padding_dict(
557 this.x_pad_dict,
558 view,
559 prev_scale_models[model.get_key_for_orientation('horizontal')]
560 );
561 this.remove_from_padding_dict(
562 this.y_pad_dict,
563 view,
564 prev_scale_models[model.get_key_for_orientation('vertical')]
565 );
566
567 const scale_models = model.get('scales');
568 this.update_padding_dict(
569 this.x_pad_dict,
570 view,
571 scale_models[model.get_key_for_orientation('horizontal')],
572 view.xPadding
573 );
574 this.update_padding_dict(
575 this.y_pad_dict,
576 view,
577 scale_models[model.get_key_for_orientation('vertical')],
578 view.yPadding
579 );
580
581 this.update_paddings();
582 }
583
584 mark_padding_updated(view: Mark) {
585 const model = view.model;
586 const scale_models = model.get('scales');
587
588 this.update_padding_dict(
589 this.x_pad_dict,
590 view,
591 scale_models[model.get_key_for_orientation('horizontal')],
592 view.xPadding
593 );
594 this.update_padding_dict(
595 this.y_pad_dict,
596 view,
597 scale_models[model.get_key_for_orientation('vertical')],
598 view.yPadding
599 );
600
601 this.update_paddings();
602 }
603
604 update_marks(mark_views) {
605 this.update_paddings();
606 }
607
608 remove_mark(view: Mark) {
609 // Called when a mark is removed from the mark list.
610 const model = view.model;
611 model.off('redraw_legend', null, this);
612 model.off('data_updated', null, this);
613 model.off('scales_updated', null, this);
614 model.off('mark_padding_updated', null, this);
615
616 const scale_models = model.get('scales');
617 this.remove_from_padding_dict(
618 this.x_pad_dict,
619 view,
620 scale_models[model.get_key_for_orientation('horizontal')]
621 );
622 this.remove_from_padding_dict(
623 this.y_pad_dict,
624 view,
625 scale_models[model.get_key_for_orientation('vertical')]
626 );
627 view.remove();
628 }
629
630 async add_mark(model: MarkModel) {
631 model.state_change.then(() => {
632 model.on('data_updated redraw_legend', this.update_legend, this);
633 });
634
635 const dummy_node = this.fig_marks
636 .node()
637 .appendChild(document.createElementNS(d3.namespaces.svg, 'g'));
638
639 // @ts-ignore: We should use the type argument: this.create_child_view<Mark>
640 const view: Mark = await this.create_child_view(model, {
641 clip_id: this.clip_id,
642 });
643
644 this.dummyNodes[view.cid] = dummy_node;
645
646 view.on(
647 'mark_padding_updated',
648 () => {
649 this.mark_padding_updated(view);
650 },
651 this
652 );
653 view.on(
654 'mark_scales_updated',
655 () => {
656 this.mark_scales_updated(view);
657 },
658 this
659 );
660
661 let child_x_scale =
662 view.model.get('scales')[view.model.get_key_for_dimension('x')];
663 let child_y_scale =
664 view.model.get('scales')[view.model.get_key_for_dimension('y')];
665 if (child_x_scale === undefined) {
666 child_x_scale = this.scale_x.model;
667 }
668 if (child_y_scale === undefined) {
669 child_y_scale = this.scale_y.model;
670 }
671 this.update_padding_dict(
672 this.x_pad_dict,
673 view,
674 child_x_scale,
675 view.xPadding
676 );
677 this.update_padding_dict(
678 this.y_pad_dict,
679 view,
680 child_y_scale,
681 view.yPadding
682 );
683
684 // If the mark needs a WebGL renderer, we create it
685 if (view['render_gl']) {
686 this.createWebGLRenderer();
687 }
688 // If the marks list changes before replace_dummy_nodes is called, we are not DOM
689 // attached, and view.remove() in Figure.remove_mark will not remove this view from the DOM
690 // but a later call to Figure.replace_dummy_nodes will attach it to the DOM again, leading
691 // to a 'ghost' mark, originally reported in https://github.com/spacetelescope/jdaviz/issues/270
692 view.on('remove', () => {
693 if (dummy_node.parentNode) {
694 dummy_node.remove();
695 }
696 });
697
698 return view;
699 }
700
701 update_paddings() {
702 // Iterate over the paddings of the marks for each scale and store
703 // the maximum padding for each scale on the X and Y in
704 // xPaddingArr and yPaddingArr
705
706 this.xPaddingArr = {};
707 this.yPaddingArr = {};
708
709 _.forEach(this.x_pad_dict, (dict: any, scale_id) => {
710 let max = 0;
711 _.forEach(dict, (value: number, key) => {
712 max = Math.max(max, value);
713 });
714 this.xPaddingArr[scale_id] = max;
715 });
716
717 _.forEach(this.y_pad_dict, (dict: any, scale_id) => {
718 let max = 0;
719 _.forEach(dict, (value: number, key) => {
720 max = Math.max(max, value);
721 });
722 this.yPaddingArr[scale_id] = max;
723 });
724 // This is for the figure to relayout everything to account for the
725 // updated margins.
726 this.trigger('margin_updated');
727 }
728
729 update_plotarea_dimensions() {
730 this.plotarea_width = this.width - this.margin.left - this.margin.right;
731 this.plotarea_height = this.height - this.margin.top - this.margin.bottom;
732 }
733
734 processPhosphorMessage(msg) {
735 super.processPhosphorMessage.apply(this, arguments);
736
737 switch (msg.type) {
738 case 'resize':
739 case 'after-show':
740 case 'after-attach':
741 if (this.pWidget.isVisible) {
742 this.debouncedRelayout();
743 }
744 break;
745 }
746 }
747
748 relayout() {
749 const relayoutImpl = () => {
750 this.relayoutRequested = false; // reset relayout request
751 const figureSize = this.getFigureSize();
752
753 if (this.width == figureSize.width && this.height == figureSize.height) {
754 // Bypass relayout
755 return;
756 }
757
758 this.width = figureSize.width;
759 this.height = figureSize.height;
760 // update ranges
761 this.margin = this.model.get('fig_margin');
762 this.update_plotarea_dimensions();
763 // we hide it when the plot area is too small
764 if (this.plotarea_width < 1 || this.plotarea_width < 1) {
765 this.el.style.visibility = 'hidden';
766 return; // no need to continue setting properties, which can only produce errors in the js console
767 } else {
768 this.el.style.visibility = '';
769 }
770
771 if (this.scale_x !== undefined && this.scale_x !== null) {
772 this.scale_x.set_range([0, this.plotarea_width]);
773 }
774
775 if (this.scale_y !== undefined && this.scale_y !== null) {
776 this.scale_y.set_range([this.plotarea_height, 0]);
777 }
778
779 // transform figure
780 this.fig.attr(
781 'transform',
782 'translate(' + this.margin.left + ',' + this.margin.top + ')'
783 );
784 this.fig_background.attr(
785 'transform',
786 'translate(' + this.margin.left + ',' + this.margin.top + ')'
787 );
788 applyAttrs(this.title, {
789 x: 0.5 * this.plotarea_width,
790 y: -(this.margin.top / 2.0),
791 dy: '1em',
792 });
793
794 this.bg
795 .attr('width', this.plotarea_width)
796 .attr('height', this.plotarea_height);
797 this.bg_events
798 .attr('width', this.plotarea_width)
799 .attr('height', this.plotarea_height);
800
801 this.clip_path
802 .attr('width', this.plotarea_width)
803 .attr('height', this.plotarea_height);
804
805 this.trigger('margin_updated');
806 this.update_legend();
807 this.layout_webgl_canvas();
808 };
809
810 if (!this.relayoutRequested) {
811 this.relayoutRequested = true; // avoid scheduling a relayout twice
812 requestAnimationFrame(relayoutImpl.bind(this));
813 }
814 }
815
816 layout_webgl_canvas() {
817 if (this.renderer) {
818 this.renderer.domElement.style =
819 'left: ' +
820 this.margin.left +
821 'px; ' +
822 'top: ' +
823 this.margin.top +
824 'px;';
825 this.renderer.setSize(this.plotarea_width, this.plotarea_height);
826 this.update_gl();
827 }
828 }
829
830 update_legend() {
831 this.fig_marks.selectAll('.g_legend').remove();
832
833 const legend_height = 14;
834 const legend_width = 24;
835 const legend_location = this.model.get('legend_location');
836
837 const legend_g = this.fig_marks.append('g').attr('class', 'g_legend');
838
839 let count = 1;
840 let max_label_len = 1;
841
842 if (this.mark_views !== undefined && this.mark_views !== null) {
843 Promise.all(this.mark_views.views).then((views) => {
844 views.forEach((mark_view: any) => {
845 if (mark_view.model.get('display_legend')) {
846 const child_count = mark_view.draw_legend(
847 legend_g,
848 0,
849 count * (legend_height + 2),
850 0,
851 legend_height + 2
852 );
853 count = count + child_count[0];
854 max_label_len = child_count[1]
855 ? Math.max(max_label_len, child_count[1])
856 : max_label_len;
857 }
858 });
859
860 const coords = this.get_legend_coords(
861 legend_location,
862 legend_width,
863 (count + 1) * (legend_height + 2),
864 0
865 );
866 if (count !== 1) {
867 legend_g
868 .insert('g', ':first-child')
869 .attr('class', 'axis')
870 .append('rect')
871 .attr('y', (legend_height + 2) / 2.0)
872 .attr('x', -0.5 * (legend_height + 2))
873 .attr('width', max_label_len + 2 + 'em')
874 .attr('height', count * (legend_height + 2));
875 }
876 max_label_len =
877 legend_location === 'top-right' ||
878 legend_location === 'right' ||
879 legend_location === 'bottom-right'
880 ? -(max_label_len + 2)
881 : 1;
882 const em = 16;
883 legend_g.attr(
884 'transform',
885 'translate(' +
886 String(coords[0] + max_label_len * em) +
887 ' ' +
888 String(coords[1]) +
889 ') '
890 );
891
892 applyStyles(
893 legend_g.selectAll('text.legendtext'),
894 this.model.get('legend_text')
895 );
896
897 applyStyles(
898 legend_g.selectAll('.axis').selectAll('rect'),
899 this.model.get('legend_style')
900 );
901 });
902 }
903 }
904
905 get_legend_coords(
906 legend_location:
907 | 'top'
908 | 'top-right'
909 | 'right'
910 | 'bottom-right'
911 | 'bottom'
912 | 'bottom-left'
913 | 'left',
914 width: number,
915 height: number,
916 disp: number
917 ) {
918 let x_start = 0;
919 let y_start = 0;
920 const fig_width = this.plotarea_width;
921 const fig_height = this.plotarea_height;
922
923 switch (legend_location) {
924 case 'top':
925 x_start = fig_width * 0.5 - width;
926 y_start = 0;
927 break;
928 case 'top-right':
929 x_start = fig_width - disp;
930 y_start = 0;
931 break;
932 case 'right':
933 x_start = fig_width - disp;
934 y_start = fig_height * 0.5 - height;
935 break;
936 case 'bottom-right':
937 x_start = fig_width - disp;
938 y_start = fig_height - height;
939 break;
940 case 'bottom':
941 x_start = fig_width * 0.5 - width;
942 y_start = fig_height - height;
943 break;
944 case 'bottom-left':
945 x_start = 0;
946 y_start = fig_height - height;
947 break;
948 case 'left':
949 x_start = 0;
950 y_start = fig_height * 0.5 - height;
951 break;
952 default:
953 x_start = 0;
954 y_start = 0;
955 }
956 return [x_start, y_start];
957 }
958
959 async set_interaction(model: WidgetModel | null): Promise<WidgetView> {
960 if (model) {
961 // Sets the child interaction
962 await model.state_change;
963
964 // Sets the child interaction
965 // @ts-ignore: We should use the type argument: this.create_child_view<Interaction>
966 const view: Interaction = await this.create_child_view(model);
967
968 if (this.interaction_view) {
969 this.interaction_view.remove();
970 }
971 this.interaction_view = view;
972 this.interaction.node().appendChild(view.el);
973 this.displayed.then(() => {
974 view.trigger('displayed');
975 });
976 return view;
977 } else {
978 if (this.interaction_view) {
979 this.interaction_view.remove();
980 }
981 return Promise.resolve(null);
982 }
983 }
984
985 update_title(model, title) {
986 this.title.text(this.model.get('title'));
987 }
988
989 remove() {
990 if (this.mark_views !== undefined && this.mark_views !== null) {
991 this.mark_views.remove();
992 }
993 if (this.axis_views !== undefined && this.axis_views !== null) {
994 this.axis_views.remove();
995 }
996 if (this.tooltip_div !== undefined) {
997 this.tooltip_div.remove();
998 }
999 return super.remove.apply(this, arguments);
1000 }
1001
1002 get_svg() {
1003 // Returns the outer html of the figure svg
1004
1005 const replaceAll = (find, replace, str) => {
1006 return str.replace(new RegExp(find, 'g'), replace);
1007 };
1008
1009 const get_css = (node, regs) => {
1010 /**
1011 * Gathers all the css rules applied to elements of the svg
1012 * node. Removes the parent element selectors specified in
1013 * argument `regs`.
1014 */
1015 let css = '';
1016 const sheets = document.styleSheets;
1017 let selector;
1018 for (let i = 0; i < sheets.length; i++) {
1019 let rules: any = null;
1020 // due to CORS we may have some sheets we cannot access, instead of checking we always try
1021 try {
1022 rules = (sheets[i] as CSSStyleSheet).cssRules;
1023 } catch (e) {
1024 // ignore CORS errors
1025 }
1026 if (rules) {
1027 for (let j = 0; j < rules.length; j++) {
1028 const rule = rules[j];
1029 if (typeof rule.style !== 'undefined') {
1030 let match = null;
1031 try {
1032 match = node.querySelectorAll(rule.selectorText);
1033 } catch (err) {
1034 console.warn(
1035 "Invalid CSS selector '" + rule.selectorText + "'",
1036 err
1037 );
1038 }
1039 if (match) {
1040 const elems = node.querySelectorAll(rule.selectorText);
1041 if (elems.length > 0) {
1042 selector = rule.selectorText;
1043 for (let r = 0; r < regs.length; r++) {
1044 selector = replaceAll(regs[r], '', selector);
1045 }
1046 css += `${selector} { ${rule.style.cssText} }
1047 `;
1048 }
1049 } else if (rule.cssText.match(/^@font-face/)) {
1050 css += rule.cssText + '\n';
1051 }
1052 }
1053 }
1054 }
1055 }
1056 // TODO: this is terrible. The previous loop over style sheets
1057 // does not catch document's top-level properties.
1058 css += 'svg { font-size: 10px; }\n';
1059 return css;
1060 };
1061
1062 // Even though the canvas may display the rendering already, it is not guaranteed it can be read of the canvas
1063 // or we have to set preserveDrawingBuffer to true, which may impact performance.
1064 // Instead, we render again, and directly afterwards we do get the pixel data using canvas.toDataURL
1065 return this.render_gl().then(async () => {
1066 // Create standalone SVG string
1067 const node_background: any = this.svg_background.node();
1068 const node_foreground: any = this.svg.node();
1069 const width = this.plotarea_width;
1070 const height = this.plotarea_height;
1071
1072 // Creates a standalone SVG string from an inline SVG element
1073 // containing all the computed style attributes.
1074 const svg = node_foreground.cloneNode(true);
1075 // images can contain blob urls, we transform those to data urls
1076 const blobToDataUrl = async (el) => {
1077 const blob = await (await fetch(el.getAttribute('href'))).blob();
1078 const reader = new FileReader();
1079 const readerPromise = new Promise((resolve, reject) => {
1080 reader.onloadend = resolve;
1081 reader.onerror = reject;
1082 reader.abort = reject;
1083 });
1084 reader.readAsDataURL(blob);
1085 await readerPromise;
1086 el.setAttribute('href', reader.result);
1087 };
1088 const images = [...svg.querySelectorAll('image')];
1089 await Promise.all(images.map(blobToDataUrl));
1090 svg.setAttribute('version', '1.1');
1091 svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
1092 svg.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
1093 svg.setAttribute('width', this.width);
1094 svg.setAttribute('height', this.height);
1095 svg.style.background = window.getComputedStyle(document.body).background;
1096
1097 const computedStyle = window.getComputedStyle(this.el);
1098 const cssCode =
1099 get_css(this.el, [
1100 '.theme-dark',
1101 '.theme-light',
1102 '.bqplot > ',
1103 ':root',
1104 ]) + '\n';
1105 // extract all CSS variables, and generate a piece of css to define the variables
1106 const cssVariables = cssCode.match(/(--\w[\w-]*)/g) || [];
1107 const cssVariableCode =
1108 cssVariables.reduce((cssCode, variable) => {
1109 const value = computedStyle.getPropertyValue(variable);
1110 return `${cssCode}\n\t${variable}: ${value};`;
1111 }, ':root {') + '\n}\n';
1112
1113 // and put the CSS in a style element
1114 const styleElement = document.createElement('style');
1115 styleElement.setAttribute('type', 'text/css');
1116 styleElement.innerHTML =
1117 '<![CDATA[\n' + cssVariableCode + cssCode + ']]>';
1118
1119 const defs = document.createElement('defs');
1120 defs.appendChild(styleElement);
1121 // we put the svg background part before the marks
1122 const g_root = svg.children[0];
1123 const svg_background = node_background.cloneNode(true);
1124 // first the axes
1125 g_root.insertBefore(
1126 svg_background.children[0].children[1],
1127 g_root.children[0]
1128 );
1129 // and the background as first element
1130 g_root.insertBefore(
1131 svg_background.children[0].children[0],
1132 g_root.children[0]
1133 );
1134
1135 // and add the webgl canvas as an image
1136 if (this.renderer) {
1137 const data_url = this.renderer.domElement.toDataURL('image/png');
1138 const marks = d3.select(g_root.children[3]);
1139 marks
1140 .insert('image', ':first-child')
1141 .attr('x', 0)
1142 .attr('y', 0)
1143 .attr('width', 1)
1144 .attr('height', 1)
1145 .attr('preserveAspectRatio', 'none')
1146 .attr('transform', 'scale(' + width + ', ' + height + ')')
1147 .attr('href', data_url);
1148 }
1149
1150 svg.insertBefore(defs, svg.firstChild);
1151 // Getting the outer HTML
1152 return svg.outerHTML;
1153 });
1154 }
1155
1156 async get_rendered_canvas(scale): Promise<HTMLCanvasElement> {
1157 // scale up the underlying canvas for high dpi screens
1158 // such that image is of the same quality
1159 scale = scale || window.devicePixelRatio;
1160 // Render a SVG data into a canvas and
1161 const xml = await this.get_svg();
1162
1163 return new Promise((resolve) => {
1164 const image = new Image();
1165 image.onload = () => {
1166 const canvas = document.createElement('canvas');
1167 canvas.classList.add('bqplot');
1168 canvas.width = this.width * scale;
1169 canvas.height = this.height * scale;
1170 canvas.style.width = this.width.toString();
1171 canvas.style.height = this.height.toString();
1172 const context = canvas.getContext('2d');
1173 context.scale(scale, scale);
1174 context.drawImage(image, 0, 0);
1175 resolve(canvas);
1176 };
1177 image.src =
1178 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(xml)));
1179 });
1180 }
1181
1182 async upload_png(model, scale) {
1183 const canvas = await this.get_rendered_canvas(scale);
1184 canvas.toBlob(async (blob) => {
1185 const buff = await blob.arrayBuffer();
1186 model.send(
1187 {
1188 event: 'upload_png',
1189 },
1190 null,
1191 [buff]
1192 );
1193 });
1194 }
1195
1196 save_png(filename, scale) {
1197 // Render a SVG data into a canvas and download as PNG.
1198
1199 this.get_rendered_canvas(scale).then((canvas: any) => {
1200 const a = document.createElement('a');
1201 a.download = filename || 'image.png';
1202 a.href = canvas.toDataURL('image/png');
1203 document.body.appendChild(a);
1204 a.click();
1205 });
1206 }
1207
1208 save_svg(filename: string) {
1209 this.get_svg().then((xml) => {
1210 const a = document.createElement('a');
1211 a.download = filename || 'bqplot.svg';
1212 a.href = 'data:text/plain;charset=utf-8,' + encodeURIComponent(xml);
1213 document.body.appendChild(a);
1214 a.click();
1215 document.body.removeChild(a);
1216 });
1217 }
1218
1219 async getPixel(x, y) {
1220 const canvas = await this.get_rendered_canvas(window.devicePixelRatio);
1221 const context = canvas.getContext('2d');
1222 const pixel = context.getImageData(
1223 x * window.devicePixelRatio,
1224 y * window.devicePixelRatio,
1225 1,
1226 1
1227 );
1228 return pixel.data;
1229 }
1230
1231 update_gl() {
1232 if (!this._update_requested) {
1233 this._update_requested = true;
1234 requestAnimationFrame(this._update_gl.bind(this));
1235 }
1236 }
1237
1238 _update_gl() {
1239 this.render_gl();
1240 this._update_requested = false;
1241 }
1242
1243 async render_gl(): Promise<void> {
1244 // Nothing to render using a WebGL context
1245 if (!this.renderer) {
1246 return Promise.resolve();
1247 }
1248
1249 const views = await Promise.all(this.mark_views.views);
1250
1251 // render all marks that have a render_gl method
1252 this.renderer.autoClear = false;
1253 this.renderer.autoClearColor = new (THREE.Color as (x) => void)(0x000000);
1254 this.renderer.clear();
1255 const marks_gl = _.filter(views, (view: Mark) => view['render_gl']);
1256
1257 for (const mark of marks_gl) {
1258 mark['render_gl']();
1259 }
1260 }
1261
1262 change_theme() {
1263 this.el.classList.remove(this.model.previous('theme'));
1264 this.el.classList.add(this.model.get('theme'));
1265 }
1266
1267 axis_views: widgets.ViewList<widgets.DOMWidgetView>;
1268 bg: d3.Selection<SVGRectElement, any, any, any>;
1269 bg_events: d3.Selection<SVGRectElement, any, any, any>;
1270 change_layout: () => void;
1271 clip_id: string;
1272 clip_path: d3.Selection<SVGRectElement, any, any, any>;
1273 debouncedRelayout: () => void;
1274 fig_axes: d3.Selection<SVGGraphicsElement, any, any, any>;
1275 fig_marks: d3.Selection<SVGGraphicsElement, any, any, any>;
1276 fig_background: d3.Selection<SVGGraphicsElement, any, any, any>;
1277 fig: d3.Selection<SVGGraphicsElement, any, any, any>;
1278 figure_padding_x: number;
1279 figure_padding_y: number;
1280 height: number;
1281 interaction_view: Interaction;
1282 interaction: d3.Selection<SVGGElement, any, any, any>;
1283 margin: { top: number; bottom: number; left: number; right: number };
1284 mark_views: widgets.ViewList<Mark>;
1285 plotarea_height: number;
1286 plotarea_width: number;
1287 popper_reference: popper.ReferenceObject;
1288 popper: popper;
1289 renderer: THREE.WebGLRenderer | null;
1290 scale_x: Scale;
1291 scale_y: Scale;
1292 svg: d3.Selection<SVGElement, any, any, any>;
1293 svg_background: d3.Selection<SVGElement, any, any, any>;
1294 title: d3.Selection<SVGTextElement, any, any, any>;
1295 tooltip_div: d3.Selection<HTMLDivElement, any, any, any>;
1296 width: number;
1297 x_pad_dict: { [id: string]: number };
1298 xPaddingArr: { [id: string]: number };
1299 y_pad_dict: { [id: string]: number };
1300 yPaddingArr: { [id: string]: number };
1301
1302 private dummyNodes: Dict<any> = {};
1303
1304 private _update_requested: boolean;
1305 private relayoutRequested: boolean = false;
1306
1307 // this is public for the test framework, but considered a private API
1308 public _initial_marks_created: Promise<any>;
1309 private _initial_marks_created_resolve: Function;
1310 }