Debian Codegraph @

js/src/Axis.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 { WidgetView } from '@jupyter-widgets/base';
17 import * as d3 from 'd3';
18 // const d3 =Object.assign({}, require("d3-axis"), require("d3-format"), require("d3-selection"), require("d3-selection-multi"), require("d3-time"), require("d3-time-format"));
19 import * as utils from './utils';
20 import * as _ from 'underscore';
21 import { applyAttrs, applyStyles } from './utils';
22 import { Figure } from './Figure';
23 import { Scale } from './Scale';
24 import { isOrdinalScale } from './OrdinalScale';
25 import { isDateScale } from './DateScale';
26 import { isLogScale } from './LogScale';
27 import { isLinearScale } from './LinearScale';
28 import { isDateColorScale } from './DateColorScale';
29 import { isColorScale } from './ColorScale';
30
31 // Polyfill for Math.log10 in IE11
32 Math.log10 =
33 Math.log10 ||
34 function (x) {
35 return Math.log(x) / Math.LN10;
36 };
37
38 const DATESCALE_WIDTH_THRESHOLD = 500;
39 const UNITS_ARRAY = ['em', 'ex', 'px'];
40
41 export class Axis extends WidgetView {
42 initialize() {
43 this.setElement(
44 document.createElementNS(d3.namespaces.svg, 'g') as HTMLElement
45 );
46 this.d3el = d3.select(this.el);
47 super.initialize.apply(this, arguments);
48 }
49
50 render() {
51 this.d3el.style('display', this.model.get('visible') ? 'inline' : 'none');
52 this.parent = this.options.parent;
53
54 const scale_promise = this.set_scale_promise(this.model.get('scale'));
55 const offset_promise = this.get_offset_promise();
56
57 Promise.all([scale_promise, offset_promise]).then(() => {
58 this.create_listeners();
59 this.tick_format = this.generate_tick_formatter();
60 this.set_scales_range();
61 this.append_axis();
62 });
63 }
64
65 create_listeners() {
66 // Creates all event listeners
67
68 this.listenTo(this.model, 'change:scale', (model, value) => {
69 this.update_scale(model.previous('scale'), value);
70 // TODO: rescale_axis does too many things. Decompose
71 this.axis.scale(this.axis_scale.scale as d3.AxisScale<d3.AxisDomain>); // TODO: this is in redraw_axisline
72 this.rescale_axis();
73 });
74
75 // Tick attributes
76 this.listenTo(this.model, 'change:tick_values', this.set_tick_values);
77 this.listenTo(this.model, 'change:tick_format', this.tickformat_changed);
78 this.listenTo(this.model, 'change:num_ticks', this.set_tick_values);
79 this.listenTo(this.model, 'change:tick_rotate', this.apply_tick_styling);
80 this.listenTo(this.model, 'change:tick_style', this.apply_tick_styling);
81
82 // Label attributes
83 this.model.on_some_change(
84 ['label', 'label_color'],
85 this.update_label,
86 this
87 );
88
89 // Axis attributes
90 this.listenTo(this.model, 'change:color', this.update_color);
91 this.model.on_some_change(
92 ['grid_color', 'grid_lines'],
93 this.update_grid_lines,
94 this
95 );
96 this.listenTo(
97 this.model,
98 'change:label_location',
99 this.update_label_location
100 );
101 this.listenTo(this.model, 'change:label_offset', this.update_label_offset);
102 this.listenTo(this.model, 'change:visible', this.update_visibility);
103 this.model.on_some_change(
104 ['side', 'orientation'],
105 this.update_display,
106 this
107 );
108 this.listenTo(this.model, 'change:offset', this.update_offset);
109 this.listenTo(this.parent, 'margin_updated', this.parent_margin_updated);
110 }
111
112 update_offset() {
113 const offset_creation_promise = this.get_offset_promise();
114 offset_creation_promise.then(() => {
115 this.set_scales_range();
116 this.update_offset_scale_domain();
117 this.g_axisline.attr('transform', this.get_axis_transform());
118 this.update_grid_lines();
119 });
120 }
121
122 update_display() {
123 this.g_axisline.remove();
124 this.set_scales_range();
125 this.append_axis();
126 }
127
128 set_tick_values(animate?: boolean) {
129 // Sets specific tick values from "tick_values" parameter
130
131 let useticks = [];
132 const tick_values = this.model.get('tick_values');
133 const num_ticks = this.model.get('num_ticks');
134
135 if (
136 tick_values !== undefined &&
137 tick_values !== null &&
138 tick_values.length > 0
139 ) {
140 this.axis.tickValues(this.get_ticks_from_array_or_length(tick_values));
141 } else if (num_ticks !== undefined && num_ticks !== null) {
142 this.axis.tickValues(this.get_ticks_from_array_or_length());
143 } else {
144 if (isDateScale(this.axis_scale)) {
145 // Reduce number of suggested ticks if figure width is below the
146 // threshold. Note: "undefined" will result in the D3 default
147 // setting
148 const numDateTicks =
149 this.width < DATESCALE_WIDTH_THRESHOLD ? 5 : undefined;
150 const scale = this.axis_scale.scale;
151 this.axis.tickValues(scale.ticks(numDateTicks));
152 } else if (isOrdinalScale(this.axis_scale)) {
153 this.axis.tickValues(this.axis_scale.scale.domain());
154 } else if (isLogScale(this.axis_scale)) {
155 let i, r;
156 const scale = this.axis_scale.scale;
157 const allticks = scale.ticks();
158 const oom = Math.abs(Math.log10(scale.domain()[1] / scale.domain()[0]));
159 if (oom < 2) {
160 this.axis.tickValues(allticks);
161 } else if (oom < 7) {
162 useticks = [];
163 for (i = 0; i < allticks.length; i++) {
164 r = Math.abs(Math.log10(allticks[i]) % 1);
165 if (
166 Math.abs(r) < 0.001 ||
167 Math.abs(r - 1) < 0.001 ||
168 Math.abs(r - 0.30103) < 0.001 ||
169 Math.abs(r - 0.69897) < 0.001
170 ) {
171 useticks.push(allticks[i]);
172 }
173 }
174 this.axis.tickValues(useticks);
175 } else {
176 useticks = [];
177 const s = Math.round(oom / 10);
178 for (i = 0; i < allticks.length; i++) {
179 r = Math.abs(Math.log10(allticks[i]) % s);
180 if (Math.abs(r) < 0.001 || Math.abs(r - s) < 0.001) {
181 useticks.push(allticks[i]);
182 }
183 }
184 this.axis.tickValues(useticks);
185 }
186 } else if (
187 isLinearScale(this.axis_scale) ||
188 isColorScale(this.axis_scale)
189 ) {
190 this.axis.tickValues(this.axis_scale.scale.ticks());
191 }
192 }
193 if (
194 this.model.get('tick_format') === null ||
195 this.model.get('tick_format') === undefined
196 ) {
197 if (!isOrdinalScale(this.axis_scale)) {
198 this.tick_format = this.guess_tick_format(this.axis.tickValues());
199 }
200 }
201 this.axis.tickFormat(this.tick_format);
202
203 if (this.g_axisline) {
204 this.g_axisline
205 .transition('set_tick_values')
206 .duration(
207 animate === true ? this.parent.model.get('animation_duration') : 0
208 )
209 .call(this.axis);
210
211 this.apply_tick_styling();
212 }
213 }
214
215 tickformat_changed() {
216 this.tick_format = this.generate_tick_formatter();
217 this.axis.tickFormat(this.tick_format);
218 if (this.g_axisline) {
219 this.g_axisline.call(this.axis);
220 }
221 this.apply_tick_styling();
222 }
223
224 apply_tick_styling() {
225 // Applies current tick styling to all displayed ticks
226 const tickText = this.g_axisline.selectAll('.tick text');
227 applyStyles(tickText, this.model.get('tick_style'));
228 tickText.attr('transform', this.get_tick_transforms());
229 }
230
231 get_tick_transforms() {
232 // parses object and returns a string that can be passed to a D3 as a
233 // set of options
234 // Note: Currently, only the `tick_rotate` attribute uses .transform()
235
236 const rotation = this.model.get('tick_rotate');
237 return `rotate(${rotation})`;
238 }
239
240 update_scales() {
241 // Updates the domains of both scales
242
243 this.update_scale_domain();
244 this.update_offset_scale_domain();
245 }
246
247 update_scale_domain() {
248 // Sets the scale domain (Range of input values)
249
250 const is_vertical = this.model.get('orientation') === 'vertical';
251
252 const initial_range = is_vertical
253 ? this.parent.padded_range('y', this.axis_scale.model)
254 : this.parent.padded_range('x', this.axis_scale.model);
255
256 const target_range = is_vertical
257 ? this.parent.range('y')
258 : this.parent.range('x');
259
260 this.axis_scale.expand_domain(initial_range, target_range);
261 this.axis.scale(this.axis_scale.scale as d3.AxisScale<d3.AxisDomain>);
262 }
263
264 update_offset_scale_domain() {
265 // Sets the domain (range of input values) of the offset scale
266
267 const is_vertical = this.model.get('orientation') === 'vertical';
268
269 if (this.offset_scale) {
270 const initial_range = !is_vertical
271 ? this.parent.padded_range('y', this.offset_scale.model)
272 : this.parent.padded_range('x', this.offset_scale.model);
273
274 const target_range = !is_vertical
275 ? this.parent.range('y')
276 : this.parent.range('x');
277
278 this.offset_scale.expand_domain(initial_range, target_range);
279 }
280 }
281
282 generate_tick_formatter() {
283 if (isDateScale(this.axis_scale) || isDateColorScale(this.axis_scale)) {
284 if (this.model.get('tick_format')) {
285 return d3.utcFormat(this.model.get('tick_format'));
286 } else {
287 return this.guess_tick_format();
288 }
289 } else if (isOrdinalScale(this.axis_scale)) {
290 const tick_format = this.model.get('tick_format');
291 if (tick_format) {
292 //TODO: This may not be the best way to do this. We can
293 //check the instance of the elements in the domain and
294 //apply the format depending on that.
295 if (utils.is_valid_time_format(tick_format)) {
296 return d3.utcFormat(tick_format);
297 } else {
298 return d3.format(tick_format);
299 }
300 }
301 return (d) => {
302 return d;
303 };
304 } else {
305 // linear or log scale
306 if (this.model.get('tick_format')) {
307 return d3.format(this.model.get('tick_format'));
308 }
309 return this.guess_tick_format();
310 }
311 }
312
313 set_scales_range() {
314 const is_vertical = this.model.get('orientation') === 'vertical';
315
316 this.axis_scale.set_range(is_vertical ? [this.height, 0] : [0, this.width]);
317 if (this.offset_scale) {
318 this.offset_scale.set_range(
319 is_vertical ? [0, this.width] : [this.height, 0]
320 );
321 }
322 }
323
324 create_axis() {
325 // Creates the initial D3 axis and sets it on this.axis
326
327 const is_vertical = this.model.get('orientation') === 'vertical';
328 const side = this.model.get('side');
329
330 if (is_vertical) {
331 this.axis =
332 side === 'right'
333 ? d3.axisRight(this.axis_scale.scale as d3.AxisScale<d3.AxisDomain>)
334 : d3.axisLeft(this.axis_scale.scale as d3.AxisScale<d3.AxisDomain>);
335 } else {
336 this.axis =
337 side === 'top'
338 ? d3.axisTop(this.axis_scale.scale as d3.AxisScale<d3.AxisDomain>)
339 : d3.axisBottom(this.axis_scale.scale as d3.AxisScale<d3.AxisDomain>);
340 }
341 }
342
343 append_axis() {
344 this.create_axis();
345 this.update_scales();
346
347 // Create initial SVG element
348 this.g_axisline = this.d3el
349 .append('g')
350 .attr('class', 'axis')
351 .attr('transform', this.get_axis_transform())
352 .call(this.axis);
353
354 // Create element for axis label
355 const lineText = this.g_axisline
356 .append('text')
357 .attr('class', 'axislabel')
358 .text(this.model.get('label'));
359 applyStyles(lineText, this.get_text_styling());
360 applyAttrs(lineText, this.get_label_attributes());
361
362 // Apply custom settings
363 this.set_tick_values();
364 this.update_grid_lines();
365 this.update_color();
366 this.apply_tick_styling();
367 this.update_label();
368 }
369
370 get_offset_promise() {
371 /*
372 * The offset may require the creation of a Scale, which is async
373 * Hence, get_offset_promise returns a promise.
374 */
375 let return_promise = Promise.resolve();
376 const offset = this.model.get('offset');
377 const is_vertical = this.model.get('orientation') === 'vertical';
378
379 if (offset.value !== undefined && offset.value !== null) {
380 //If scale is undefined but, the value is defined, then we have
381 //to
382 if (offset.scale === undefined) {
383 this.offset_scale = is_vertical
384 ? this.parent.scale_x
385 : this.parent.scale_y;
386 } else {
387 return_promise = this.create_child_view(offset.scale).then((view) => {
388 this.offset_scale = view as WidgetView as Scale;
389 if (
390 isLinearScale(this.offset_scale) ||
391 isDateScale(this.offset_scale) ||
392 isLogScale(this.offset_scale)
393 ) {
394 this.offset_scale.scale.clamp(true);
395 }
396 this.offset_scale.on('domain_changed', () => {
397 this.update_offset_scale_domain();
398 this.g_axisline.attr('transform', this.get_axis_transform());
399 this.update_grid_lines();
400 });
401 });
402 }
403 this.offset_value = offset.value;
404 } else {
405 //required if the offset has been changed from a valid value
406 //to null
407 this.offset_scale = this.offset_value = undefined;
408 }
409 return return_promise;
410 }
411
412 highlight() {
413 this.g_axisline.classed('axisbold', true);
414 }
415
416 unhighlight() {
417 this.g_axisline.classed('axisbold', false);
418 }
419
420 get_basic_transform() {
421 const is_vertical = this.model.get('orientation') === 'vertical';
422 const side = this.model.get('side');
423
424 if (is_vertical) {
425 return side === 'right' ? this.width : 0;
426 } else {
427 return side === 'top' ? 0 : this.height;
428 }
429 }
430
431 get_axis_transform() {
432 const is_vertical = this.model.get('orientation') === 'vertical';
433 if (is_vertical) {
434 return 'translate(' + this.process_offset() + ', 0)';
435 } else {
436 return 'translate(0, ' + this.process_offset() + ')';
437 }
438 }
439
440 process_offset() {
441 if (this.offset_scale === undefined || this.offset_scale === null) {
442 return this.get_basic_transform();
443 } else {
444 let value = this.offset_scale.scale(this.offset_value);
445 //The null check is required for two reasons. Value may be null
446 //or the scale is ordinal which does not include the value in
447 //its domain.
448 value = value === undefined ? this.get_basic_transform() : value;
449 return this.offset_scale.offset + value;
450 }
451 }
452
453 get_label_attributes() {
454 // Returns an object based on values of "label_location" and "label_offset"
455
456 let label_x = 0;
457 const label_location = this.model.get('label_location');
458 const label_offset = this.calculate_label_offset();
459 const is_vertical = this.model.get('orientation') === 'vertical';
460 const side = this.model.get('side');
461
462 if (is_vertical) {
463 if (label_location === 'start') {
464 label_x = -this.height;
465 } else if (label_location === 'middle') {
466 label_x = -this.height / 2;
467 }
468 if (side === 'right') {
469 return {
470 transform: 'rotate(-90)',
471 x: label_x,
472 y: label_offset,
473 dy: '1ex',
474 dx: '0em',
475 };
476 } else {
477 return {
478 transform: 'rotate(-90)',
479 x: label_x,
480 y: label_offset,
481 dy: '0em',
482 dx: '0em',
483 };
484 }
485 } else {
486 if (label_location === 'middle') {
487 label_x = this.width / 2;
488 } else if (label_location === 'end') {
489 label_x = this.width;
490 }
491 if (side === 'top') {
492 return {
493 x: label_x,
494 y: label_offset,
495 dy: '0.75ex',
496 dx: '0em',
497 transform: '',
498 };
499 } else {
500 return {
501 x: label_x,
502 y: label_offset,
503 dy: '0.25ex',
504 dx: '0em',
505 transform: '',
506 };
507 }
508 }
509 }
510
511 get_text_styling() {
512 // This function returns the text styling based on the attributes
513 // of the axis. As of now, only the text-anchor attribute is set.
514 // More can be added :)
515 const label_location = this.model.get('label_location');
516 if (label_location === 'start') {
517 return { 'text-anchor': 'start' };
518 } else if (label_location === 'end') {
519 return { 'text-anchor': 'end' };
520 } else {
521 return { 'text-anchor': 'middle' };
522 }
523 }
524
525 update_label() {
526 this.g_axisline.select('text.axislabel').text(this.model.get('label'));
527 this.d3el.selectAll('.axislabel').selectAll('text');
528 if (
529 this.model.get('label_color') !== '' &&
530 this.model.get('label_color') !== null
531 ) {
532 this.g_axisline
533 .select('text.axislabel')
534 .style('fill', this.model.get('label_color'));
535 this.d3el
536 .selectAll('.axislabel')
537 .selectAll('text')
538 .style('fill', this.model.get('label_color'));
539 }
540 }
541
542 update_label_location() {
543 const axisLabel = this.g_axisline.select('text.axislabel');
544 applyStyles(axisLabel, this.get_text_styling());
545 applyAttrs(axisLabel, this.get_label_attributes());
546 }
547
548 update_label_offset(model, offset) {
549 this.label_offset = this.calculate_label_offset();
550 this.g_axisline.select('text.axislabel').attr('y', this.label_offset);
551 }
552
553 calculate_label_offset() {
554 // If the label offset is not defined, depending on the orientation
555 // of the axis, an offset is set.
556
557 let label_offset = this.model.get('label_offset');
558 const is_vertical = this.model.get('orientation') === 'vertical';
559 const side = this.model.get('side');
560
561 if (!label_offset) {
562 if (!is_vertical) {
563 label_offset = '2em';
564 } else {
565 label_offset = '4ex';
566 }
567 }
568 // Label_offset is a signed distance from the axis line. Positive
569 // is away from the figure and negative is towards the figure. The
570 // notion of away and towards is different for left/right and
571 // top/bottom axis.
572 let index = -1;
573 for (let i = 0; i < UNITS_ARRAY.length && index === -1; i++) {
574 index = label_offset.indexOf(UNITS_ARRAY[i]);
575 }
576
577 if (index === -1) {
578 return label_offset;
579 }
580
581 if (side === 'top' || side === 'left') {
582 const num = -1 * parseInt(label_offset.substring(0, index));
583 label_offset = num + label_offset.substring(index);
584 }
585 return label_offset;
586 }
587
588 update_grid_lines(animate?: boolean) {
589 const grid_type = this.model.get('grid_lines');
590 const side = this.model.get('side');
591 const orientation = this.model.get('orientation');
592 const is_x = orientation !== 'vertical';
593 const animation_duration =
594 animate === true ? this.parent.model.get('animation_duration') : 0;
595
596 let tickSize = orientation === 'vertical' ? -this.width : -this.height;
597 let tickOffset = 0;
598
599 //apply offsets if applicable
600 if (this.offset_scale) {
601 const offset = this.offset_scale.scale(this.offset_value);
602
603 if (side === 'bottom' || side == 'right') {
604 tickSize = -offset;
605 tickOffset = is_x ? this.height - offset : this.width - offset;
606 } else {
607 tickSize += offset;
608 tickOffset = -offset;
609 }
610 }
611
612 if (grid_type !== 'none') {
613 this.axis.tickSizeInner(tickSize).tickSizeOuter(6);
614 } else {
615 this.axis.tickSize(6);
616 }
617
618 this.g_axisline.selectAll('.tick').classed('short', grid_type === 'none');
619
620 this.g_axisline
621 .transition('update_grid_lines')
622 .duration(animation_duration)
623 .call(this.axis)
624 .selectAll('.tick line')
625 .attr(
626 is_x ? 'y1' : 'x1',
627 this.offset_scale && grid_type !== 'none' ? tickOffset : null
628 )
629 .style('stroke-dasharray', grid_type === 'dashed' ? '5, 5' : null);
630
631 this.apply_tick_styling();
632
633 if (this.model.get('grid_color')) {
634 this.g_axisline
635 .selectAll('.tick line')
636 .style('stroke', this.model.get('grid_color'));
637 }
638 }
639
640 update_color() {
641 if (this.model.get('color')) {
642 this.d3el
643 .selectAll('.tick')
644 .selectAll('text')
645 .style('fill', this.model.get('color'));
646 this.d3el.selectAll('.domain').style('stroke', this.model.get('color'));
647 }
648 }
649
650 redraw_axisline() {
651 // TODO: This call might not be necessary
652 // TODO: Doesn't do what it states.
653 // Has to redraw from a clean slate
654 this.update_scales();
655
656 //animate axis and grid lines on domain changes
657 const animate = true;
658 this.set_tick_values(animate);
659 this.update_grid_lines(animate);
660 }
661
662 rescale_axis() {
663 //function to be called when the range of the axis has been updated
664 //or the axis has to be repositioned.
665 this.set_scales_range();
666 //The following calls to update domains are made as the domain
667 //of the axis scale needs to be recalculated as the expansion due
668 //to the padding depends on the size of the canvas because of the
669 //presence of fixed pixel padding for the bounding box.
670 this.update_axis_domain();
671 this.update_scales();
672 this.g_axisline.attr('transform', this.get_axis_transform());
673 this.g_axisline.call(this.axis);
674 const axisLabel = this.g_axisline.select('text.axislabel');
675 applyAttrs(axisLabel, this.get_label_attributes());
676 applyStyles(axisLabel, this.get_text_styling());
677 // TODO: what follows is currently part of redraw_axisline
678 this.set_tick_values();
679 this.update_grid_lines();
680 this.apply_tick_styling();
681 }
682
683 update_axis_domain() {
684 const initial_range = this.vertical
685 ? this.parent.padded_range('y', this.axis_scale.model)
686 : this.parent.padded_range('x', this.axis_scale.model);
687 const target_range = this.vertical
688 ? this.parent.range('y')
689 : this.parent.range('x');
690 this.axis_scale.expand_domain(initial_range, target_range);
691 this.axis.scale(this.axis_scale.scale as d3.AxisScale<d3.AxisDomain>);
692 }
693
694 parent_margin_updated() {
695 // sets the new dimensions of the g element for the axis.
696 this.rescale_axis();
697 }
698
699 update_visibility(model, visible) {
700 this.d3el.style('display', visible ? 'inline' : 'none');
701 }
702
703 get_ticks_from_array_or_length(data_array?: any[]) {
704 // This function is to be called when the ticks are passed explicitly
705 // or the number of ticks to be drawn.
706 // Have to do different things based on the type of the scale.
707 // If an array is passed, then just scale and return equally spaced
708 // points in the array. This is the way it is done for ordinal
709 // scales.
710 let step, max;
711 const num_ticks = this.model.get('num_ticks');
712
713 if (isOrdinalScale(this.axis_scale)) {
714 data_array = this.axis_scale.scale.domain();
715 }
716 if (num_ticks !== undefined && num_ticks !== null && num_ticks < 2) {
717 return [];
718 }
719 if (data_array) {
720 if (
721 num_ticks == undefined ||
722 num_ticks == null ||
723 data_array.length <= num_ticks
724 ) {
725 return data_array;
726 } else {
727 step = Math.floor(data_array.length / (num_ticks - 1));
728 const indices = _.range(0, data_array.length, step);
729 return indices.map((index) => {
730 return data_array[index];
731 });
732 }
733 }
734 const scale_range = this.axis_scale.scale.domain();
735 const max_index = this.axis_scale.scale.domain().length - 1;
736 step =
737 ((scale_range[max_index] as any) - (scale_range[0] as any)) /
738 (num_ticks - 1);
739 if (isDateScale(this.axis_scale) || isDateColorScale(this.axis_scale)) {
740 //For date scale, the dates have to be converted into milliseconds
741 //since epoch time and then back.
742 scale_range[0] = (scale_range[0] as Date).getTime();
743 scale_range[max_index] = (scale_range[max_index] as Date).getTime();
744 max = (scale_range[max_index] as any) + step * 0.5;
745 const range_in_times = _.range(scale_range[0] as any, max, step);
746 return range_in_times.map((elem) => {
747 return new Date(elem);
748 });
749 } else {
750 max = (scale_range[max_index] as any) + step * 0.5;
751 return _.range(scale_range[0] as any, max, step);
752 }
753 }
754
755 set_scale_promise(model) {
756 // Sets the child scale
757 if (this.axis_scale) {
758 this.axis_scale.remove();
759 }
760 return this.create_child_view(model).then((view) => {
761 // Trigger the displayed event of the child view.
762 this.displayed.then(() => {
763 view.trigger('displayed');
764 });
765 this.axis_scale = view as WidgetView as Scale;
766 this.axis_scale.on('domain_changed', this.redraw_axisline, this);
767 this.axis_scale.on('highlight_axis', this.highlight, this);
768 this.axis_scale.on('unhighlight_axis', this.unhighlight, this);
769 });
770 }
771
772 update_scale(old, scale) {
773 // Called when the child scale changes
774 this.axis_scale.off();
775 this.set_scale_promise(scale);
776 }
777
778 _get_digits(number) {
779 return number === 0 ? 1 : Math.floor(Math.log10(Math.abs(number))) + 1;
780 }
781
782 _replace_trailing_zeros(str) {
783 //regex to replace the trailing
784 //zeros after the decimal point.
785 //Handles the case of exponentially formatted string
786 //TODO: Should be done in a single regex
787 const e_index = str.search('e');
788 if (e_index != -1) {
789 return (
790 str
791 .substring(0, e_index)
792 .replace(/(\.[0-9]*?)0+$/gi, '$1')
793 .replace(/\.$/, '') + str.substring(e_index)
794 );
795 } else {
796 return str.replace(/(\.[0-9]*?)0+$/gi, '$1').replace(/\.$/, '');
797 }
798 }
799
800 get_format_func(prec: number) {
801 if (prec === 0) {
802 // format this as an integer
803 return (number) => {
804 return d3.format('d')(Math.round(number));
805 };
806 }
807 //if it is -1, then it is a generic format
808 const fmt_string = prec == -1 ? '' : '.' + prec;
809 return (number) => {
810 const str = d3.format(fmt_string + 'g')(number);
811 const reg_str = str.replace(/-|\.|e/gi, '');
812 if (reg_str.length < 6) {
813 return this._replace_trailing_zeros(str);
814 } else {
815 //if length is more than 6, format it exponentially
816 if (fmt_string === '') {
817 //if fmt_string is "", then the number o/p can be
818 //arbitrarily large
819 let new_str = d3.format(fmt_string + 'e')(number);
820 if (new_str.length >= 7) {
821 //in the case of a round off error, setting the max
822 //limit to be 6
823 new_str = d3.format('.6e')(number);
824 }
825 return this._replace_trailing_zeros(new_str);
826 } else {
827 //Format with the precision required
828 return this._replace_trailing_zeros(
829 d3.format(fmt_string + 'e')(number)
830 );
831 }
832 }
833 };
834 }
835
836 _linear_scale_precision(ticks?: any[]): number {
837 if (!(isLinearScale(this.axis_scale) || isColorScale(this.axis_scale))) {
838 return -1;
839 }
840 ticks =
841 ticks === undefined || ticks === null
842 ? this.axis_scale.scale.ticks()
843 : ticks;
844 // Case where all data is concentrated into one point.
845 if (ticks.length === 1) {
846 return 1;
847 }
848 const diff = Math.abs(ticks[1] - ticks[0]);
849 const max = Math.max(Math.abs(ticks[0]), Math.abs(ticks[ticks.length - 1]));
850
851 const max_digits = this._get_digits(max);
852 // number of digits in the max
853 const diff_digits = this._get_digits(diff);
854 // number of digits in the min
855
856 const precision = Math.abs(max_digits - diff_digits);
857 // difference in the number of digits. The number of digits we have
858 // to display is the diff above + 1.
859 if (max_digits >= 0 && diff_digits > 0) {
860 if (max_digits <= 6) {
861 // format the number as an integer
862 return 0;
863 } else {
864 // precision plus 1 is returned here as they are the number of
865 // digits to be displayed. Capped at 6
866 return Math.min(precision, 6) + 1;
867 }
868 } else if (diff_digits <= 0) {
869 // return math.abs(diff_digits) + max_digits + 1. Capped at 6.
870 return Math.min(Math.abs(diff_digits) + max_digits, 6) + 1;
871 }
872 }
873
874 linear_sc_format(ticks?: any[]) {
875 return this.get_format_func(this._linear_scale_precision(ticks));
876 }
877
878 date_sc_format(ticks?: any[]) {
879 // assumes that scale is a linear date scale
880 if (!isDateScale(this.axis_scale)) {
881 return;
882 }
883 ticks =
884 ticks === undefined || ticks === null
885 ? this.axis_scale.scale.ticks()
886 : ticks;
887 // diff is the difference between ticks in milliseconds
888 const diff = Math.abs(ticks[1] - ticks[0]);
889
890 const format_millisecond = d3.utcFormat('.%L'),
891 format_second = d3.utcFormat(':%S'),
892 format_minute = d3.utcFormat('%I:%M'),
893 format_hour = d3.utcFormat('%I %p'),
894 format_day = d3.utcFormat('%b %d'),
895 format_month = d3.utcFormat('%b %Y'),
896 format_year = d3.utcFormat('%Y');
897
898 return (date) => {
899 let div = 1000;
900 if (Math.floor(diff / div) === 0) {
901 //diff is less than a second
902 if (d3.utcSecond(date) < date) {
903 return format_millisecond(date);
904 } else if (d3.utcMinute(date) < date) {
905 return format_second(date);
906 } else {
907 return format_minute(date);
908 }
909 } else if (Math.floor(diff / (div *= 60)) === 0) {
910 //diff is less than a minute
911 if (d3.utcMinute(date) < date) {
912 return format_second(date);
913 } else {
914 return format_minute(date);
915 }
916 } else if (Math.floor(diff / (div *= 60)) === 0) {
917 // diff is less than an hour
918 if (d3.utcHour(date) < date) {
919 return format_minute(date);
920 } else {
921 return format_hour(date);
922 }
923 } else if (Math.floor(diff / (div *= 24)) === 0) {
924 //diff is less than a day
925 if (d3.utcDay(date) < date) {
926 return format_hour(date);
927 } else {
928 return format_day(date);
929 }
930 } else if (Math.floor(diff / (div *= 27)) === 0) {
931 //diff is less than a month
932 if (d3.utcMonth(date) < date) {
933 return format_day(date);
934 } else {
935 return format_month(date);
936 }
937 } else if (Math.floor(diff / (div *= 12)) === 0) {
938 //diff is less than a year
939 if (d3.utcMonth(date) < date) {
940 return format_day(date);
941 } else {
942 return format_month(date);
943 }
944 } else {
945 //diff is more than a year
946 if (d3.utcMonth(date) < date) {
947 return format_day(date);
948 } else if (d3.utcYear(date) < date) {
949 return format_month(date);
950 } else {
951 return format_year(date);
952 }
953 }
954 };
955 }
956
957 log_sc_format(ticks?: any[]) {
958 return this.get_format_func(this._log_sc_precision(ticks));
959 }
960
961 _log_sc_precision(ticks?: any[]): number {
962 if (!isLogScale(this.axis_scale)) {
963 return -1;
964 }
965 ticks =
966 ticks === undefined || ticks === null
967 ? this.axis_scale.scale.ticks()
968 : ticks;
969 const ratio = Math.abs(Math.log10(ticks[1] / ticks[0]));
970
971 if (ratio >= 0.301) {
972 //format them as they are with the max_length of 6
973 return -1;
974 } else {
975 //return a default of 3 digits of precision
976 return 3;
977 }
978 }
979
980 guess_tick_format(ticks?: any[]) {
981 if (isDateScale(this.axis_scale) || isDateColorScale(this.axis_scale)) {
982 return this.date_sc_format(ticks);
983 } else if (
984 isLinearScale(this.axis_scale) ||
985 isColorScale(this.axis_scale)
986 ) {
987 return this.linear_sc_format(ticks);
988 } else if (isLogScale(this.axis_scale)) {
989 return this.log_sc_format(ticks);
990 }
991 }
992
993 get width(): number {
994 return (
995 this.parent.width - this.parent.margin.right - this.parent.margin.left
996 );
997 }
998
999 get height(): number {
1000 return (
1001 this.parent.height - this.parent.margin.top - this.parent.margin.bottom
1002 );
1003 }
1004
1005 get margin() {
1006 return this.parent.margin;
1007 }
1008
1009 axis_scale: Scale;
1010 axis: d3.Axis<d3.AxisDomain>;
1011 d3el: d3.Selection<HTMLElement, any, any, any>;
1012 g_axisline: d3.Selection<SVGGElement, any, any, any>;
1013 label_offset: string;
1014 offset_scale: Scale;
1015 offset_value: any;
1016 parent: Figure;
1017 tick_format: (d: number) => string;
1018 vertical: boolean;
1019 }