-
Notifications
You must be signed in to change notification settings - Fork 11.9k
/
core.scale.js
1441 lines (1249 loc) · 38.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
'use strict';
const defaults = require('./core.defaults');
const Element = require('./core.element');
const helpers = require('../helpers/index');
const Ticks = require('./core.ticks');
const alignPixel = helpers.canvas._alignPixel;
const isArray = helpers.isArray;
const isFinite = helpers.isFinite;
const isNullOrUndef = helpers.isNullOrUndef;
const valueOrDefault = helpers.valueOrDefault;
const resolve = helpers.options.resolve;
defaults._set('scale', {
display: true,
offset: false,
reverse: false,
beginAtZero: false,
// grid line settings
gridLines: {
display: true,
color: 'rgba(0,0,0,0.1)',
lineWidth: 1,
drawBorder: true,
drawOnChartArea: true,
drawTicks: true,
tickMarkLength: 10,
offsetGridLines: false,
borderDash: [],
borderDashOffset: 0.0
},
// scale label
scaleLabel: {
// display property
display: false,
// actual label
labelString: '',
// top/bottom padding
padding: {
top: 4,
bottom: 4
}
},
// label settings
ticks: {
minRotation: 0,
maxRotation: 50,
mirror: false,
padding: 0,
display: true,
autoSkip: true,
autoSkipPadding: 0,
labelOffset: 0,
// We pass through arrays to be rendered as multiline labels, we convert Others to strings here.
callback: Ticks.formatters.values,
minor: {},
major: {}
}
});
/** Returns a new array containing numItems from arr */
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;
}
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;
}
function garbageCollect(caches, length) {
helpers.each(caches, function(cache) {
var gc = cache.gc;
var gcLen = gc.length / 2;
var i;
if (gcLen > length) {
for (i = 0; i < gcLen; ++i) {
delete cache.data[gc[i]];
}
gc.splice(0, gcLen);
}
});
}
function getTickMarkLength(options) {
return options.drawTicks ? options.tickMarkLength : 0;
}
function getScaleLabelHeight(options) {
if (!options.display) {
return 0;
}
const font = helpers.options._parseFont(options);
const padding = helpers.options.toPadding(options.padding);
return font.lineHeight + padding.height;
}
function parseFontOptions(options, nestedOpts) {
return helpers.extend(helpers.options._parseFont({
fontFamily: valueOrDefault(nestedOpts.fontFamily, options.fontFamily),
fontSize: valueOrDefault(nestedOpts.fontSize, options.fontSize),
fontStyle: valueOrDefault(nestedOpts.fontStyle, options.fontStyle),
lineHeight: valueOrDefault(nestedOpts.lineHeight, options.lineHeight)
}), {
color: resolve([nestedOpts.fontColor, options.fontColor, defaults.fontColor])
});
}
function parseTickFontOptions(options) {
const minor = parseFontOptions(options, options.minor);
const major = options.major.enabled ? parseFontOptions(options, options.major) : minor;
return {minor, major};
}
function getEvenSpacing(arr) {
const len = arr.length;
let i, diff;
if (len < 2) {
return false;
}
for (diff = arr[0], i = 1; i < len; ++i) {
if (arr[i] - arr[i - 1] !== diff) {
return false;
}
}
return diff;
}
function calculateSpacing(majorIndices, ticks, axisLength, ticksLimit) {
const evenMajorSpacing = getEvenSpacing(majorIndices);
const spacing = ticks.length / ticksLimit;
let factors, factor, i, ilen;
// If the major ticks are evenly spaced apart, place the minor ticks
// so that they divide the major ticks into even chunks
if (!evenMajorSpacing) {
return Math.max(spacing, 1);
}
factors = helpers.math._factorize(evenMajorSpacing);
for (i = 0, ilen = factors.length - 1; i < ilen; i++) {
factor = factors[i];
if (factor > spacing) {
return factor;
}
}
return Math.max(spacing, 1);
}
function getMajorIndices(ticks) {
const result = [];
let i, ilen;
for (i = 0, ilen = ticks.length; i < ilen; i++) {
if (ticks[i].major) {
result.push(i);
}
}
return result;
}
function skipMajors(ticks, newTicks, majorIndices, spacing) {
let count = 0;
let next = majorIndices[0];
let i;
spacing = Math.ceil(spacing);
for (i = 0; i < ticks.length; i++) {
if (i === next) {
newTicks.push(ticks[i]);
count++;
next = majorIndices[count * spacing];
}
}
}
function skip(ticks, newTicks, spacing, majorStart, majorEnd) {
const start = valueOrDefault(majorStart, 0);
const end = Math.min(valueOrDefault(majorEnd, ticks.length), ticks.length);
let count = 0;
let length, i, next;
spacing = Math.ceil(spacing);
if (majorEnd) {
length = majorEnd - majorStart;
spacing = length / Math.floor(length / spacing);
}
next = start;
while (next < 0) {
count++;
next = Math.round(start + count * spacing);
}
for (i = Math.max(start, 0); i < end; i++) {
if (i === next) {
newTicks.push(ticks[i]);
count++;
next = Math.round(start + count * spacing);
}
}
}
class Scale extends Element {
/**
* Parse a supported input value to internal representation.
* @param {*} raw
* @param {number} index
* @private
* @since 3.0
*/
_parse(raw, index) { // eslint-disable-line no-unused-vars
return raw;
}
/**
* Parse an object for axis to internal representation.
* @param {object} obj
* @param {string} axis
* @param {number} index
* @private
* @since 3.0
*/
_parseObject(obj, axis, index) {
if (obj[axis] !== undefined) {
return this._parse(obj[axis], index);
}
return null;
}
/**
* @private
* @since 3.0
*/
_getUserBounds() {
let min = this._userMin;
let max = this._userMax;
if (isNullOrUndef(min) || isNaN(min)) {
min = Number.POSITIVE_INFINITY;
}
if (isNullOrUndef(max) || isNaN(max)) {
max = Number.NEGATIVE_INFINITY;
}
return {min, max, minDefined: isFinite(min), maxDefined: isFinite(max)};
}
/**
* @private
* @since 3.0
*/
_getMinMax(canStack) {
const me = this;
let {min, max, minDefined, maxDefined} = me._getUserBounds();
let minPositive = Number.POSITIVE_INFINITY;
let i, ilen, metas, minmax;
if (minDefined && maxDefined) {
return {min, max};
}
metas = me._getMatchingVisibleMetas();
for (i = 0, ilen = metas.length; i < ilen; ++i) {
minmax = metas[i].controller._getMinMax(me, canStack);
if (!minDefined) {
min = Math.min(min, minmax.min);
}
if (!maxDefined) {
max = Math.max(max, minmax.max);
}
minPositive = Math.min(minPositive, minmax.minPositive);
}
return {min, max, minPositive};
}
_invalidateCaches() {}
/**
* Get the padding needed for the scale
* @method getPadding
* @private
* @returns {Padding} the necessary padding
*/
getPadding() {
const me = this;
return {
left: me.paddingLeft || 0,
top: me.paddingTop || 0,
right: me.paddingRight || 0,
bottom: me.paddingBottom || 0
};
}
/**
* Returns the scale tick objects ({label, major})
* @since 2.7
*/
getTicks() {
return this.ticks;
}
/**
* @private
*/
_getLabels() {
const data = this.chart.data;
return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels || [];
}
// These methods are ordered by lifecyle. Utilities then follow.
// Any function defined here is inherited by all scale types.
// Any function can be extended by the scale type
beforeUpdate() {
helpers.callback(this.options.beforeUpdate, [this]);
}
/**
* @param {number} maxWidth - the max width in pixels
* @param {number} maxHeight - the max height in pixels
* @param {object} 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 me = this;
const tickOpts = me.options.ticks;
const sampleSize = tickOpts.sampleSize;
let samplingEnabled;
// Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
me.beforeUpdate();
// Absorb the master measurements
// TODO: make maxWidth, maxHeight private
me.maxWidth = maxWidth;
me.maxHeight = maxHeight;
me.margins = helpers.extend({
left: 0,
right: 0,
top: 0,
bottom: 0
}, margins);
me.ticks = null;
me._labelSizes = null;
me._maxLabelLines = 0;
me._longestTextCache = me._longestTextCache || {};
me._gridLineItems = null;
me._labelItems = null;
// Dimensions
me.beforeSetDimensions();
me.setDimensions();
me.afterSetDimensions();
// Data min/max
me.beforeDataLimits();
me.determineDataLimits();
me.afterDataLimits();
me.beforeBuildTicks();
me.ticks = me.buildTicks() || [];
// Allow modification of ticks in callback.
me.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
samplingEnabled = sampleSize < me.ticks.length;
me._convertTicksToLabels(samplingEnabled ? sample(me.ticks, sampleSize) : me.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.
me._configure();
// Tick Rotation
me.beforeCalculateLabelRotation();
me.calculateLabelRotation(); // Preconditions: number of ticks and sizes of largest labels must be calculated beforehand
me.afterCalculateLabelRotation();
me.beforeFit();
me.fit(); // Preconditions: label rotation and label sizes must be calculated beforehand
me.afterFit();
// Auto-skip
me.ticks = tickOpts.display && (tickOpts.autoSkip || tickOpts.source === 'auto') ? me._autoSkip(me.ticks) : me.ticks;
if (samplingEnabled) {
// Generate labels using all non-skipped ticks
me._convertTicksToLabels(me.ticks);
}
// IMPORTANT: after this point, we consider that `this.ticks` will NEVER change!
me.afterUpdate();
}
/**
* @private
*/
_configure() {
const me = this;
let reversePixels = me.options.reverse;
let startPixel, endPixel;
if (me.isHorizontal()) {
startPixel = me.left;
endPixel = me.right;
} else {
startPixel = me.top;
endPixel = me.bottom;
// by default vertical scales are from bottom to top, so pixels are reversed
reversePixels = !reversePixels;
}
me._startPixel = startPixel;
me._endPixel = endPixel;
me._reversePixels = reversePixels;
me._length = endPixel - startPixel;
}
afterUpdate() {
helpers.callback(this.options.afterUpdate, [this]);
}
//
beforeSetDimensions() {
helpers.callback(this.options.beforeSetDimensions, [this]);
}
setDimensions() {
const me = this;
// Set the unconstrained dimension before label rotation
if (me.isHorizontal()) {
// Reset position before calculating rotation
me.width = me.maxWidth;
me.left = 0;
me.right = me.width;
} else {
me.height = me.maxHeight;
// Reset position before calculating rotation
me.top = 0;
me.bottom = me.height;
}
// Reset padding
me.paddingLeft = 0;
me.paddingTop = 0;
me.paddingRight = 0;
me.paddingBottom = 0;
}
afterSetDimensions() {
helpers.callback(this.options.afterSetDimensions, [this]);
}
// Data limits
beforeDataLimits() {
helpers.callback(this.options.beforeDataLimits, [this]);
}
determineDataLimits() {}
afterDataLimits() {
helpers.callback(this.options.afterDataLimits, [this]);
}
//
beforeBuildTicks() {
helpers.callback(this.options.beforeBuildTicks, [this]);
}
buildTicks() {}
afterBuildTicks() {
helpers.callback(this.options.afterBuildTicks, [this]);
}
beforeTickToLabelConversion() {
helpers.callback(this.options.beforeTickToLabelConversion, [this]);
}
/**
* Convert ticks to label strings
*/
generateTickLabels(ticks) {
const me = this;
const tickOpts = me.options.ticks;
let i, ilen, tick;
for (i = 0, ilen = ticks.length; i < ilen; i++) {
tick = ticks[i];
tick.label = helpers.callback(tickOpts.callback, [tick.value, i, ticks], me);
}
}
afterTickToLabelConversion() {
helpers.callback(this.options.afterTickToLabelConversion, [this]);
}
//
beforeCalculateLabelRotation() {
helpers.callback(this.options.beforeCalculateLabelRotation, [this]);
}
calculateLabelRotation() {
const me = this;
const options = me.options;
const tickOpts = options.ticks;
const numTicks = me.ticks.length;
const minRotation = tickOpts.minRotation || 0;
const maxRotation = tickOpts.maxRotation;
let labelRotation = minRotation;
let labelSizes, maxLabelWidth, maxLabelHeight, maxWidth, tickWidth, maxHeight, maxLabelDiagonal;
if (!me._isVisible() || !tickOpts.display || minRotation >= maxRotation || numTicks <= 1 || !me.isHorizontal()) {
me.labelRotation = minRotation;
return;
}
labelSizes = me._getLabelSizes();
maxLabelWidth = labelSizes.widest.width;
maxLabelHeight = labelSizes.highest.height - labelSizes.highest.offset;
// Estimate the width of each grid based on the canvas width, the maximum
// label width and the number of tick intervals
maxWidth = Math.min(me.maxWidth, me.chart.width - maxLabelWidth);
tickWidth = options.offset ? me.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 = me.maxHeight - getTickMarkLength(options.gridLines)
- tickOpts.padding - getScaleLabelHeight(options.scaleLabel);
maxLabelDiagonal = Math.sqrt(maxLabelWidth * maxLabelWidth + maxLabelHeight * maxLabelHeight);
labelRotation = helpers.math.toDegrees(Math.min(
Math.asin(Math.min((labelSizes.highest.height + 6) / tickWidth, 1)),
Math.asin(Math.min(maxHeight / maxLabelDiagonal, 1)) - Math.asin(maxLabelHeight / maxLabelDiagonal)
));
labelRotation = Math.max(minRotation, Math.min(maxRotation, labelRotation));
}
me.labelRotation = labelRotation;
}
afterCalculateLabelRotation() {
helpers.callback(this.options.afterCalculateLabelRotation, [this]);
}
//
beforeFit() {
helpers.callback(this.options.beforeFit, [this]);
}
fit() {
const me = this;
// Reset
const minSize = {
width: 0,
height: 0
};
const chart = me.chart;
const opts = me.options;
const tickOpts = opts.ticks;
const scaleLabelOpts = opts.scaleLabel;
const gridLineOpts = opts.gridLines;
const display = me._isVisible();
const labelsBelowTicks = opts.position !== 'top' && me.axis === 'x';
const isHorizontal = me.isHorizontal();
// Width
if (isHorizontal) {
minSize.width = me.maxWidth;
} else if (display) {
minSize.width = getTickMarkLength(gridLineOpts) + getScaleLabelHeight(scaleLabelOpts);
}
// height
if (!isHorizontal) {
minSize.height = me.maxHeight; // fill all the height
} else if (display) {
minSize.height = getTickMarkLength(gridLineOpts) + getScaleLabelHeight(scaleLabelOpts);
}
// Don't bother fitting the ticks if we are not showing the labels
if (tickOpts.display && display) {
const tickFonts = parseTickFontOptions(tickOpts);
const labelSizes = me._getLabelSizes();
const firstLabelSize = labelSizes.first;
const lastLabelSize = labelSizes.last;
const widestLabelSize = labelSizes.widest;
const highestLabelSize = labelSizes.highest;
const lineSpace = tickFonts.minor.lineHeight * 0.4;
const tickPadding = tickOpts.padding;
if (isHorizontal) {
// A horizontal axis is more constrained by the height.
const isRotated = me.labelRotation !== 0;
const angleRadians = helpers.math.toRadians(me.labelRotation);
const cosRotation = Math.cos(angleRadians);
const sinRotation = Math.sin(angleRadians);
const labelHeight = sinRotation * widestLabelSize.width
+ cosRotation * (highestLabelSize.height - (isRotated ? highestLabelSize.offset : 0))
+ (isRotated ? 0 : lineSpace); // padding
minSize.height = Math.min(me.maxHeight, minSize.height + labelHeight + tickPadding);
const offsetLeft = me.getPixelForTick(0) - me.left;
const offsetRight = me.right - me.getPixelForTick(me.ticks.length - 1);
let paddingLeft, paddingRight;
// 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) {
paddingLeft = labelsBelowTicks ?
cosRotation * firstLabelSize.width + sinRotation * firstLabelSize.offset :
sinRotation * (firstLabelSize.height - firstLabelSize.offset);
paddingRight = labelsBelowTicks ?
sinRotation * (lastLabelSize.height - lastLabelSize.offset) :
cosRotation * lastLabelSize.width + sinRotation * lastLabelSize.offset;
} else {
paddingLeft = firstLabelSize.width / 2;
paddingRight = lastLabelSize.width / 2;
}
// Adjust padding taking into account changes in offsets
// and add 3 px to move away from canvas edges
me.paddingLeft = Math.max((paddingLeft - offsetLeft) * me.width / (me.width - offsetLeft), 0) + 3;
me.paddingRight = Math.max((paddingRight - offsetRight) * me.width / (me.width - offsetRight), 0) + 3;
} 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
var labelWidth = tickOpts.mirror ? 0 :
// use lineSpace for consistency with horizontal axis
// tickPadding is not implemented for horizontal
widestLabelSize.width + tickPadding + lineSpace;
minSize.width = Math.min(me.maxWidth, minSize.width + labelWidth);
me.paddingTop = firstLabelSize.height / 2;
me.paddingBottom = lastLabelSize.height / 2;
}
}
me.handleMargins();
if (isHorizontal) {
me.width = me._length = chart.width - me.margins.left - me.margins.right;
me.height = minSize.height;
} else {
me.width = minSize.width;
me.height = me._length = chart.height - me.margins.top - me.margins.bottom;
}
}
/**
* Handle margins and padding interactions
* @private
*/
handleMargins() {
const me = this;
if (me.margins) {
me.margins.left = Math.max(me.paddingLeft, me.margins.left);
me.margins.top = Math.max(me.paddingTop, me.margins.top);
me.margins.right = Math.max(me.paddingRight, me.margins.right);
me.margins.bottom = Math.max(me.paddingBottom, me.margins.bottom);
}
}
afterFit() {
helpers.callback(this.options.afterFit, [this]);
}
// Shared Methods
isHorizontal() {
const {axis, position} = this.options;
return position === 'top' || position === 'bottom' || axis === 'x';
}
isFullWidth() {
return this.options.fullWidth;
}
_convertTicksToLabels(ticks) {
const me = this;
me.beforeTickToLabelConversion();
me.generateTickLabels(ticks);
me.afterTickToLabelConversion();
}
/**
* @private
*/
_getLabelSizes() {
const me = this;
let labelSizes = me._labelSizes;
if (!labelSizes) {
me._labelSizes = labelSizes = me._computeLabelSizes();
}
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.
* @private
*/
_computeLabelSizes() {
const me = this;
const ctx = me.ctx;
const tickFonts = parseTickFontOptions(me.options.ticks);
const caches = me._longestTextCache;
const sampleSize = me.options.ticks.sampleSize;
const widths = [];
const heights = [];
const offsets = [];
let ticks = me.ticks;
if (sampleSize < ticks.length) {
ticks = sample(ticks, sampleSize);
}
const length = ticks.length;
let i, j, jlen, label, tickFont, fontString, cache, lineHeight, width, height, nestedLabel, widest, highest;
for (i = 0; i < length; ++i) {
label = ticks[i].label;
tickFont = ticks[i].major ? tickFonts.major : tickFonts.minor;
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 = helpers.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 = label[j];
// Undefined labels and arrays should not be measured
if (!isNullOrUndef(nestedLabel) && !isArray(nestedLabel)) {
width = helpers.measureText(ctx, cache.data, cache.gc, width, nestedLabel);
height += lineHeight;
}
}
}
widths.push(width);
heights.push(height);
offsets.push(lineHeight / 2);
}
garbageCollect(caches, length);
widest = widths.indexOf(Math.max.apply(null, widths));
highest = heights.indexOf(Math.max.apply(null, heights));
function valueAt(idx) {
return {
width: widths[idx] || 0,
height: heights[idx] || 0,
offset: offsets[idx] || 0
};
}
return {
first: valueAt(0),
last: valueAt(length - 1),
widest: valueAt(widest),
highest: valueAt(highest)
};
}
/**
* Used to get the label to display in the tooltip for the given value
* @param value
*/
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 index
* @param datasetIndex
*/
getPixelForValue() {}
/**
* 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 pixel
*/
getValueForPixel() {}
/**
* Returns the location of the tick at the given index
* The coordinate (0, 0) is at the upper-left corner of the canvas
*/
getPixelForTick(index) {
const me = this;
const offset = me.options.offset;
const numTicks = me.ticks.length;
const tickWidth = 1 / Math.max(numTicks - (offset ? 0 : 1), 1);
return index < 0 || index > numTicks - 1
? null
: me.getPixelForDecimal(index * tickWidth + (offset ? tickWidth / 2 : 0));
}
/**
* Utility for getting the pixel location of a percentage of scale
* The coordinate (0, 0) is at the upper-left corner of the canvas
*/
getPixelForDecimal(decimal) {
const me = this;
if (me._reversePixels) {
decimal = 1 - decimal;
}
return me._startPixel + decimal * me._length;
}
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
*/
getBasePixel() {
return this.getPixelForValue(this.getBaseValue());
}
getBaseValue() {
const {min, max} = this;
return min < 0 && max < 0 ? max :
min > 0 && max > 0 ? min :
0;
}
/**
* Returns a subset of ticks to be plotted to avoid overlapping labels.
* @private
*/
_autoSkip(ticks) {
const me = this;
const tickOpts = me.options.ticks;
const axisLength = me._length;
const ticksLimit = tickOpts.maxTicksLimit || axisLength / me._tickSize();
const majorIndices = tickOpts.major.enabled ? getMajorIndices(ticks) : [];
const numMajorIndices = majorIndices.length;
const first = majorIndices[0];
const last = majorIndices[numMajorIndices - 1];
const newTicks = [];
// If there are too many major ticks to display them all
if (numMajorIndices > ticksLimit) {
skipMajors(ticks, newTicks, majorIndices, numMajorIndices / ticksLimit);
return newTicks;
}
const spacing = calculateSpacing(majorIndices, ticks, axisLength, ticksLimit);
if (numMajorIndices > 0) {
let i, ilen;
const avgMajorSpacing = numMajorIndices > 1 ? Math.round((last - first) / (numMajorIndices - 1)) : null;
skip(ticks, newTicks, spacing, helpers.isNullOrUndef(avgMajorSpacing) ? 0 : first - avgMajorSpacing, first);
for (i = 0, ilen = numMajorIndices - 1; i < ilen; i++) {
skip(ticks, newTicks, spacing, majorIndices[i], majorIndices[i + 1]);
}
skip(ticks, newTicks, spacing, last, helpers.isNullOrUndef(avgMajorSpacing) ? ticks.length : last + avgMajorSpacing);
return newTicks;
}
skip(ticks, newTicks, spacing);
return newTicks;
}
/**
* @private
*/
_tickSize() {
const me = this;
const optionTicks = me.options.ticks;
// Calculate space needed by label in axis direction.
const rot = helpers.math.toRadians(me.labelRotation);
const cos = Math.abs(Math.cos(rot));
const sin = Math.abs(Math.sin(rot));
const labelSizes = me._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 me.isHorizontal()
? h * cos > w * sin ? w / cos : h / sin
: h * sin < w * cos ? h / cos : w / sin;
}
/**
* @private
*/
_isVisible() {
const display = this.options.display;
if (display !== 'auto') {
return !!display;
}
return this._getMatchingVisibleMetas().length > 0;
}
/**
* @private
*/
_computeGridLineItems(chartArea) {
const me = this;
const axis = me.axis;
const chart = me.chart;
const options = me.options;
const {gridLines, position} = options;
const offsetGridLines = gridLines.offsetGridLines;
const isHorizontal = me.isHorizontal();
const ticks = me.ticks;
const ticksLength = ticks.length + (offsetGridLines ? 1 : 0);
const tl = getTickMarkLength(gridLines);
const items = [];
let context = {
scale: me,
tick: ticks[0],
};
const axisWidth = gridLines.drawBorder ? resolve([gridLines.borderWidth, gridLines.lineWidth, 0], context, 0) : 0;
const axisHalfWidth = axisWidth / 2;
const alignBorderValue = function(pixel) {
return alignPixel(chart, pixel, axisWidth);
};
let borderValue, i, tick, lineValue, alignedLineValue;
let tx1, ty1, tx2, ty2, x1, y1, x2, y2;
if (position === 'top') {
borderValue = alignBorderValue(me.bottom);
ty1 = me.bottom - tl;
ty2 = borderValue - axisHalfWidth;
y1 = alignBorderValue(chartArea.top) + axisHalfWidth;
y2 = chartArea.bottom;
} else if (position === 'bottom') {
borderValue = alignBorderValue(me.top);
y1 = chartArea.top;
y2 = alignBorderValue(chartArea.bottom) - axisHalfWidth;
ty1 = borderValue + axisHalfWidth;