-
Notifications
You must be signed in to change notification settings - Fork 11.9k
/
core.scale.js
1710 lines (1503 loc) · 48.4 KB
/
core.scale.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import Element from './core.element.js';
import {_alignPixel, _measureText, renderText, clipArea, unclipArea} from '../helpers/helpers.canvas.js';
import {callback as call, each, finiteOrDefault, isArray, isFinite, isNullOrUndef, isObject, valueOrDefault} from '../helpers/helpers.core.js';
import {toDegrees, toRadians, _int16Range, _limitValue, HALF_PI} from '../helpers/helpers.math.js';
import {_alignStartEnd, _toLeftRightCenter} from '../helpers/helpers.extras.js';
import {createContext, toFont, toPadding, _addGrace} from '../helpers/helpers.options.js';
import {autoSkip} from './core.scale.autoskip.js';
const reverseAlign = (align) => align === 'left' ? 'right' : align === 'right' ? 'left' : align;
const offsetFromEdge = (scale, edge, offset) => edge === 'top' || edge === 'left' ? scale[edge] + offset : scale[edge] - offset;
const getTicksLimit = (ticksLength, maxTicksLimit) => Math.min(maxTicksLimit || ticksLength, ticksLength);
/**
* @typedef { import('../types/index.js').Chart } Chart
* @typedef {{value:number | string, label?:string, major?:boolean, $context?:any}} Tick
*/
/**
* Returns a new array containing numItems from arr
* @param {any[]} arr
* @param {number} numItems
*/
function sample(arr, numItems) {
const result = [];
const increment = arr.length / numItems;
const len = arr.length;
let i = 0;
for (; i < len; i += increment) {
result.push(arr[Math.floor(i)]);
}
return result;
}
/**
* @param {Scale} scale
* @param {number} index
* @param {boolean} offsetGridLines
*/
function getPixelForGridLine(scale, index, offsetGridLines) {
const length = scale.ticks.length;
const validIndex = Math.min(index, length - 1);
const start = scale._startPixel;
const end = scale._endPixel;
const epsilon = 1e-6; // 1e-6 is margin in pixels for accumulated error.
let lineValue = scale.getPixelForTick(validIndex);
let offset;
if (offsetGridLines) {
if (length === 1) {
offset = Math.max(lineValue - start, end - lineValue);
} else if (index === 0) {
offset = (scale.getPixelForTick(1) - lineValue) / 2;
} else {
offset = (lineValue - scale.getPixelForTick(validIndex - 1)) / 2;
}
lineValue += validIndex < index ? offset : -offset;
// Return undefined if the pixel is out of the range
if (lineValue < start - epsilon || lineValue > end + epsilon) {
return;
}
}
return lineValue;
}
/**
* @param {object} caches
* @param {number} length
*/
function garbageCollect(caches, length) {
each(caches, (cache) => {
const gc = cache.gc;
const gcLen = gc.length / 2;
let i;
if (gcLen > length) {
for (i = 0; i < gcLen; ++i) {
delete cache.data[gc[i]];
}
gc.splice(0, gcLen);
}
});
}
/**
* @param {object} options
*/
function getTickMarkLength(options) {
return options.drawTicks ? options.tickLength : 0;
}
/**
* @param {object} options
*/
function getTitleHeight(options, fallback) {
if (!options.display) {
return 0;
}
const font = toFont(options.font, fallback);
const padding = toPadding(options.padding);
const lines = isArray(options.text) ? options.text.length : 1;
return (lines * font.lineHeight) + padding.height;
}
function createScaleContext(parent, scale) {
return createContext(parent, {
scale,
type: 'scale'
});
}
function createTickContext(parent, index, tick) {
return createContext(parent, {
tick,
index,
type: 'tick'
});
}
function titleAlign(align, position, reverse) {
/** @type {CanvasTextAlign} */
let ret = _toLeftRightCenter(align);
if ((reverse && position !== 'right') || (!reverse && position === 'right')) {
ret = reverseAlign(ret);
}
return ret;
}
function titleArgs(scale, offset, position, align) {
const {top, left, bottom, right, chart} = scale;
const {chartArea, scales} = chart;
let rotation = 0;
let maxWidth, titleX, titleY;
const height = bottom - top;
const width = right - left;
if (scale.isHorizontal()) {
titleX = _alignStartEnd(align, left, right);
if (isObject(position)) {
const positionAxisID = Object.keys(position)[0];
const value = position[positionAxisID];
titleY = scales[positionAxisID].getPixelForValue(value) + height - offset;
} else if (position === 'center') {
titleY = (chartArea.bottom + chartArea.top) / 2 + height - offset;
} else {
titleY = offsetFromEdge(scale, position, offset);
}
maxWidth = right - left;
} else {
if (isObject(position)) {
const positionAxisID = Object.keys(position)[0];
const value = position[positionAxisID];
titleX = scales[positionAxisID].getPixelForValue(value) - width + offset;
} else if (position === 'center') {
titleX = (chartArea.left + chartArea.right) / 2 - width + offset;
} else {
titleX = offsetFromEdge(scale, position, offset);
}
titleY = _alignStartEnd(align, bottom, top);
rotation = position === 'left' ? -HALF_PI : HALF_PI;
}
return {titleX, titleY, maxWidth, rotation};
}
export default class Scale extends Element {
// eslint-disable-next-line max-statements
constructor(cfg) {
super();
/** @type {string} */
this.id = cfg.id;
/** @type {string} */
this.type = cfg.type;
/** @type {any} */
this.options = undefined;
/** @type {CanvasRenderingContext2D} */
this.ctx = cfg.ctx;
/** @type {Chart} */
this.chart = cfg.chart;
// implements box
/** @type {number} */
this.top = undefined;
/** @type {number} */
this.bottom = undefined;
/** @type {number} */
this.left = undefined;
/** @type {number} */
this.right = undefined;
/** @type {number} */
this.width = undefined;
/** @type {number} */
this.height = undefined;
this._margins = {
left: 0,
right: 0,
top: 0,
bottom: 0
};
/** @type {number} */
this.maxWidth = undefined;
/** @type {number} */
this.maxHeight = undefined;
/** @type {number} */
this.paddingTop = undefined;
/** @type {number} */
this.paddingBottom = undefined;
/** @type {number} */
this.paddingLeft = undefined;
/** @type {number} */
this.paddingRight = undefined;
// scale-specific properties
/** @type {string=} */
this.axis = undefined;
/** @type {number=} */
this.labelRotation = undefined;
this.min = undefined;
this.max = undefined;
this._range = undefined;
/** @type {Tick[]} */
this.ticks = [];
/** @type {object[]|null} */
this._gridLineItems = null;
/** @type {object[]|null} */
this._labelItems = null;
/** @type {object|null} */
this._labelSizes = null;
this._length = 0;
this._maxLength = 0;
this._longestTextCache = {};
/** @type {number} */
this._startPixel = undefined;
/** @type {number} */
this._endPixel = undefined;
this._reversePixels = false;
this._userMax = undefined;
this._userMin = undefined;
this._suggestedMax = undefined;
this._suggestedMin = undefined;
this._ticksLength = 0;
this._borderValue = 0;
this._cache = {};
this._dataLimitsCached = false;
this.$context = undefined;
}
/**
* @param {any} options
* @since 3.0
*/
init(options) {
this.options = options.setContext(this.getContext());
this.axis = options.axis;
// parse min/max value, so we can properly determine min/max for other scales
this._userMin = this.parse(options.min);
this._userMax = this.parse(options.max);
this._suggestedMin = this.parse(options.suggestedMin);
this._suggestedMax = this.parse(options.suggestedMax);
}
/**
* Parse a supported input value to internal representation.
* @param {*} raw
* @param {number} [index]
* @since 3.0
*/
parse(raw, index) { // eslint-disable-line no-unused-vars
return raw;
}
/**
* @return {{min: number, max: number, minDefined: boolean, maxDefined: boolean}}
* @protected
* @since 3.0
*/
getUserBounds() {
let {_userMin, _userMax, _suggestedMin, _suggestedMax} = this;
_userMin = finiteOrDefault(_userMin, Number.POSITIVE_INFINITY);
_userMax = finiteOrDefault(_userMax, Number.NEGATIVE_INFINITY);
_suggestedMin = finiteOrDefault(_suggestedMin, Number.POSITIVE_INFINITY);
_suggestedMax = finiteOrDefault(_suggestedMax, Number.NEGATIVE_INFINITY);
return {
min: finiteOrDefault(_userMin, _suggestedMin),
max: finiteOrDefault(_userMax, _suggestedMax),
minDefined: isFinite(_userMin),
maxDefined: isFinite(_userMax)
};
}
/**
* @param {boolean} canStack
* @return {{min: number, max: number}}
* @protected
* @since 3.0
*/
getMinMax(canStack) {
let {min, max, minDefined, maxDefined} = this.getUserBounds();
let range;
if (minDefined && maxDefined) {
return {min, max};
}
const metas = this.getMatchingVisibleMetas();
for (let i = 0, ilen = metas.length; i < ilen; ++i) {
range = metas[i].controller.getMinMax(this, canStack);
if (!minDefined) {
min = Math.min(min, range.min);
}
if (!maxDefined) {
max = Math.max(max, range.max);
}
}
// Make sure min <= max when only min or max is defined by user and the data is outside that range
min = maxDefined && min > max ? max : min;
max = minDefined && min > max ? min : max;
return {
min: finiteOrDefault(min, finiteOrDefault(max, min)),
max: finiteOrDefault(max, finiteOrDefault(min, max))
};
}
/**
* Get the padding needed for the scale
* @return {{top: number, left: number, bottom: number, right: number}} the necessary padding
* @private
*/
getPadding() {
return {
left: this.paddingLeft || 0,
top: this.paddingTop || 0,
right: this.paddingRight || 0,
bottom: this.paddingBottom || 0
};
}
/**
* Returns the scale tick objects
* @return {Tick[]}
* @since 2.7
*/
getTicks() {
return this.ticks;
}
/**
* @return {string[]}
*/
getLabels() {
const data = this.chart.data;
return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels || [];
}
/**
* @return {import('../types.js').LabelItem[]}
*/
getLabelItems(chartArea = this.chart.chartArea) {
const items = this._labelItems || (this._labelItems = this._computeLabelItems(chartArea));
return items;
}
// When a new layout is created, reset the data limits cache
beforeLayout() {
this._cache = {};
this._dataLimitsCached = false;
}
// These methods are ordered by lifecycle. Utilities then follow.
// Any function defined here is inherited by all scale types.
// Any function can be extended by the scale type
beforeUpdate() {
call(this.options.beforeUpdate, [this]);
}
/**
* @param {number} maxWidth - the max width in pixels
* @param {number} maxHeight - the max height in pixels
* @param {{top: number, left: number, bottom: number, right: number}} margins - the space between the edge of the other scales and edge of the chart
* This space comes from two sources:
* - padding - space that's required to show the labels at the edges of the scale
* - thickness of scales or legends in another orientation
*/
update(maxWidth, maxHeight, margins) {
const {beginAtZero, grace, ticks: tickOpts} = this.options;
const sampleSize = tickOpts.sampleSize;
// Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
this.beforeUpdate();
// Absorb the master measurements
this.maxWidth = maxWidth;
this.maxHeight = maxHeight;
this._margins = margins = Object.assign({
left: 0,
right: 0,
top: 0,
bottom: 0
}, margins);
this.ticks = null;
this._labelSizes = null;
this._gridLineItems = null;
this._labelItems = null;
// Dimensions
this.beforeSetDimensions();
this.setDimensions();
this.afterSetDimensions();
this._maxLength = this.isHorizontal()
? this.width + margins.left + margins.right
: this.height + margins.top + margins.bottom;
// Data min/max
if (!this._dataLimitsCached) {
this.beforeDataLimits();
this.determineDataLimits();
this.afterDataLimits();
this._range = _addGrace(this, grace, beginAtZero);
this._dataLimitsCached = true;
}
this.beforeBuildTicks();
this.ticks = this.buildTicks() || [];
// Allow modification of ticks in callback.
this.afterBuildTicks();
// Compute tick rotation and fit using a sampled subset of labels
// We generally don't need to compute the size of every single label for determining scale size
const samplingEnabled = sampleSize < this.ticks.length;
this._convertTicksToLabels(samplingEnabled ? sample(this.ticks, sampleSize) : this.ticks);
// configure is called twice, once here, once from core.controller.updateLayout.
// Here we haven't been positioned yet, but dimensions are correct.
// Variables set in configure are needed for calculateLabelRotation, and
// it's ok that coordinates are not correct there, only dimensions matter.
this.configure();
// Tick Rotation
this.beforeCalculateLabelRotation();
this.calculateLabelRotation(); // Preconditions: number of ticks and sizes of largest labels must be calculated beforehand
this.afterCalculateLabelRotation();
// Auto-skip
if (tickOpts.display && (tickOpts.autoSkip || tickOpts.source === 'auto')) {
this.ticks = autoSkip(this, this.ticks);
this._labelSizes = null;
this.afterAutoSkip();
}
if (samplingEnabled) {
// Generate labels using all non-skipped ticks
this._convertTicksToLabels(this.ticks);
}
this.beforeFit();
this.fit(); // Preconditions: label rotation and label sizes must be calculated beforehand
this.afterFit();
// IMPORTANT: after this point, we consider that `this.ticks` will NEVER change!
this.afterUpdate();
}
/**
* @protected
*/
configure() {
let reversePixels = this.options.reverse;
let startPixel, endPixel;
if (this.isHorizontal()) {
startPixel = this.left;
endPixel = this.right;
} else {
startPixel = this.top;
endPixel = this.bottom;
// by default vertical scales are from bottom to top, so pixels are reversed
reversePixels = !reversePixels;
}
this._startPixel = startPixel;
this._endPixel = endPixel;
this._reversePixels = reversePixels;
this._length = endPixel - startPixel;
this._alignToPixels = this.options.alignToPixels;
}
afterUpdate() {
call(this.options.afterUpdate, [this]);
}
//
beforeSetDimensions() {
call(this.options.beforeSetDimensions, [this]);
}
setDimensions() {
// Set the unconstrained dimension before label rotation
if (this.isHorizontal()) {
// Reset position before calculating rotation
this.width = this.maxWidth;
this.left = 0;
this.right = this.width;
} else {
this.height = this.maxHeight;
// Reset position before calculating rotation
this.top = 0;
this.bottom = this.height;
}
// Reset padding
this.paddingLeft = 0;
this.paddingTop = 0;
this.paddingRight = 0;
this.paddingBottom = 0;
}
afterSetDimensions() {
call(this.options.afterSetDimensions, [this]);
}
_callHooks(name) {
this.chart.notifyPlugins(name, this.getContext());
call(this.options[name], [this]);
}
// Data limits
beforeDataLimits() {
this._callHooks('beforeDataLimits');
}
determineDataLimits() {}
afterDataLimits() {
this._callHooks('afterDataLimits');
}
//
beforeBuildTicks() {
this._callHooks('beforeBuildTicks');
}
/**
* @return {object[]} the ticks
*/
buildTicks() {
return [];
}
afterBuildTicks() {
this._callHooks('afterBuildTicks');
}
beforeTickToLabelConversion() {
call(this.options.beforeTickToLabelConversion, [this]);
}
/**
* Convert ticks to label strings
* @param {Tick[]} ticks
*/
generateTickLabels(ticks) {
const tickOpts = this.options.ticks;
let i, ilen, tick;
for (i = 0, ilen = ticks.length; i < ilen; i++) {
tick = ticks[i];
tick.label = call(tickOpts.callback, [tick.value, i, ticks], this);
}
}
afterTickToLabelConversion() {
call(this.options.afterTickToLabelConversion, [this]);
}
//
beforeCalculateLabelRotation() {
call(this.options.beforeCalculateLabelRotation, [this]);
}
calculateLabelRotation() {
const options = this.options;
const tickOpts = options.ticks;
const numTicks = getTicksLimit(this.ticks.length, options.ticks.maxTicksLimit);
const minRotation = tickOpts.minRotation || 0;
const maxRotation = tickOpts.maxRotation;
let labelRotation = minRotation;
let tickWidth, maxHeight, maxLabelDiagonal;
if (!this._isVisible() || !tickOpts.display || minRotation >= maxRotation || numTicks <= 1 || !this.isHorizontal()) {
this.labelRotation = minRotation;
return;
}
const labelSizes = this._getLabelSizes();
const maxLabelWidth = labelSizes.widest.width;
const maxLabelHeight = labelSizes.highest.height;
// Estimate the width of each grid based on the canvas width, the maximum
// label width and the number of tick intervals
const maxWidth = _limitValue(this.chart.width - maxLabelWidth, 0, this.maxWidth);
tickWidth = options.offset ? this.maxWidth / numTicks : maxWidth / (numTicks - 1);
// Allow 3 pixels x2 padding either side for label readability
if (maxLabelWidth + 6 > tickWidth) {
tickWidth = maxWidth / (numTicks - (options.offset ? 0.5 : 1));
maxHeight = this.maxHeight - getTickMarkLength(options.grid)
- tickOpts.padding - getTitleHeight(options.title, this.chart.options.font);
maxLabelDiagonal = Math.sqrt(maxLabelWidth * maxLabelWidth + maxLabelHeight * maxLabelHeight);
labelRotation = toDegrees(Math.min(
Math.asin(_limitValue((labelSizes.highest.height + 6) / tickWidth, -1, 1)),
Math.asin(_limitValue(maxHeight / maxLabelDiagonal, -1, 1)) - Math.asin(_limitValue(maxLabelHeight / maxLabelDiagonal, -1, 1))
));
labelRotation = Math.max(minRotation, Math.min(maxRotation, labelRotation));
}
this.labelRotation = labelRotation;
}
afterCalculateLabelRotation() {
call(this.options.afterCalculateLabelRotation, [this]);
}
afterAutoSkip() {}
//
beforeFit() {
call(this.options.beforeFit, [this]);
}
fit() {
// Reset
const minSize = {
width: 0,
height: 0
};
const {chart, options: {ticks: tickOpts, title: titleOpts, grid: gridOpts}} = this;
const display = this._isVisible();
const isHorizontal = this.isHorizontal();
if (display) {
const titleHeight = getTitleHeight(titleOpts, chart.options.font);
if (isHorizontal) {
minSize.width = this.maxWidth;
minSize.height = getTickMarkLength(gridOpts) + titleHeight;
} else {
minSize.height = this.maxHeight; // fill all the height
minSize.width = getTickMarkLength(gridOpts) + titleHeight;
}
// Don't bother fitting the ticks if we are not showing the labels
if (tickOpts.display && this.ticks.length) {
const {first, last, widest, highest} = this._getLabelSizes();
const tickPadding = tickOpts.padding * 2;
const angleRadians = toRadians(this.labelRotation);
const cos = Math.cos(angleRadians);
const sin = Math.sin(angleRadians);
if (isHorizontal) {
// A horizontal axis is more constrained by the height.
const labelHeight = tickOpts.mirror ? 0 : sin * widest.width + cos * highest.height;
minSize.height = Math.min(this.maxHeight, minSize.height + labelHeight + tickPadding);
} else {
// A vertical axis is more constrained by the width. Labels are the
// dominant factor here, so get that length first and account for padding
const labelWidth = tickOpts.mirror ? 0 : cos * widest.width + sin * highest.height;
minSize.width = Math.min(this.maxWidth, minSize.width + labelWidth + tickPadding);
}
this._calculatePadding(first, last, sin, cos);
}
}
this._handleMargins();
if (isHorizontal) {
this.width = this._length = chart.width - this._margins.left - this._margins.right;
this.height = minSize.height;
} else {
this.width = minSize.width;
this.height = this._length = chart.height - this._margins.top - this._margins.bottom;
}
}
_calculatePadding(first, last, sin, cos) {
const {ticks: {align, padding}, position} = this.options;
const isRotated = this.labelRotation !== 0;
const labelsBelowTicks = position !== 'top' && this.axis === 'x';
if (this.isHorizontal()) {
const offsetLeft = this.getPixelForTick(0) - this.left;
const offsetRight = this.right - this.getPixelForTick(this.ticks.length - 1);
let paddingLeft = 0;
let paddingRight = 0;
// Ensure that our ticks are always inside the canvas. When rotated, ticks are right aligned
// which means that the right padding is dominated by the font height
if (isRotated) {
if (labelsBelowTicks) {
paddingLeft = cos * first.width;
paddingRight = sin * last.height;
} else {
paddingLeft = sin * first.height;
paddingRight = cos * last.width;
}
} else if (align === 'start') {
paddingRight = last.width;
} else if (align === 'end') {
paddingLeft = first.width;
} else if (align !== 'inner') {
paddingLeft = first.width / 2;
paddingRight = last.width / 2;
}
// Adjust padding taking into account changes in offsets
this.paddingLeft = Math.max((paddingLeft - offsetLeft + padding) * this.width / (this.width - offsetLeft), 0);
this.paddingRight = Math.max((paddingRight - offsetRight + padding) * this.width / (this.width - offsetRight), 0);
} else {
let paddingTop = last.height / 2;
let paddingBottom = first.height / 2;
if (align === 'start') {
paddingTop = 0;
paddingBottom = first.height;
} else if (align === 'end') {
paddingTop = last.height;
paddingBottom = 0;
}
this.paddingTop = paddingTop + padding;
this.paddingBottom = paddingBottom + padding;
}
}
/**
* Handle margins and padding interactions
* @private
*/
_handleMargins() {
if (this._margins) {
this._margins.left = Math.max(this.paddingLeft, this._margins.left);
this._margins.top = Math.max(this.paddingTop, this._margins.top);
this._margins.right = Math.max(this.paddingRight, this._margins.right);
this._margins.bottom = Math.max(this.paddingBottom, this._margins.bottom);
}
}
afterFit() {
call(this.options.afterFit, [this]);
}
// Shared Methods
/**
* @return {boolean}
*/
isHorizontal() {
const {axis, position} = this.options;
return position === 'top' || position === 'bottom' || axis === 'x';
}
/**
* @return {boolean}
*/
isFullSize() {
return this.options.fullSize;
}
/**
* @param {Tick[]} ticks
* @private
*/
_convertTicksToLabels(ticks) {
this.beforeTickToLabelConversion();
this.generateTickLabels(ticks);
// Ticks should be skipped when callback returns null or undef, so lets remove those.
let i, ilen;
for (i = 0, ilen = ticks.length; i < ilen; i++) {
if (isNullOrUndef(ticks[i].label)) {
ticks.splice(i, 1);
ilen--;
i--;
}
}
this.afterTickToLabelConversion();
}
/**
* @return {{ first: object, last: object, widest: object, highest: object, widths: Array, heights: array }}
* @private
*/
_getLabelSizes() {
let labelSizes = this._labelSizes;
if (!labelSizes) {
const sampleSize = this.options.ticks.sampleSize;
let ticks = this.ticks;
if (sampleSize < ticks.length) {
ticks = sample(ticks, sampleSize);
}
this._labelSizes = labelSizes = this._computeLabelSizes(ticks, ticks.length, this.options.ticks.maxTicksLimit);
}
return labelSizes;
}
/**
* Returns {width, height, offset} objects for the first, last, widest, highest tick
* labels where offset indicates the anchor point offset from the top in pixels.
* @return {{ first: object, last: object, widest: object, highest: object, widths: Array, heights: array }}
* @private
*/
_computeLabelSizes(ticks, length, maxTicksLimit) {
const {ctx, _longestTextCache: caches} = this;
const widths = [];
const heights = [];
const increment = Math.floor(length / getTicksLimit(length, maxTicksLimit));
let widestLabelSize = 0;
let highestLabelSize = 0;
let i, j, jlen, label, tickFont, fontString, cache, lineHeight, width, height, nestedLabel;
for (i = 0; i < length; i += increment) {
label = ticks[i].label;
tickFont = this._resolveTickFontOptions(i);
ctx.font = fontString = tickFont.string;
cache = caches[fontString] = caches[fontString] || {data: {}, gc: []};
lineHeight = tickFont.lineHeight;
width = height = 0;
// Undefined labels and arrays should not be measured
if (!isNullOrUndef(label) && !isArray(label)) {
width = _measureText(ctx, cache.data, cache.gc, width, label);
height = lineHeight;
} else if (isArray(label)) {
// if it is an array let's measure each element
for (j = 0, jlen = label.length; j < jlen; ++j) {
nestedLabel = /** @type {string} */ (label[j]);
// Undefined labels and arrays should not be measured
if (!isNullOrUndef(nestedLabel) && !isArray(nestedLabel)) {
width = _measureText(ctx, cache.data, cache.gc, width, nestedLabel);
height += lineHeight;
}
}
}
widths.push(width);
heights.push(height);
widestLabelSize = Math.max(width, widestLabelSize);
highestLabelSize = Math.max(height, highestLabelSize);
}
garbageCollect(caches, length);
const widest = widths.indexOf(widestLabelSize);
const highest = heights.indexOf(highestLabelSize);
const valueAt = (idx) => ({width: widths[idx] || 0, height: heights[idx] || 0});
return {
first: valueAt(0),
last: valueAt(length - 1),
widest: valueAt(widest),
highest: valueAt(highest),
widths,
heights,
};
}
/**
* Used to get the label to display in the tooltip for the given value
* @param {*} value
* @return {string}
*/
getLabelForValue(value) {
return value;
}
/**
* Returns the location of the given data point. Value can either be an index or a numerical value
* The coordinate (0, 0) is at the upper-left corner of the canvas
* @param {*} value
* @param {number} [index]
* @return {number}
*/
getPixelForValue(value, index) { // eslint-disable-line no-unused-vars
return NaN;
}
/**
* Used to get the data value from a given pixel. This is the inverse of getPixelForValue
* The coordinate (0, 0) is at the upper-left corner of the canvas
* @param {number} pixel
* @return {*}
*/
getValueForPixel(pixel) {} // eslint-disable-line no-unused-vars
/**
* Returns the location of the tick at the given index
* The coordinate (0, 0) is at the upper-left corner of the canvas
* @param {number} index
* @return {number}
*/
getPixelForTick(index) {
const ticks = this.ticks;
if (index < 0 || index > ticks.length - 1) {
return null;
}
return this.getPixelForValue(ticks[index].value);
}
/**
* Utility for getting the pixel location of a percentage of scale
* The coordinate (0, 0) is at the upper-left corner of the canvas
* @param {number} decimal
* @return {number}
*/
getPixelForDecimal(decimal) {
if (this._reversePixels) {
decimal = 1 - decimal;
}
const pixel = this._startPixel + decimal * this._length;
return _int16Range(this._alignToPixels ? _alignPixel(this.chart, pixel, 0) : pixel);
}
/**
* @param {number} pixel
* @return {number}
*/
getDecimalForPixel(pixel) {
const decimal = (pixel - this._startPixel) / this._length;
return this._reversePixels ? 1 - decimal : decimal;
}
/**
* Returns the pixel for the minimum chart value
* The coordinate (0, 0) is at the upper-left corner of the canvas
* @return {number}
*/
getBasePixel() {
return this.getPixelForValue(this.getBaseValue());
}
/**
* @return {number}
*/
getBaseValue() {
const {min, max} = this;
return min < 0 && max < 0 ? max :
min > 0 && max > 0 ? min :
0;
}
/**
* @protected
*/
getContext(index) {
const ticks = this.ticks || [];
if (index >= 0 && index < ticks.length) {
const tick = ticks[index];
return tick.$context ||
(tick.$context = createTickContext(this.getContext(), index, tick));
}
return this.$context ||
(this.$context = createScaleContext(this.chart.getContext(), this));
}
/**
* @return {number}
* @private
*/
_tickSize() {
const optionTicks = this.options.ticks;
// Calculate space needed by label in axis direction.
const rot = toRadians(this.labelRotation);
const cos = Math.abs(Math.cos(rot));
const sin = Math.abs(Math.sin(rot));
const labelSizes = this._getLabelSizes();
const padding = optionTicks.autoSkipPadding || 0;
const w = labelSizes ? labelSizes.widest.width + padding : 0;
const h = labelSizes ? labelSizes.highest.height + padding : 0;
// Calculate space needed for 1 tick in axis direction.
return this.isHorizontal()
? h * cos > w * sin ? w / cos : h / sin
: h * sin < w * cos ? h / cos : w / sin;
}
/**
* @return {boolean}
* @private
*/
_isVisible() {