-
Notifications
You must be signed in to change notification settings - Fork 11.9k
/
core.scale.js
1328 lines (1138 loc) · 35.9 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';
var defaults = require('./core.defaults');
var Element = require('./core.element');
var helpers = require('../helpers/index');
var Ticks = require('./core.ticks');
var isArray = helpers.isArray;
var isNullOrUndef = helpers.isNullOrUndef;
var valueOrDefault = helpers.valueOrDefault;
var valueAtIndexOrDefault = helpers.valueAtIndexOrDefault;
defaults._set('scale', {
display: true,
position: 'left',
offset: false,
// grid line settings
gridLines: {
display: true,
color: 'rgba(0,0,0,0.1)',
lineWidth: 1,
drawBorder: true,
drawOnChartArea: true,
drawTicks: true,
tickMarkLength: 10,
zeroLineWidth: 1,
zeroLineColor: 'rgba(0,0,0,0.25)',
zeroLineBorderDash: [],
zeroLineBorderDashOffset: 0.0,
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: {
beginAtZero: false,
minRotation: 0,
maxRotation: 50,
mirror: false,
padding: 0,
reverse: false,
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) {
var result = [];
var increment = arr.length / numItems;
var i = 0;
var len = arr.length;
for (; i < len; i += increment) {
result.push(arr[Math.floor(i)]);
}
return result;
}
function getPixelForGridLine(scale, index, offsetGridLines) {
var length = scale.getTicks().length;
var validIndex = Math.min(index, length - 1);
var lineValue = scale.getPixelForTick(validIndex);
var start = scale._startPixel;
var end = scale._endPixel;
var epsilon = 1e-6; // 1e-6 is margin in pixels for accumulated error.
var 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);
}
});
}
/**
* 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.
*/
function computeLabelSizes(ctx, tickFonts, ticks, caches) {
var length = ticks.length;
var widths = [];
var heights = [];
var offsets = [];
var 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)
};
}
function getTickMarkLength(options) {
return options.drawTicks ? options.tickMarkLength : 0;
}
function getScaleLabelHeight(options) {
var font, padding;
if (!options.display) {
return 0;
}
font = helpers.options._parseFont(options);
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: helpers.options.resolve([nestedOpts.fontColor, options.fontColor, defaults.global.defaultFontColor])
});
}
function parseTickFontOptions(options) {
var minor = parseFontOptions(options, options.minor);
var major = options.major.enabled ? parseFontOptions(options, options.major) : minor;
return {minor: minor, major: major};
}
var Scale = Element.extend({
zeroLineIndex: 0,
/**
* Get the padding needed for the scale
* @method getPadding
* @private
* @returns {Padding} the necessary padding
*/
getPadding: function() {
var 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: function() {
return this._ticks;
},
/**
* @private
*/
_getLabels: function() {
var 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
/**
* Provided for backward compatibility, not available anymore
* @function Chart.Scale.mergeTicksOptions
* @deprecated since version 2.8.0
* @todo remove at version 3
*/
mergeTicksOptions: function() {
// noop
},
beforeUpdate: function() {
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: function(maxWidth, maxHeight, margins) {
var me = this;
var tickOpts = me.options.ticks;
var sampleSize = tickOpts.sampleSize;
var i, ilen, labels, ticks, samplingEnabled;
// Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
me.beforeUpdate();
// Absorb the master measurements
me.maxWidth = maxWidth;
me.maxHeight = maxHeight;
me.margins = helpers.extend({
left: 0,
right: 0,
top: 0,
bottom: 0
}, margins);
me._ticks = null;
me.ticks = null;
me._labelSizes = null;
me._maxLabelLines = 0;
me.longestLabelWidth = 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();
// Ticks - `this.ticks` is now DEPRECATED!
// Internal ticks are now stored as objects in the PRIVATE `this._ticks` member
// and must not be accessed directly from outside this class. `this.ticks` being
// around for long time and not marked as private, we can't change its structure
// without unexpected breaking changes. If you need to access the scale ticks,
// use scale.getTicks() instead.
me.beforeBuildTicks();
// New implementations should return an array of objects but for BACKWARD COMPAT,
// we still support no return (`this.ticks` internally set by calling this method).
ticks = me.buildTicks() || [];
// Allow modification of ticks in callback.
ticks = me.afterBuildTicks(ticks) || ticks;
// Ensure ticks contains ticks in new tick format
if ((!ticks || !ticks.length) && me.ticks) {
ticks = [];
for (i = 0, ilen = me.ticks.length; i < ilen; ++i) {
ticks.push({
value: me.ticks[i],
major: false
});
}
}
me._ticks = ticks;
// 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 > ticks.length;
labels = me._convertTicksToLabels(samplingEnabled ? sample(ticks, sampleSize) : 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 calculateTickRotation, and
// it's ok that coordinates are not correct there, only dimensions matter.
me._configure();
// Tick Rotation
me.beforeCalculateTickRotation();
me.calculateTickRotation();
me.afterCalculateTickRotation();
me.beforeFit();
me.fit();
me.afterFit();
// Auto-skip
me._ticksToDraw = tickOpts.display && tickOpts.autoSkip ? me._autoSkip(ticks) : ticks;
if (samplingEnabled) {
// Generate labels using all non-skipped ticks
labels = me._convertTicksToLabels(me._ticksToDraw);
}
me.ticks = labels; // BACKWARD COMPATIBILITY
// IMPORTANT: after this point, we consider that `this.ticks` will NEVER change!
me.afterUpdate();
// TODO(v3): remove minSize as a public property and return value from all layout boxes. It is unused
// make maxWidth and maxHeight private
return me.minSize;
},
/**
* @private
*/
_configure: function() {
var me = this;
var reversePixels = me.options.ticks.reverse;
var 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: function() {
helpers.callback(this.options.afterUpdate, [this]);
},
//
beforeSetDimensions: function() {
helpers.callback(this.options.beforeSetDimensions, [this]);
},
setDimensions: function() {
var 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: function() {
helpers.callback(this.options.afterSetDimensions, [this]);
},
// Data limits
beforeDataLimits: function() {
helpers.callback(this.options.beforeDataLimits, [this]);
},
determineDataLimits: helpers.noop,
afterDataLimits: function() {
helpers.callback(this.options.afterDataLimits, [this]);
},
//
beforeBuildTicks: function() {
helpers.callback(this.options.beforeBuildTicks, [this]);
},
buildTicks: helpers.noop,
afterBuildTicks: function(ticks) {
var me = this;
// ticks is empty for old axis implementations here
if (isArray(ticks) && ticks.length) {
return helpers.callback(me.options.afterBuildTicks, [me, ticks]);
}
// Support old implementations (that modified `this.ticks` directly in buildTicks)
me.ticks = helpers.callback(me.options.afterBuildTicks, [me, me.ticks]) || me.ticks;
return ticks;
},
beforeTickToLabelConversion: function() {
helpers.callback(this.options.beforeTickToLabelConversion, [this]);
},
convertTicksToLabels: function() {
var me = this;
// Convert ticks to strings
var tickOpts = me.options.ticks;
me.ticks = me.ticks.map(tickOpts.userCallback || tickOpts.callback, this);
},
afterTickToLabelConversion: function() {
helpers.callback(this.options.afterTickToLabelConversion, [this]);
},
//
beforeCalculateTickRotation: function() {
helpers.callback(this.options.beforeCalculateTickRotation, [this]);
},
calculateTickRotation: function() {
var me = this;
var options = me.options;
var tickOpts = options.ticks;
var numTicks = me.getTicks().length;
var minRotation = tickOpts.minRotation || 0;
var maxRotation = tickOpts.maxRotation;
var labelRotation = minRotation;
var 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.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;
},
afterCalculateTickRotation: function() {
helpers.callback(this.options.afterCalculateTickRotation, [this]);
},
//
beforeFit: function() {
helpers.callback(this.options.beforeFit, [this]);
},
fit: function() {
var me = this;
// Reset
var minSize = me.minSize = {
width: 0,
height: 0
};
var chart = me.chart;
var opts = me.options;
var tickOpts = opts.ticks;
var scaleLabelOpts = opts.scaleLabel;
var gridLineOpts = opts.gridLines;
var display = me._isVisible();
var isBottom = opts.position === 'bottom';
var 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) {
var tickFonts = parseTickFontOptions(tickOpts);
var labelSizes = me._getLabelSizes();
var firstLabelSize = labelSizes.first;
var lastLabelSize = labelSizes.last;
var widestLabelSize = labelSizes.widest;
var highestLabelSize = labelSizes.highest;
var lineSpace = tickFonts.minor.lineHeight * 0.4;
var tickPadding = tickOpts.padding;
if (isHorizontal) {
// A horizontal axis is more constrained by the height.
var isRotated = me.labelRotation !== 0;
var angleRadians = helpers.toRadians(me.labelRotation);
var cosRotation = Math.cos(angleRadians);
var sinRotation = Math.sin(angleRadians);
var 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);
var offsetLeft = me.getPixelForTick(0) - me.left;
var offsetRight = me.right - me.getPixelForTick(me.getTicks().length - 1);
var 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 = isBottom ?
cosRotation * firstLabelSize.width + sinRotation * firstLabelSize.offset :
sinRotation * (firstLabelSize.height - firstLabelSize.offset);
paddingRight = isBottom ?
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: function() {
var 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: function() {
helpers.callback(this.options.afterFit, [this]);
},
// Shared Methods
isHorizontal: function() {
var pos = this.options.position;
return pos === 'top' || pos === 'bottom';
},
isFullWidth: function() {
return this.options.fullWidth;
},
// Get the correct value. NaN bad inputs, If the value type is object get the x or y based on whether we are horizontal or not
getRightValue: function(rawValue) {
// Null and undefined values first
if (isNullOrUndef(rawValue)) {
return NaN;
}
// isNaN(object) returns true, so make sure NaN is checking for a number; Discard Infinite values
if ((typeof rawValue === 'number' || rawValue instanceof Number) && !isFinite(rawValue)) {
return NaN;
}
// If it is in fact an object, dive in one more level
if (rawValue) {
if (this.isHorizontal()) {
if (rawValue.x !== undefined) {
return this.getRightValue(rawValue.x);
}
} else if (rawValue.y !== undefined) {
return this.getRightValue(rawValue.y);
}
}
// Value is good, return it
return rawValue;
},
_convertTicksToLabels: function(ticks) {
var me = this;
var labels, i, ilen;
me.ticks = ticks.map(function(tick) {
return tick.value;
});
me.beforeTickToLabelConversion();
// New implementations should return the formatted tick labels but for BACKWARD
// COMPAT, we still support no return (`this.ticks` internally changed by calling
// this method and supposed to contain only string values).
labels = me.convertTicksToLabels(ticks) || me.ticks;
me.afterTickToLabelConversion();
// BACKWARD COMPAT: synchronize `_ticks` with labels (so potentially `this.ticks`)
for (i = 0, ilen = ticks.length; i < ilen; ++i) {
ticks[i].label = labels[i];
}
return labels;
},
/**
* @private
*/
_getLabelSizes: function() {
var me = this;
var labelSizes = me._labelSizes;
if (!labelSizes) {
me._labelSizes = labelSizes = computeLabelSizes(me.ctx, parseTickFontOptions(me.options.ticks), me.getTicks(), me.longestTextCache);
me.longestLabelWidth = labelSizes.widest.width;
}
return labelSizes;
},
/**
* @private
*/
_parseValue: function(value) {
var start, end, min, max;
if (isArray(value)) {
start = +this.getRightValue(value[0]);
end = +this.getRightValue(value[1]);
min = Math.min(start, end);
max = Math.max(start, end);
} else {
value = +this.getRightValue(value);
start = undefined;
end = value;
min = value;
max = value;
}
return {
min: min,
max: max,
start: start,
end: end
};
},
/**
* @private
*/
_getScaleLabel: function(rawValue) {
var v = this._parseValue(rawValue);
if (v.start !== undefined) {
return '[' + v.start + ', ' + v.end + ']';
}
return +this.getRightValue(rawValue);
},
/**
* Used to get the value to display in the tooltip for the data at the given index
* @param index
* @param datasetIndex
*/
getLabelForIndex: helpers.noop,
/**
* 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: helpers.noop,
/**
* 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: helpers.noop,
/**
* Returns the location of the tick at the given index
* The coordinate (0, 0) is at the upper-left corner of the canvas
*/
getPixelForTick: function(index) {
var me = this;
var offset = me.options.offset;
var numTicks = me._ticks.length;
var 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: function(decimal) {
var me = this;
if (me._reversePixels) {
decimal = 1 - decimal;
}
return me._startPixel + decimal * me._length;
},
getDecimalForPixel: function(pixel) {
var decimal = (pixel - this._startPixel) / this._length;
return Math.min(1, Math.max(0, 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: function() {
return this.getPixelForValue(this.getBaseValue());
},
getBaseValue: function() {
var me = this;
var min = me.min;
var max = me.max;
return me.beginAtZero ? 0 :
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: function(ticks) {
var me = this;
var optionTicks = me.options.ticks;
var tickCount = ticks.length;
var skipRatio = false;
var maxTicks = optionTicks.maxTicksLimit;
// Total space needed to display all ticks. First and last ticks are
// drawn as their center at end of axis, so tickCount-1
var ticksLength = me._tickSize() * (tickCount - 1);
var axisLength = me._length;
var result = [];
var i, tick;
if (ticksLength > axisLength) {
skipRatio = 1 + Math.floor(ticksLength / axisLength);
}
// if they defined a max number of optionTicks,
// increase skipRatio until that number is met
if (tickCount > maxTicks) {
skipRatio = Math.max(skipRatio, 1 + Math.floor(tickCount / maxTicks));
}
for (i = 0; i < tickCount; i++) {
tick = ticks[i];
if (skipRatio <= 1 || i % skipRatio === 0) {
tick._index = i;
result.push(tick);
} else {
delete tick.label;
}
}
return result;
},
/**
* @private
*/
_tickSize: function() {
var me = this;
var optionTicks = me.options.ticks;
// Calculate space needed by label in axis direction.
var rot = helpers.toRadians(me.labelRotation);
var cos = Math.abs(Math.cos(rot));
var sin = Math.abs(Math.sin(rot));
var labelSizes = me._getLabelSizes();
var padding = optionTicks.autoSkipPadding || 0;
var w = labelSizes ? labelSizes.widest.width + padding : 0;
var 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: function() {
var me = this;
var chart = me.chart;
var display = me.options.display;
var i, ilen, meta;
if (display !== 'auto') {
return !!display;
}
// When 'auto', the scale is visible if at least one associated dataset is visible.
for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {
if (chart.isDatasetVisible(i)) {
meta = chart.getDatasetMeta(i);
if (meta.xAxisID === me.id || meta.yAxisID === me.id) {
return true;
}
}
}
return false;
},
/**
* @private
*/
_computeGridLineItems: function(chartArea) {
var me = this;
var chart = me.chart;
var options = me.options;
var gridLines = options.gridLines;
var position = options.position;
var offsetGridLines = gridLines.offsetGridLines;
var isHorizontal = me.isHorizontal();
var ticks = me._ticksToDraw;
var ticksLength = ticks.length + (offsetGridLines ? 1 : 0);
var tl = getTickMarkLength(gridLines);
var items = [];
var axisWidth = gridLines.drawBorder ? valueAtIndexOrDefault(gridLines.lineWidth, 0, 0) : 0;
var axisHalfWidth = axisWidth / 2;
var alignPixel = helpers._alignPixel;
var alignBorderValue = function(pixel) {
return alignPixel(chart, pixel, axisWidth);
};
var borderValue, i, tick, label, lineValue, alignedLineValue;
var tx1, ty1, tx2, ty2, x1, y1, x2, y2, lineWidth, lineColor, borderDash, borderDashOffset;
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;
ty2 = me.top + tl;
} else if (position === 'left') {
borderValue = alignBorderValue(me.right);
tx1 = me.right - tl;
tx2 = borderValue - axisHalfWidth;
x1 = alignBorderValue(chartArea.left) + axisHalfWidth;
x2 = chartArea.right;
} else {
borderValue = alignBorderValue(me.left);
x1 = chartArea.left;
x2 = alignBorderValue(chartArea.right) - axisHalfWidth;
tx1 = borderValue + axisHalfWidth;
tx2 = me.left + tl;
}
for (i = 0; i < ticksLength; ++i) {
tick = ticks[i] || {};
label = tick.label;
// autoskipper skipped this tick (#4635)
if (isNullOrUndef(label) && i < ticks.length) {
continue;
}
if (i === me.zeroLineIndex && options.offset === offsetGridLines) {
// Draw the first index specially
lineWidth = gridLines.zeroLineWidth;
lineColor = gridLines.zeroLineColor;
borderDash = gridLines.zeroLineBorderDash || [];