최초 커밋

This commit is contained in:
2025-10-01 09:29:34 +09:00
commit a8b84ff39a
1677 changed files with 954149 additions and 0 deletions

View File

@@ -0,0 +1,498 @@
/* *
*
* (c) 2010-2020 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from './Globals.js';
import Color from './Color.js';
var color = Color.parse;
import LegendSymbolMixin from '../mixins/legend-symbol.js';
import U from './Utilities.js';
var objectEach = U.objectEach, pick = U.pick, seriesType = U.seriesType;
import './Series.js';
import './Options.js';
var Series = H.Series;
/**
* Area series type.
*
* @private
* @class
* @name Highcharts.seriesTypes.area
*
* @augments Highcharts.Series
*/
seriesType('area', 'line',
/**
* The area series type.
*
* @sample {highcharts} highcharts/demo/area-basic/
* Area chart
* @sample {highstock} stock/demo/area/
* Area chart
*
* @extends plotOptions.line
* @excluding useOhlcData
* @product highcharts highstock
* @optionparent plotOptions.area
*/
{
/**
* Fill color or gradient for the area. When `null`, the series' `color`
* is used with the series' `fillOpacity`.
*
* In styled mode, the fill color can be set with the `.highcharts-area`
* class name.
*
* @sample {highcharts} highcharts/plotoptions/area-fillcolor-default/
* Null by default
* @sample {highcharts} highcharts/plotoptions/area-fillcolor-gradient/
* Gradient
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @product highcharts highstock
* @apioption plotOptions.area.fillColor
*/
/**
* Fill opacity for the area. When you set an explicit `fillColor`,
* the `fillOpacity` is not applied. Instead, you should define the
* opacity in the `fillColor` with an rgba color definition. The
* `fillOpacity` setting, also the default setting, overrides the alpha
* component of the `color` setting.
*
* In styled mode, the fill opacity can be set with the
* `.highcharts-area` class name.
*
* @sample {highcharts} highcharts/plotoptions/area-fillopacity/
* Automatic fill color and fill opacity of 0.1
*
* @type {number}
* @default {highcharts} 0.75
* @default {highstock} 0.75
* @product highcharts highstock
* @apioption plotOptions.area.fillOpacity
*/
/**
* A separate color for the graph line. By default the line takes the
* `color` of the series, but the lineColor setting allows setting a
* separate color for the line without altering the `fillColor`.
*
* In styled mode, the line stroke can be set with the
* `.highcharts-graph` class name.
*
* @sample {highcharts} highcharts/plotoptions/area-linecolor/
* Dark gray line
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @product highcharts highstock
* @apioption plotOptions.area.lineColor
*/
/**
* A separate color for the negative part of the area.
*
* In styled mode, a negative color is set with the
* `.highcharts-negative` class name.
*
* @see [negativeColor](#plotOptions.area.negativeColor)
*
* @sample {highcharts} highcharts/css/series-negative-color/
* Negative color in styled mode
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @since 3.0
* @product highcharts
* @apioption plotOptions.area.negativeFillColor
*/
/**
* Whether the whole area or just the line should respond to mouseover
* tooltips and other mouse or touch events.
*
* @sample {highcharts|highstock} highcharts/plotoptions/area-trackbyarea/
* Display the tooltip when the area is hovered
*
* @type {boolean}
* @default false
* @since 1.1.6
* @product highcharts highstock
* @apioption plotOptions.area.trackByArea
*/
/**
* When this is true, the series will not cause the Y axis to cross
* the zero plane (or [threshold](#plotOptions.series.threshold) option)
* unless the data actually crosses the plane.
*
* For example, if `softThreshold` is `false`, a series of 0, 1, 2,
* 3 will make the Y axis show negative values according to the
* `minPadding` option. If `softThreshold` is `true`, the Y axis starts
* at 0.
*
* @since 4.1.9
* @product highcharts highstock
*/
softThreshold: false,
/**
* The Y axis value to serve as the base for the area, for
* distinguishing between values above and below a threshold. The area
* between the graph and the threshold is filled.
*
* * If a number is given, the Y axis will scale to the threshold.
* * If `null`, the scaling behaves like a line series with fill between
* the graph and the Y axis minimum.
* * If `Infinity` or `-Infinity`, the area between the graph and the
* corresponing Y axis extreme is filled (since v6.1.0).
*
* @sample {highcharts} highcharts/plotoptions/area-threshold/
* A threshold of 100
* @sample {highcharts} highcharts/plotoptions/area-threshold-infinity/
* A threshold of Infinity
*
* @type {number|null}
* @since 2.0
* @product highcharts highstock
*/
threshold: 0
},
/* eslint-disable valid-jsdoc */
/**
* @lends seriesTypes.area.prototype
*/
{
singleStacks: false,
/**
* Return an array of stacked points, where null and missing points are
* replaced by dummy points in order for gaps to be drawn correctly in
* stacks.
* @private
*/
getStackPoints: function (points) {
var series = this, segment = [], keys = [], xAxis = this.xAxis, yAxis = this.yAxis, stack = yAxis.stacks[this.stackKey], pointMap = {}, seriesIndex = series.index, yAxisSeries = yAxis.series, seriesLength = yAxisSeries.length, visibleSeries, upOrDown = pick(yAxis.options.reversedStacks, true) ? 1 : -1, i;
points = points || this.points;
if (this.options.stacking) {
for (i = 0; i < points.length; i++) {
// Reset after point update (#7326)
points[i].leftNull = points[i].rightNull = void 0;
// Create a map where we can quickly look up the points by
// their X values.
pointMap[points[i].x] = points[i];
}
// Sort the keys (#1651)
objectEach(stack, function (stackX, x) {
// nulled after switching between
// grouping and not (#1651, #2336)
if (stackX.total !== null) {
keys.push(x);
}
});
keys.sort(function (a, b) {
return a - b;
});
visibleSeries = yAxisSeries.map(function (s) {
return s.visible;
});
keys.forEach(function (x, idx) {
var y = 0, stackPoint, stackedValues;
if (pointMap[x] && !pointMap[x].isNull) {
segment.push(pointMap[x]);
// Find left and right cliff. -1 goes left, 1 goes
// right.
[-1, 1].forEach(function (direction) {
var nullName = direction === 1 ?
'rightNull' :
'leftNull', cliffName = direction === 1 ?
'rightCliff' :
'leftCliff', cliff = 0, otherStack = stack[keys[idx + direction]];
// If there is a stack next to this one,
// to the left or to the right...
if (otherStack) {
i = seriesIndex;
// Can go either up or down,
// depending on reversedStacks
while (i >= 0 && i < seriesLength) {
stackPoint = otherStack.points[i];
if (!stackPoint) {
// If the next point in this series
// is missing, mark the point
// with point.leftNull or
// point.rightNull = true.
if (i === seriesIndex) {
pointMap[x][nullName] =
true;
// If there are missing points in
// the next stack in any of the
// series below this one, we need
// to substract the missing values
// and add a hiatus to the left or
// right.
}
else if (visibleSeries[i]) {
stackedValues =
stack[x].points[i];
if (stackedValues) {
cliff -=
stackedValues[1] -
stackedValues[0];
}
}
}
// When reversedStacks is true, loop up,
// else loop down
i += upOrDown;
}
}
pointMap[x][cliffName] = cliff;
});
// There is no point for this X value in this series, so we
// insert a dummy point in order for the areas to be drawn
// correctly.
}
else {
// Loop down the stack to find the series below this
// one that has a value (#1991)
i = seriesIndex;
while (i >= 0 && i < seriesLength) {
stackPoint = stack[x].points[i];
if (stackPoint) {
y = stackPoint[1];
break;
}
// When reversedStacks is true, loop up, else loop
// down
i += upOrDown;
}
y = yAxis.translate(// #6272
y, 0, 1, 0, 1);
segment.push({
isNull: true,
plotX: xAxis.translate(// #6272
x, 0, 0, 0, 1),
x: x,
plotY: y,
yBottom: y
});
}
});
}
return segment;
},
/**
* @private
*/
getGraphPath: function (points) {
var getGraphPath = Series.prototype.getGraphPath, graphPath, options = this.options, stacking = options.stacking, yAxis = this.yAxis, topPath, bottomPath, bottomPoints = [], graphPoints = [], seriesIndex = this.index, i, areaPath, plotX, stacks = yAxis.stacks[this.stackKey], threshold = options.threshold, translatedThreshold = Math.round(// #10909
yAxis.getThreshold(options.threshold)), isNull, yBottom, connectNulls = pick(// #10574
options.connectNulls, stacking === 'percent'),
// To display null points in underlying stacked series, this
// series graph must be broken, and the area also fall down to
// fill the gap left by the null point. #2069
addDummyPoints = function (i, otherI, side) {
var point = points[i], stackedValues = stacking &&
stacks[point.x].points[seriesIndex], nullVal = point[side + 'Null'] || 0, cliffVal = point[side + 'Cliff'] || 0, top, bottom, isNull = true;
if (cliffVal || nullVal) {
top = (nullVal ?
stackedValues[0] :
stackedValues[1]) + cliffVal;
bottom = stackedValues[0] + cliffVal;
isNull = !!nullVal;
}
else if (!stacking &&
points[otherI] &&
points[otherI].isNull) {
top = bottom = threshold;
}
// Add to the top and bottom line of the area
if (typeof top !== 'undefined') {
graphPoints.push({
plotX: plotX,
plotY: top === null ?
translatedThreshold :
yAxis.getThreshold(top),
isNull: isNull,
isCliff: true
});
bottomPoints.push({
plotX: plotX,
plotY: bottom === null ?
translatedThreshold :
yAxis.getThreshold(bottom),
doCurve: false // #1041, gaps in areaspline areas
});
}
};
// Find what points to use
points = points || this.points;
// Fill in missing points
if (stacking) {
points = this.getStackPoints(points);
}
for (i = 0; i < points.length; i++) {
// Reset after series.update of stacking property (#12033)
if (!stacking) {
points[i].leftCliff = points[i].rightCliff =
points[i].leftNull = points[i].rightNull = void 0;
}
isNull = points[i].isNull;
plotX = pick(points[i].rectPlotX, points[i].plotX);
yBottom = pick(points[i].yBottom, translatedThreshold);
if (!isNull || connectNulls) {
if (!connectNulls) {
addDummyPoints(i, i - 1, 'left');
}
// Skip null point when stacking is false and connectNulls
// true
if (!(isNull && !stacking && connectNulls)) {
graphPoints.push(points[i]);
bottomPoints.push({
x: i,
plotX: plotX,
plotY: yBottom
});
}
if (!connectNulls) {
addDummyPoints(i, i + 1, 'right');
}
}
}
topPath = getGraphPath.call(this, graphPoints, true, true);
bottomPoints.reversed = true;
bottomPath = getGraphPath.call(this, bottomPoints, true, true);
if (bottomPath.length) {
bottomPath[0] = 'L';
}
areaPath = topPath.concat(bottomPath);
// TODO: don't set leftCliff and rightCliff when connectNulls?
graphPath = getGraphPath
.call(this, graphPoints, false, connectNulls);
areaPath.xMap = topPath.xMap;
this.areaPath = areaPath;
return graphPath;
},
/**
* Draw the graph and the underlying area. This method calls the Series
* base function and adds the area. The areaPath is calculated in the
* getSegmentPath method called from Series.prototype.drawGraph.
* @private
*/
drawGraph: function () {
// Define or reset areaPath
this.areaPath = [];
// Call the base method
Series.prototype.drawGraph.apply(this);
// Define local variables
var series = this, areaPath = this.areaPath, options = this.options, zones = this.zones, props = [[
'area',
'highcharts-area',
this.color,
options.fillColor
]]; // area name, main color, fill color
zones.forEach(function (zone, i) {
props.push([
'zone-area-' + i,
'highcharts-area highcharts-zone-area-' + i + ' ' +
zone.className,
zone.color || series.color,
zone.fillColor || options.fillColor
]);
});
props.forEach(function (prop) {
var areaKey = prop[0], area = series[areaKey], verb = area ? 'animate' : 'attr', attribs = {};
// Create or update the area
if (area) { // update
area.endX = series.preventGraphAnimation ?
null :
areaPath.xMap;
area.animate({ d: areaPath });
}
else { // create
attribs.zIndex = 0; // #1069
area = series[areaKey] = series.chart.renderer
.path(areaPath)
.addClass(prop[1])
.add(series.group);
area.isArea = true;
}
if (!series.chart.styledMode) {
attribs.fill = pick(prop[3], color(prop[2])
.setOpacity(pick(options.fillOpacity, 0.75))
.get());
}
area[verb](attribs);
area.startX = areaPath.xMap;
area.shiftUnit = options.step ? 2 : 1;
});
},
drawLegendSymbol: LegendSymbolMixin.drawRectangle
});
/* eslint-enable valid-jsdoc */
/**
* A `area` series. If the [type](#series.area.type) option is not
* specified, it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.area
* @excluding dataParser, dataURL, useOhlcData
* @product highcharts highstock
* @apioption series.area
*/
/**
* An array of data points for the series. For the `area` series type,
* points can be given in the following ways:
*
* 1. An array of numerical values. In this case, the numerical values will be
* interpreted as `y` options. The `x` values will be automatically
* calculated, either starting at 0 and incremented by 1, or from
* `pointStart` * and `pointInterval` given in the series options. If the
* axis has categories, these will be used. Example:
* ```js
* data: [0, 5, 3, 5]
* ```
*
* 2. An array of arrays with 2 values. In this case, the values correspond to
* `x,y`. If the first value is a string, it is applied as the name of the
* point, and the `x` value is inferred.
* ```js
* data: [
* [0, 9],
* [1, 7],
* [2, 6]
* ]
* ```
*
* 3. An array of objects with named values. The following snippet shows only a
* few settings, see the complete options set below. If the total number of
* data points exceeds the series'
* [turboThreshold](#series.area.turboThreshold), this option is not
* available.
* ```js
* data: [{
* x: 1,
* y: 9,
* name: "Point2",
* color: "#00FF00"
* }, {
* x: 1,
* y: 6,
* name: "Point1",
* color: "#FF00FF"
* }]
* ```
*
* @sample {highcharts} highcharts/chart/reflow-true/
* Numerical values
* @sample {highcharts} highcharts/series/data-array-of-arrays/
* Arrays of numeric x and y
* @sample {highcharts} highcharts/series/data-array-of-arrays-datetime/
* Arrays of datetime x and y
* @sample {highcharts} highcharts/series/data-array-of-name-value/
* Arrays of point.name and y
* @sample {highcharts} highcharts/series/data-array-of-objects/
* Config objects
*
* @type {Array<number|Array<(number|string),(number|null)>|null|*>}
* @extends series.line.data
* @product highcharts highstock
* @apioption series.area.data
*/
''; // adds doclets above to transpilat

View File

@@ -0,0 +1,117 @@
/* *
*
* (c) 2010-2020 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from './Globals.js';
import LegendSymbolMixin from '../mixins/legend-symbol.js';
import U from './Utilities.js';
var seriesType = U.seriesType;
import './AreaSeries.js';
import './SplineSeries.js';
var areaProto = H.seriesTypes.area.prototype, defaultPlotOptions = H.defaultPlotOptions;
/**
* AreaSpline series type.
*
* @private
* @class
* @name Highcharts.seriesTypes.areaspline
*
* @augments Highcharts.Series
*/
seriesType('areaspline', 'spline',
/**
* The area spline series is an area series where the graph between the
* points is smoothed into a spline.
*
* @sample {highcharts} highcharts/demo/areaspline/
* Area spline chart
* @sample {highstock} stock/demo/areaspline/
* Area spline chart
*
* @extends plotOptions.area
* @excluding step
* @product highcharts highstock
* @apioption plotOptions.areaspline
*/
defaultPlotOptions.area, {
getStackPoints: areaProto.getStackPoints,
getGraphPath: areaProto.getGraphPath,
drawGraph: areaProto.drawGraph,
drawLegendSymbol: LegendSymbolMixin.drawRectangle
});
/**
* A `areaspline` series. If the [type](#series.areaspline.type) option
* is not specified, it is inherited from [chart.type](#chart.type).
*
*
* @extends series,plotOptions.areaspline
* @excluding dataParser, dataURL, step
* @product highcharts highstock
* @apioption series.areaspline
*/
/**
* An array of data points for the series. For the `areaspline` series
* type, points can be given in the following ways:
*
* 1. An array of numerical values. In this case, the numerical values will be
* interpreted as `y` options. The `x` values will be automatically
* calculated, either starting at 0 and incremented by 1, or from
* `pointStart` and `pointInterval` given in the series options. If the axis
* has categories, these will be used. Example:
* ```js
* data: [0, 5, 3, 5]
* ```
*
* 2. An array of arrays with 2 values. In this case, the values correspond to
* `x,y`. If the first value is a string, it is applied as the name of the
* point, and the `x` value is inferred.
* ```js
* data: [
* [0, 10],
* [1, 9],
* [2, 3]
* ]
* ```
*
* 3. An array of objects with named values. The following snippet shows only a
* few settings, see the complete options set below. If the total number of
* data points exceeds the series'
* [turboThreshold](#series.areaspline.turboThreshold), this option is not
* available.
* ```js
* data: [{
* x: 1,
* y: 4,
* name: "Point2",
* color: "#00FF00"
* }, {
* x: 1,
* y: 4,
* name: "Point1",
* color: "#FF00FF"
* }]
* ```
*
* @sample {highcharts} highcharts/chart/reflow-true/
* Numerical values
* @sample {highcharts} highcharts/series/data-array-of-arrays/
* Arrays of numeric x and y
* @sample {highcharts} highcharts/series/data-array-of-arrays-datetime/
* Arrays of datetime x and y
* @sample {highcharts} highcharts/series/data-array-of-name-value/
* Arrays of point.name and y
* @sample {highcharts} highcharts/series/data-array-of-objects/
* Config objects
*
* @type {Array<number|Array<(number|string),(number|null)>|null|*>}
* @extends series.line.data
* @product highcharts highstock
* @apioption series.areaspline.data
*/
''; // adds doclets above into transpilat

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,120 @@
/* *
*
* (c) 2010-2020 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import U from './Utilities.js';
var seriesType = U.seriesType;
import './ColumnSeries.js';
/**
* Bar series type.
*
* @private
* @class
* @name Highcharts.seriesTypes.bar
*
* @augments Highcharts.Series
*/
seriesType('bar', 'column',
/**
* A bar series is a special type of column series where the columns are
* horizontal.
*
* @sample highcharts/demo/bar-basic/
* Bar chart
*
* @extends plotOptions.column
* @product highcharts
* @apioption plotOptions.bar
*/
/**
* @ignore
*/
null, {
inverted: true
});
/**
* A `bar` series. If the [type](#series.bar.type) option is not specified,
* it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.bar
* @excluding connectNulls, dashStyle, dataParser, dataURL, gapSize, gapUnit,
* linecap, lineWidth, marker, connectEnds, step
* @product highcharts
* @apioption series.bar
*/
/**
* An array of data points for the series. For the `bar` series type,
* points can be given in the following ways:
*
* 1. An array of numerical values. In this case, the numerical values will be
* interpreted as `y` options. The `x` values will be automatically
* calculated, either starting at 0 and incremented by 1, or from
* `pointStart` and `pointInterval` given in the series options. If the axis
* has categories, these will be used. Example:
* ```js
* data: [0, 5, 3, 5]
* ```
*
* 2. An array of arrays with 2 values. In this case, the values correspond to
* `x,y`. If the first value is a string, it is applied as the name of the
* point, and the `x` value is inferred.
* ```js
* data: [
* [0, 5],
* [1, 10],
* [2, 3]
* ]
* ```
*
* 3. An array of objects with named values. The following snippet shows only a
* few settings, see the complete options set below. If the total number of
* data points exceeds the series'
* [turboThreshold](#series.bar.turboThreshold), this option is not
* available.
* ```js
* data: [{
* x: 1,
* y: 1,
* name: "Point2",
* color: "#00FF00"
* }, {
* x: 1,
* y: 10,
* name: "Point1",
* color: "#FF00FF"
* }]
* ```
*
* @sample {highcharts} highcharts/chart/reflow-true/
* Numerical values
* @sample {highcharts} highcharts/series/data-array-of-arrays/
* Arrays of numeric x and y
* @sample {highcharts} highcharts/series/data-array-of-arrays-datetime/
* Arrays of datetime x and y
* @sample {highcharts} highcharts/series/data-array-of-name-value/
* Arrays of point.name and y
* @sample {highcharts} highcharts/series/data-array-of-objects/
* Config objects
*
* @type {Array<number|Array<(number|string),(number|null)>|null|*>}
* @extends series.column.data
* @product highcharts
* @apioption series.bar.data
*/
/**
* @excluding halo,lineWidth,lineWidthPlus,marker
* @product highcharts highstock
* @apioption series.bar.states.hover
*/
/**
* @excluding halo,lineWidth,lineWidthPlus,marker
* @product highcharts highstock
* @apioption series.bar.states.select
*/
''; // gets doclets above into transpilat

View File

@@ -0,0 +1,285 @@
/* *
*
* (c) 2010-2020 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from './Globals.js';
import U from './Utilities.js';
var merge = U.merge, seriesType = U.seriesType;
var defaultPlotOptions = H.defaultPlotOptions, seriesTypes = H.seriesTypes;
/**
* A candlestick chart is a style of financial chart used to describe price
* movements over time.
*
* @sample stock/demo/candlestick/
* Candlestick chart
*
* @extends plotOptions.ohlc
* @excluding borderColor,borderRadius,borderWidth
* @product highstock
* @optionparent plotOptions.candlestick
*/
var candlestickOptions = {
/**
* The specific line color for up candle sticks. The default is to inherit
* the general `lineColor` setting.
*
* @sample {highstock} stock/plotoptions/candlestick-linecolor/
* Candlestick line colors
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @since 1.3.6
* @product highstock
* @apioption plotOptions.candlestick.upLineColor
*/
/**
* @type {Highcharts.DataGroupingApproximationValue|Function}
* @default ohlc
* @product highstock
* @apioption plotOptions.candlestick.dataGrouping.approximation
*/
states: {
/**
* @extends plotOptions.column.states.hover
* @product highstock
*/
hover: {
/**
* The pixel width of the line/border around the candlestick.
*
* @product highstock
*/
lineWidth: 2
}
},
/**
* @extends plotOptions.ohlc.tooltip
*/
tooltip: defaultPlotOptions.ohlc.tooltip,
/**
* @type {number|null}
* @product highstock
*/
threshold: null,
/**
* The color of the line/border of the candlestick.
*
* In styled mode, the line stroke can be set with the
* `.highcharts-candlestick-series .highcahrts-point` rule.
*
* @see [upLineColor](#plotOptions.candlestick.upLineColor)
*
* @sample {highstock} stock/plotoptions/candlestick-linecolor/
* Candlestick line colors
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @default #000000
* @product highstock
*/
lineColor: '#000000',
/**
* The pixel width of the candlestick line/border. Defaults to `1`.
*
*
* In styled mode, the line stroke width can be set with the
* `.highcharts-candlestick-series .highcahrts-point` rule.
*
* @product highstock
*/
lineWidth: 1,
/**
* The fill color of the candlestick when values are rising.
*
* In styled mode, the up color can be set with the
* `.highcharts-candlestick-series .highcharts-point-up` rule.
*
* @sample {highstock} stock/plotoptions/candlestick-color/
* Custom colors
* @sample {highstock} highcharts/css/candlestick/
* Colors in styled mode
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @default #ffffff
* @product highstock
*/
upColor: '#ffffff',
/**
* @product highstock
*/
stickyTracking: true
};
/**
* The candlestick series type.
*
* @private
* @class
* @name Highcharts.seriesTypes.candlestick
*
* @augments Highcharts.seriesTypes.ohlc
*/
seriesType('candlestick', 'ohlc', merge(defaultPlotOptions.column, candlestickOptions),
/**
* @lends seriesTypes.candlestick
*/
{
/* eslint-disable valid-jsdoc */
/**
* Postprocess mapping between options and SVG attributes
*
* @private
* @function Highcharts.seriesTypes.candlestick#pointAttribs
* @param {Highcharts.Point} point
* @param {string} [state]
* @return {Highcharts.SVGAttributes}
*/
pointAttribs: function (point, state) {
var attribs = seriesTypes.column.prototype.pointAttribs.call(this, point, state), options = this.options, isUp = point.open < point.close, stroke = options.lineColor || this.color, stateOptions;
attribs['stroke-width'] = options.lineWidth;
attribs.fill = point.options.color ||
(isUp ? (options.upColor || this.color) : this.color);
attribs.stroke = point.options.lineColor ||
(isUp ? (options.upLineColor || stroke) : stroke);
// Select or hover states
if (state) {
stateOptions = options.states[state];
attribs.fill = stateOptions.color || attribs.fill;
attribs.stroke = stateOptions.lineColor || attribs.stroke;
attribs['stroke-width'] =
stateOptions.lineWidth || attribs['stroke-width'];
}
return attribs;
},
/**
* Draw the data points.
*
* @private
* @function Highcharts.seriesTypes.candlestick#drawPoints
* @return {void}
*/
drawPoints: function () {
var series = this, points = series.points, chart = series.chart, reversedYAxis = series.yAxis.reversed;
points.forEach(function (point) {
var graphic = point.graphic, plotOpen, plotClose, topBox, bottomBox, hasTopWhisker, hasBottomWhisker, crispCorr, crispX, path, halfWidth, isNew = !graphic;
if (typeof point.plotY !== 'undefined') {
if (!graphic) {
point.graphic = graphic = chart.renderer.path()
.add(series.group);
}
if (!series.chart.styledMode) {
graphic
.attr(series.pointAttribs(point, (point.selected && 'select'))) // #3897
.shadow(series.options.shadow);
}
// Crisp vector coordinates
crispCorr = (graphic.strokeWidth() % 2) / 2;
// #2596:
crispX = Math.round(point.plotX) - crispCorr;
plotOpen = point.plotOpen;
plotClose = point.plotClose;
topBox = Math.min(plotOpen, plotClose);
bottomBox = Math.max(plotOpen, plotClose);
halfWidth = Math.round(point.shapeArgs.width / 2);
hasTopWhisker = reversedYAxis ?
bottomBox !== point.yBottom :
Math.round(topBox) !==
Math.round(point.plotHigh);
hasBottomWhisker = reversedYAxis ?
Math.round(topBox) !==
Math.round(point.plotHigh) :
bottomBox !== point.yBottom;
topBox = Math.round(topBox) + crispCorr;
bottomBox = Math.round(bottomBox) + crispCorr;
// Create the path. Due to a bug in Chrome 49, the path is
// first instanciated with no values, then the values
// pushed. For unknown reasons, instanciating the path array
// with all the values would lead to a crash when updating
// frequently (#5193).
path = [];
path.push('M', crispX - halfWidth, bottomBox, 'L', crispX - halfWidth, topBox, 'L', crispX + halfWidth, topBox, 'L', crispX + halfWidth, bottomBox, 'Z', // Ensure a nice rectangle #2602
'M', crispX, topBox, 'L',
// #460, #2094
crispX, hasTopWhisker ?
Math.round(reversedYAxis ?
point.yBottom :
point.plotHigh) :
topBox, 'M', crispX, bottomBox, 'L',
// #460, #2094
crispX, hasBottomWhisker ?
Math.round(reversedYAxis ?
point.plotHigh :
point.yBottom) :
bottomBox);
graphic[isNew ? 'attr' : 'animate']({ d: path })
.addClass(point.getClassName(), true);
}
});
/* eslint-enable valid-jsdoc */
}
});
/**
* A `candlestick` series. If the [type](#series.candlestick.type)
* option is not specified, it is inherited from [chart.type](
* #chart.type).
*
* @type {*}
* @extends series,plotOptions.candlestick
* @excluding dataParser, dataURL
* @product highstock
* @apioption series.candlestick
*/
/**
* An array of data points for the series. For the `candlestick` series
* type, points can be given in the following ways:
*
* 1. An array of arrays with 5 or 4 values. In this case, the values correspond
* to `x,open,high,low,close`. If the first value is a string, it is applied
* as the name of the point, and the `x` value is inferred. The `x` value can
* also be omitted, in which case the inner arrays should be of length 4.
* Then the `x` value is automatically calculated, either starting at 0 and
* incremented by 1, or from `pointStart` and `pointInterval` given in the
* series options.
* ```js
* data: [
* [0, 7, 2, 0, 4],
* [1, 1, 4, 2, 8],
* [2, 3, 3, 9, 3]
* ]
* ```
*
* 2. An array of objects with named values. The following snippet shows only a
* few settings, see the complete options set below. If the total number of
* data points exceeds the series'
* [turboThreshold](#series.candlestick.turboThreshold), this option is not
* available.
* ```js
* data: [{
* x: 1,
* open: 9,
* high: 2,
* low: 4,
* close: 6,
* name: "Point2",
* color: "#00FF00"
* }, {
* x: 1,
* open: 1,
* high: 4,
* low: 7,
* close: 7,
* name: "Point1",
* color: "#FF00FF"
* }]
* ```
*
* @type {Array<Array<(number|string),number,number,number>|Array<(number|string),number,number,number,number>|*>}
* @extends series.ohlc.data
* @excluding y
* @product highstock
* @apioption series.candlestick.data
*/
''; // adds doclets above to transpilat

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,405 @@
/* *
*
* (c) 2010-2020 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from './Globals.js';
/**
* A valid color to be parsed and handled by Highcharts. Highcharts internally
* supports hex colors like `#ffffff`, rgb colors like `rgb(255,255,255)` and
* rgba colors like `rgba(255,255,255,1)`. Other colors may be supported by the
* browsers and displayed correctly, but Highcharts is not able to process them
* and apply concepts like opacity and brightening.
*
* @typedef {string} Highcharts.ColorString
*/
/**
* A valid color type than can be parsed and handled by Highcharts. It can be a
* color string, a gradient object, or a pattern object.
*
* @typedef {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject} Highcharts.ColorType
*/
/**
* Gradient options instead of a solid color.
*
* @example
* // Linear gradient used as a color option
* color: {
* linearGradient: { x1: 0, x2: 0, y1: 0, y2: 1 },
* stops: [
* [0, '#003399'], // start
* [0.5, '#ffffff'], // middle
* [1, '#3366AA'] // end
* ]
* }
*
* @interface Highcharts.GradientColorObject
*/ /**
* Holds an object that defines the start position and the end position relative
* to the shape.
* @name Highcharts.GradientColorObject#linearGradient
* @type {Highcharts.LinearGradientColorObject|undefined}
*/ /**
* Holds an object that defines the center position and the radius.
* @name Highcharts.GradientColorObject#radialGradient
* @type {Highcharts.RadialGradientColorObject|undefined}
*/ /**
* The first item in each tuple is the position in the gradient, where 0 is the
* start of the gradient and 1 is the end of the gradient. Multiple stops can be
* applied. The second item is the color for each stop. This color can also be
* given in the rgba format.
* @name Highcharts.GradientColorObject#stops
* @type {Array<Highcharts.GradientColorStopObject>}
*/
/**
* Color stop tuple.
*
* @see Highcharts.GradientColorObject
*
* @interface Highcharts.GradientColorStopObject
*/ /**
* @name Highcharts.GradientColorStopObject#0
* @type {number}
*/ /**
* @name Highcharts.GradientColorStopObject#1
* @type {Highcharts.ColorString}
*/ /**
* @name Highcharts.GradoentColorStopObject#color
* @type {Highcharts.Color|undefined}
*/
/**
* Defines the start position and the end position for a gradient relative
* to the shape. Start position (x1, y1) and end position (x2, y2) are relative
* to the shape, where 0 means top/left and 1 is bottom/right.
*
* @interface Highcharts.LinearGradientColorObject
*/ /**
* Start horizontal position of the gradient. Float ranges 0-1.
* @name Highcharts.LinearGradientColorObject#x1
* @type {number}
*/ /**
* End horizontal position of the gradient. Float ranges 0-1.
* @name Highcharts.LinearGradientColorObject#x2
* @type {number}
*/ /**
* Start vertical position of the gradient. Float ranges 0-1.
* @name Highcharts.LinearGradientColorObject#y1
* @type {number}
*/ /**
* End vertical position of the gradient. Float ranges 0-1.
* @name Highcharts.LinearGradientColorObject#y2
* @type {number}
*/
/**
* Defines the center position and the radius for a gradient.
*
* @interface Highcharts.RadialGradientColorObject
*/ /**
* Center horizontal position relative to the shape. Float ranges 0-1.
* @name Highcharts.RadialGradientColorObject#cx
* @type {number}
*/ /**
* Center vertical position relative to the shape. Float ranges 0-1.
* @name Highcharts.RadialGradientColorObject#cy
* @type {number}
*/ /**
* Radius relative to the shape. Float ranges 0-1.
* @name Highcharts.RadialGradientColorObject#r
* @type {number}
*/
import U from './Utilities.js';
var isNumber = U.isNumber, merge = U.merge, pInt = U.pInt;
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* Handle color operations. Some object methods are chainable.
*
* @class
* @name Highcharts.Color
*
* @param {Highcharts.ColorType} input
* The input color in either rbga or hex format
*/
var Color = /** @class */ (function () {
/* *
*
* Constructors
*
* */
function Color(input) {
// Collection of parsers. This can be extended from the outside by pushing
// parsers to Highcharts.Color.prototype.parsers.
this.parsers = [{
// RGBA color
// eslint-disable-next-line max-len
regex: /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]?(?:\.[0-9]+)?)\s*\)/,
parse: function (result) {
return [
pInt(result[1]),
pInt(result[2]),
pInt(result[3]),
parseFloat(result[4], 10)
];
}
}, {
// RGB color
regex: /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/,
parse: function (result) {
return [pInt(result[1]), pInt(result[2]), pInt(result[3]), 1];
}
}];
this.rgba = [];
// Backwards compatibility, allow instanciation without new (#13053)
if (!(this instanceof Color)) {
return new Color(input);
}
this.init(input);
}
/* *
*
* Static Functions
*
* */
/**
* Creates a color instance out of a color string or object.
*
* @function Highcharts.Color.parse
*
* @param {Highcharts.ColorType} input
* The input color in either rbga or hex format.
*
* @return {Highcharts.Color}
* Color instance.
*/
Color.parse = function (input) {
return new Color(input);
};
/* *
*
* Functions
*
* */
/**
* Parse the input color to rgba array
*
* @private
* @function Highcharts.Color#init
*
* @param {Highcharts.ColorType} input
* The input color in either rbga or hex format
*
* @return {void}
*/
Color.prototype.init = function (input) {
var result, rgba, i, parser, len;
this.input = input = Color.names[input && input.toLowerCase ?
input.toLowerCase() :
''] || input;
// Gradients
if (input && input.stops) {
this.stops = input.stops.map(function (stop) {
return new Color(stop[1]);
});
// Solid colors
}
else {
// Bitmasking as input[0] is not working for legacy IE.
if (input &&
input.charAt &&
input.charAt() === '#') {
len = input.length;
input = parseInt(input.substr(1), 16);
// Handle long-form, e.g. #AABBCC
if (len === 7) {
rgba = [
(input & 0xFF0000) >> 16,
(input & 0xFF00) >> 8,
(input & 0xFF),
1
];
// Handle short-form, e.g. #ABC
// In short form, the value is assumed to be the same
// for both nibbles for each component. e.g. #ABC = #AABBCC
}
else if (len === 4) {
rgba = [
(((input & 0xF00) >> 4) |
(input & 0xF00) >> 8),
(((input & 0xF0) >> 4) |
(input & 0xF0)),
((input & 0xF) << 4) | (input & 0xF),
1
];
}
}
// Otherwise, check regex parsers
if (!rgba) {
i = this.parsers.length;
while (i-- && !rgba) {
parser = this.parsers[i];
result = parser.regex.exec(input);
if (result) {
rgba = parser.parse(result);
}
}
}
}
this.rgba = rgba || [];
};
/**
* Return the color or gradient stops in the specified format
*
* @function Highcharts.Color#get
*
* @param {string} [format]
* Possible values are 'a', 'rgb', 'rgba' (default).
*
* @return {Highcharts.ColorType}
* This color as a string or gradient stops.
*/
Color.prototype.get = function (format) {
var input = this.input, rgba = this.rgba, ret;
if (typeof this.stops !== 'undefined') {
ret = merge(input);
ret.stops = [].concat(ret.stops);
this.stops.forEach(function (stop, i) {
ret.stops[i] = [
ret.stops[i][0],
stop.get(format)
];
});
// it's NaN if gradient colors on a column chart
}
else if (rgba && isNumber(rgba[0])) {
if (format === 'rgb' || (!format && rgba[3] === 1)) {
ret = 'rgb(' + rgba[0] + ',' + rgba[1] + ',' + rgba[2] + ')';
}
else if (format === 'a') {
ret = rgba[3];
}
else {
ret = 'rgba(' + rgba.join(',') + ')';
}
}
else {
ret = input;
}
return ret;
};
/**
* Brighten the color instance.
*
* @function Highcharts.Color#brighten
*
* @param {number} alpha
* The alpha value.
*
* @return {Highcharts.Color}
* This color with modifications.
*/
Color.prototype.brighten = function (alpha) {
var i, rgba = this.rgba;
if (this.stops) {
this.stops.forEach(function (stop) {
stop.brighten(alpha);
});
}
else if (isNumber(alpha) && alpha !== 0) {
for (i = 0; i < 3; i++) {
rgba[i] += pInt(alpha * 255);
if (rgba[i] < 0) {
rgba[i] = 0;
}
if (rgba[i] > 255) {
rgba[i] = 255;
}
}
}
return this;
};
/**
* Set the color's opacity to a given alpha value.
*
* @function Highcharts.Color#setOpacity
*
* @param {number} alpha
* Opacity between 0 and 1.
*
* @return {Highcharts.Color}
* Color with modifications.
*/
Color.prototype.setOpacity = function (alpha) {
this.rgba[3] = alpha;
return this;
};
/**
* Return an intermediate color between two colors.
*
* @function Highcharts.Color#tweenTo
*
* @param {Highcharts.Color} to
* The color object to tween to.
*
* @param {number} pos
* The intermediate position, where 0 is the from color (current
* color item), and 1 is the `to` color.
*
* @return {Highcharts.ColorString}
* The intermediate color in rgba notation.
*/
Color.prototype.tweenTo = function (to, pos) {
// Check for has alpha, because rgba colors perform worse due to lack of
// support in WebKit.
var fromRgba = this.rgba, toRgba = to.rgba, hasAlpha, ret;
// Unsupported color, return to-color (#3920, #7034)
if (!toRgba.length || !fromRgba || !fromRgba.length) {
ret = to.input || 'none';
// Interpolate
}
else {
hasAlpha = (toRgba[3] !== 1 || fromRgba[3] !== 1);
ret = (hasAlpha ? 'rgba(' : 'rgb(') +
Math.round(toRgba[0] + (fromRgba[0] - toRgba[0]) * (1 - pos)) +
',' +
Math.round(toRgba[1] + (fromRgba[1] - toRgba[1]) * (1 - pos)) +
',' +
Math.round(toRgba[2] + (fromRgba[2] - toRgba[2]) * (1 - pos)) +
(hasAlpha ?
(',' +
(toRgba[3] + (fromRgba[3] - toRgba[3]) * (1 - pos))) :
'') +
')';
}
return ret;
};
/* *
*
* Static Properties
*
* */
// Collection of named colors. Can be extended from the outside by adding
// colors to Highcharts.Color.names.
Color.names = {
white: '#ffffff',
black: '#000000'
};
return Color;
}());
H.Color = Color;
/**
* Creates a color instance out of a color string.
*
* @function Highcharts.color
*
* @param {Highcharts.ColorType} input
* The input color in either rbga or hex format
*
* @return {Highcharts.Color}
* Color instance
*/
H.color = Color.parse;
export default H.Color;

View File

@@ -0,0 +1,984 @@
/* *
*
* (c) 2010-2020 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from './Globals.js';
/**
* Adjusted width and x offset of the columns for grouping.
*
* @private
* @interface Highcharts.ColumnMetricsObject
*/ /**
* Width of the columns.
* @name Highcharts.ColumnMetricsObject#width
* @type {number}
*/ /**
* Offset of the columns.
* @name Highcharts.ColumnMetricsObject#offset
* @type {number}
*/
''; // detach doclets above
import Color from './Color.js';
var color = Color.parse;
import LegendSymbolMixin from '../mixins/legend-symbol.js';
import U from './Utilities.js';
var animObject = U.animObject, clamp = U.clamp, defined = U.defined, extend = U.extend, isNumber = U.isNumber, merge = U.merge, pick = U.pick, seriesType = U.seriesType;
import './Series.js';
import './Options.js';
var noop = H.noop, Series = H.Series, svg = H.svg;
/**
* The column series type.
*
* @private
* @class
* @name Highcharts.seriesTypes.column
*
* @augments Highcharts.Series
*/
seriesType('column', 'line',
/**
* Column series display one column per value along an X axis.
*
* @sample {highcharts} highcharts/demo/column-basic/
* Column chart
* @sample {highstock} stock/demo/column/
* Column chart
*
* @extends plotOptions.line
* @excluding connectEnds, connectNulls, gapSize, gapUnit, linecap,
* lineWidth, marker, step, useOhlcData
* @product highcharts highstock
* @optionparent plotOptions.column
*/
{
/**
* The corner radius of the border surrounding each column or bar.
*
* @sample {highcharts} highcharts/plotoptions/column-borderradius/
* Rounded columns
*
* @product highcharts highstock gantt
*
* @private
*/
borderRadius: 0,
/**
* When using automatic point colors pulled from the global
* [colors](colors) or series-specific
* [plotOptions.column.colors](series.colors) collections, this option
* determines whether the chart should receive one color per series or
* one color per point.
*
* In styled mode, the `colors` or `series.colors` arrays are not
* supported, and instead this option gives the points individual color
* class names on the form `highcharts-color-{n}`.
*
* @see [series colors](#plotOptions.column.colors)
*
* @sample {highcharts} highcharts/plotoptions/column-colorbypoint-false/
* False by default
* @sample {highcharts} highcharts/plotoptions/column-colorbypoint-true/
* True
*
* @type {boolean}
* @default false
* @since 2.0
* @product highcharts highstock gantt
* @apioption plotOptions.column.colorByPoint
*/
/**
* A series specific or series type specific color set to apply instead
* of the global [colors](#colors) when [colorByPoint](
* #plotOptions.column.colorByPoint) is true.
*
* @type {Array<Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject>}
* @since 3.0
* @product highcharts highstock gantt
* @apioption plotOptions.column.colors
*/
/**
* When true, each column edge is rounded to its nearest pixel in order
* to render sharp on screen. In some cases, when there are a lot of
* densely packed columns, this leads to visible difference in column
* widths or distance between columns. In these cases, setting `crisp`
* to `false` may look better, even though each column is rendered
* blurry.
*
* @sample {highcharts} highcharts/plotoptions/column-crisp-false/
* Crisp is false
*
* @since 5.0.10
* @product highcharts highstock gantt
*
* @private
*/
crisp: true,
/**
* Padding between each value groups, in x axis units.
*
* @sample {highcharts} highcharts/plotoptions/column-grouppadding-default/
* 0.2 by default
* @sample {highcharts} highcharts/plotoptions/column-grouppadding-none/
* No group padding - all columns are evenly spaced
*
* @product highcharts highstock gantt
*
* @private
*/
groupPadding: 0.2,
/**
* Whether to group non-stacked columns or to let them render
* independent of each other. Non-grouped columns will be laid out
* individually and overlap each other.
*
* @sample {highcharts} highcharts/plotoptions/column-grouping-false/
* Grouping disabled
* @sample {highstock} highcharts/plotoptions/column-grouping-false/
* Grouping disabled
*
* @type {boolean}
* @default true
* @since 2.3.0
* @product highcharts highstock gantt
* @apioption plotOptions.column.grouping
*/
/**
* @ignore-option
* @private
*/
marker: null,
/**
* The maximum allowed pixel width for a column, translated to the
* height of a bar in a bar chart. This prevents the columns from
* becoming too wide when there is a small number of points in the
* chart.
*
* @see [pointWidth](#plotOptions.column.pointWidth)
*
* @sample {highcharts} highcharts/plotoptions/column-maxpointwidth-20/
* Limited to 50
* @sample {highstock} highcharts/plotoptions/column-maxpointwidth-20/
* Limited to 50
*
* @type {number}
* @since 4.1.8
* @product highcharts highstock gantt
* @apioption plotOptions.column.maxPointWidth
*/
/**
* Padding between each column or bar, in x axis units.
*
* @sample {highcharts} highcharts/plotoptions/column-pointpadding-default/
* 0.1 by default
* @sample {highcharts} highcharts/plotoptions/column-pointpadding-025/
* 0.25
* @sample {highcharts} highcharts/plotoptions/column-pointpadding-none/
* 0 for tightly packed columns
*
* @product highcharts highstock gantt
*
* @private
*/
pointPadding: 0.1,
/**
* A pixel value specifying a fixed width for each column or bar. When
* `null`, the width is calculated from the `pointPadding` and
* `groupPadding`.
*
* @see [maxPointWidth](#plotOptions.column.maxPointWidth)
*
* @sample {highcharts} highcharts/plotoptions/column-pointwidth-20/
* 20px wide columns regardless of chart width or the amount of
* data points
*
* @type {number}
* @since 1.2.5
* @product highcharts highstock gantt
* @apioption plotOptions.column.pointWidth
*/
/**
* A pixel value specifying a fixed width for the column or bar.
* Overrides pointWidth on the series.
*
* @see [series.pointWidth](#plotOptions.column.pointWidth)
*
* @type {number}
* @default undefined
* @since 7.0.0
* @product highcharts highstock gantt
* @apioption series.column.data.pointWidth
*/
/**
* The minimal height for a column or width for a bar. By default,
* 0 values are not shown. To visualize a 0 (or close to zero) point,
* set the minimal point length to a pixel value like 3\. In stacked
* column charts, minPointLength might not be respected for tightly
* packed values.
*
* @sample {highcharts} highcharts/plotoptions/column-minpointlength/
* Zero base value
* @sample {highcharts} highcharts/plotoptions/column-minpointlength-pos-and-neg/
* Positive and negative close to zero values
*
* @product highcharts highstock gantt
*
* @private
*/
minPointLength: 0,
/**
* When the series contains less points than the crop threshold, all
* points are drawn, event if the points fall outside the visible plot
* area at the current zoom. The advantage of drawing all points
* (including markers and columns), is that animation is performed on
* updates. On the other hand, when the series contains more points than
* the crop threshold, the series data is cropped to only contain points
* that fall within the plot area. The advantage of cropping away
* invisible points is to increase performance on large series.
*
* @product highcharts highstock gantt
*
* @private
*/
cropThreshold: 50,
/**
* The X axis range that each point is valid for. This determines the
* width of the column. On a categorized axis, the range will be 1
* by default (one category unit). On linear and datetime axes, the
* range will be computed as the distance between the two closest data
* points.
*
* The default `null` means it is computed automatically, but this
* option can be used to override the automatic value.
*
* This option is set by default to 1 if data sorting is enabled.
*
* @sample {highcharts} highcharts/plotoptions/column-pointrange/
* Set the point range to one day on a data set with one week
* between the points
*
* @type {number|null}
* @since 2.3
* @product highcharts highstock gantt
*
* @private
*/
pointRange: null,
states: {
/**
* Options for the hovered point. These settings override the normal
* state options when a point is moused over or touched.
*
* @extends plotOptions.series.states.hover
* @excluding halo, lineWidth, lineWidthPlus, marker
* @product highcharts highstock gantt
*/
hover: {
/** @ignore-option */
halo: false,
/**
* A specific border color for the hovered point. Defaults to
* inherit the normal state border color.
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @product highcharts gantt
* @apioption plotOptions.column.states.hover.borderColor
*/
/**
* A specific color for the hovered point.
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @product highcharts gantt
* @apioption plotOptions.column.states.hover.color
*/
/**
* How much to brighten the point on interaction. Requires the
* main color to be defined in hex or rgb(a) format.
*
* In styled mode, the hover brightening is by default replaced
* with a fill-opacity set in the `.highcharts-point:hover`
* rule.
*
* @sample {highcharts} highcharts/plotoptions/column-states-hover-brightness/
* Brighten by 0.5
*
* @product highcharts highstock gantt
*/
brightness: 0.1
},
/**
* Options for the selected point. These settings override the
* normal state options when a point is selected.
*
* @extends plotOptions.series.states.select
* @excluding halo, lineWidth, lineWidthPlus, marker
* @product highcharts highstock gantt
*/
select: {
/**
* A specific color for the selected point.
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @default #cccccc
* @product highcharts highstock gantt
*/
color: '#cccccc',
/**
* A specific border color for the selected point.
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @default #000000
* @product highcharts highstock gantt
*/
borderColor: '#000000'
}
},
dataLabels: {
align: null,
verticalAlign: null,
y: null
},
/**
* When this is true, the series will not cause the Y axis to cross
* the zero plane (or [threshold](#plotOptions.series.threshold) option)
* unless the data actually crosses the plane.
*
* For example, if `softThreshold` is `false`, a series of 0, 1, 2,
* 3 will make the Y axis show negative values according to the
* `minPadding` option. If `softThreshold` is `true`, the Y axis starts
* at 0.
*
* @since 4.1.9
* @product highcharts highstock
*
* @private
*/
softThreshold: false,
// false doesn't work well: https://jsfiddle.net/highcharts/hz8fopan/14/
/**
* @ignore-option
* @private
*/
startFromThreshold: true,
stickyTracking: false,
tooltip: {
distance: 6
},
/**
* The Y axis value to serve as the base for the columns, for
* distinguishing between values above and below a threshold. If `null`,
* the columns extend from the padding Y axis minimum.
*
* @type {number|null}
* @since 2.0
* @product highcharts
*
* @private
*/
threshold: 0,
/**
* The width of the border surrounding each column or bar. Defaults to
* `1` when there is room for a border, but to `0` when the columns are
* so dense that a border would cover the next column.
*
* In styled mode, the stroke width can be set with the
* `.highcharts-point` rule.
*
* @sample {highcharts} highcharts/plotoptions/column-borderwidth/
* 2px black border
*
* @type {number}
* @default undefined
* @product highcharts highstock gantt
* @apioption plotOptions.column.borderWidth
*/
/**
* The color of the border surrounding each column or bar.
*
* In styled mode, the border stroke can be set with the
* `.highcharts-point` rule.
*
* @sample {highcharts} highcharts/plotoptions/column-bordercolor/
* Dark gray border
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @default #ffffff
* @product highcharts highstock gantt
*
* @private
*/
borderColor: '#ffffff'
},
/**
* @lends seriesTypes.column.prototype
*/
{
cropShoulder: 0,
// When tooltip is not shared, this series (and derivatives) requires
// direct touch/hover. KD-tree does not apply.
directTouch: true,
trackerGroups: ['group', 'dataLabelsGroup'],
// use separate negative stacks, unlike area stacks where a negative
// point is substracted from previous (#1910)
negStacks: true,
/* eslint-disable valid-jsdoc */
/**
* Initialize the series. Extends the basic Series.init method by
* marking other series of the same type as dirty.
*
* @private
* @function Highcharts.seriesTypes.column#init
* @return {void}
*/
init: function () {
Series.prototype.init.apply(this, arguments);
var series = this, chart = series.chart;
// if the series is added dynamically, force redraw of other
// series affected by a new column
if (chart.hasRendered) {
chart.series.forEach(function (otherSeries) {
if (otherSeries.type === series.type) {
otherSeries.isDirty = true;
}
});
}
},
/**
* Return the width and x offset of the columns adjusted for grouping,
* groupPadding, pointPadding, pointWidth etc.
*
* @private
* @function Highcharts.seriesTypes.column#getColumnMetrics
* @return {Highcharts.ColumnMetricsObject}
*/
getColumnMetrics: function () {
var series = this, options = series.options, xAxis = series.xAxis, yAxis = series.yAxis, reversedStacks = xAxis.options.reversedStacks,
// Keep backward compatibility: reversed xAxis had reversed
// stacks
reverseStacks = (xAxis.reversed && !reversedStacks) ||
(!xAxis.reversed && reversedStacks), stackKey, stackGroups = {}, columnCount = 0;
// Get the total number of column type series. This is called on
// every series. Consider moving this logic to a chart.orderStacks()
// function and call it on init, addSeries and removeSeries
if (options.grouping === false) {
columnCount = 1;
}
else {
series.chart.series.forEach(function (otherSeries) {
var otherYAxis = otherSeries.yAxis, otherOptions = otherSeries.options, columnIndex;
if (otherSeries.type === series.type &&
(otherSeries.visible ||
!series.chart.options.chart
.ignoreHiddenSeries) &&
yAxis.len === otherYAxis.len &&
yAxis.pos === otherYAxis.pos) { // #642, #2086
if (otherOptions.stacking) {
stackKey = otherSeries.stackKey;
if (typeof stackGroups[stackKey] ===
'undefined') {
stackGroups[stackKey] = columnCount++;
}
columnIndex = stackGroups[stackKey];
}
else if (otherOptions.grouping !== false) { // #1162
columnIndex = columnCount++;
}
otherSeries.columnIndex = columnIndex;
}
});
}
var categoryWidth = Math.min(Math.abs(xAxis.transA) * (xAxis.ordinalSlope ||
options.pointRange ||
xAxis.closestPointRange ||
xAxis.tickInterval ||
1), // #2610
xAxis.len // #1535
), groupPadding = categoryWidth * options.groupPadding, groupWidth = categoryWidth - 2 * groupPadding, pointOffsetWidth = groupWidth / (columnCount || 1), pointWidth = Math.min(options.maxPointWidth || xAxis.len, pick(options.pointWidth, pointOffsetWidth * (1 - 2 * options.pointPadding))), pointPadding = (pointOffsetWidth - pointWidth) / 2,
// #1251, #3737
colIndex = (series.columnIndex || 0) + (reverseStacks ? 1 : 0), pointXOffset = pointPadding +
(groupPadding +
colIndex * pointOffsetWidth -
(categoryWidth / 2)) * (reverseStacks ? -1 : 1);
// Save it for reading in linked series (Error bars particularly)
series.columnMetrics = {
width: pointWidth,
offset: pointXOffset
};
return series.columnMetrics;
},
/**
* Make the columns crisp. The edges are rounded to the nearest full
* pixel.
*
* @private
* @function Highcharts.seriesTypes.column#crispCol
* @param {number} x
* @param {number} y
* @param {number} w
* @param {number} h
* @return {Highcharts.BBoxObject}
*/
crispCol: function (x, y, w, h) {
var chart = this.chart, borderWidth = this.borderWidth, xCrisp = -(borderWidth % 2 ? 0.5 : 0), yCrisp = borderWidth % 2 ? 0.5 : 1, right, bottom, fromTop;
if (chart.inverted && chart.renderer.isVML) {
yCrisp += 1;
}
// Horizontal. We need to first compute the exact right edge, then
// round it and compute the width from there.
if (this.options.crisp) {
right = Math.round(x + w) + xCrisp;
x = Math.round(x) + xCrisp;
w = right - x;
}
// Vertical
bottom = Math.round(y + h) + yCrisp;
fromTop = Math.abs(y) <= 0.5 && bottom > 0.5; // #4504, #4656
y = Math.round(y) + yCrisp;
h = bottom - y;
// Top edges are exceptions
if (fromTop && h) { // #5146
y -= 1;
h += 1;
}
return {
x: x,
y: y,
width: w,
height: h
};
},
/**
* Translate each point to the plot area coordinate system and find
* shape positions
*
* @private
* @function Highcharts.seriesTypes.column#translate
*/
translate: function () {
var series = this, chart = series.chart, options = series.options, dense = series.dense =
series.closestPointRange * series.xAxis.transA < 2, borderWidth = series.borderWidth = pick(options.borderWidth, dense ? 0 : 1 // #3635
), xAxis = series.xAxis, yAxis = series.yAxis, threshold = options.threshold, translatedThreshold = series.translatedThreshold =
yAxis.getThreshold(threshold), minPointLength = pick(options.minPointLength, 5), metrics = series.getColumnMetrics(), seriesPointWidth = metrics.width,
// postprocessed for border width
seriesBarW = series.barW =
Math.max(seriesPointWidth, 1 + 2 * borderWidth), seriesXOffset = series.pointXOffset = metrics.offset, dataMin = series.dataMin, dataMax = series.dataMax;
if (chart.inverted) {
translatedThreshold -= 0.5; // #3355
}
// When the pointPadding is 0, we want the columns to be packed
// tightly, so we allow individual columns to have individual sizes.
// When pointPadding is greater, we strive for equal-width columns
// (#2694).
if (options.pointPadding) {
seriesBarW = Math.ceil(seriesBarW);
}
Series.prototype.translate.apply(series);
// Record the new values
series.points.forEach(function (point) {
var yBottom = pick(point.yBottom, translatedThreshold), safeDistance = 999 + Math.abs(yBottom), pointWidth = seriesPointWidth, plotX = point.plotX,
// Don't draw too far outside plot area (#1303, #2241,
// #4264)
plotY = clamp(point.plotY, -safeDistance, yAxis.len + safeDistance), barX = point.plotX + seriesXOffset, barW = seriesBarW, barY = Math.min(plotY, yBottom), up, barH = Math.max(plotY, yBottom) - barY;
// Handle options.minPointLength
if (minPointLength && Math.abs(barH) < minPointLength) {
barH = minPointLength;
up = (!yAxis.reversed && !point.negative) ||
(yAxis.reversed && point.negative);
// Reverse zeros if there's no positive value in the series
// in visible range (#7046)
if (point.y === threshold &&
series.dataMax <= threshold &&
// and if there's room for it (#7311)
yAxis.min < threshold &&
// if all points are the same value (i.e zero) not draw
// as negative points (#10646)
dataMin !== dataMax) {
up = !up;
}
// If stacked...
barY = (Math.abs(barY - translatedThreshold) > minPointLength ?
// ...keep position
yBottom - minPointLength :
// #1485, #4051
translatedThreshold -
(up ? minPointLength : 0));
}
// Handle point.options.pointWidth
// @todo Handle grouping/stacking too. Calculate offset properly
if (defined(point.options.pointWidth)) {
pointWidth = barW =
Math.ceil(point.options.pointWidth);
barX -= Math.round((pointWidth - seriesPointWidth) / 2);
}
// Cache for access in polar
point.barX = barX;
point.pointWidth = pointWidth;
// Fix the tooltip on center of grouped columns (#1216, #424,
// #3648)
point.tooltipPos = chart.inverted ?
[
yAxis.len + yAxis.pos - chart.plotLeft - plotY,
xAxis.len + xAxis.pos - chart.plotTop - (plotX || 0) - seriesXOffset - barW / 2,
barH
] :
[barX + barW / 2, plotY + yAxis.pos -
chart.plotTop, barH];
// Register shape type and arguments to be used in drawPoints
// Allow shapeType defined on pointClass level
point.shapeType =
series.pointClass.prototype.shapeType || 'rect';
point.shapeArgs = series.crispCol.apply(series, point.isNull ?
// #3169, drilldown from null must have a position to work
// from #6585, dataLabel should be placed on xAxis, not
// floating in the middle of the chart
[barX, translatedThreshold, barW, 0] :
[barX, barY, barW, barH]);
});
},
getSymbol: noop,
/**
* Use a solid rectangle like the area series types
*
* @private
* @function Highcharts.seriesTypes.column#drawLegendSymbol
*
* @param {Highcharts.Legend} legend
* The legend object
*
* @param {Highcharts.Series|Highcharts.Point} item
* The series (this) or point
*/
drawLegendSymbol: LegendSymbolMixin.drawRectangle,
/**
* Columns have no graph
*
* @private
* @function Highcharts.seriesTypes.column#drawGraph
*/
drawGraph: function () {
this.group[this.dense ? 'addClass' : 'removeClass']('highcharts-dense-data');
},
/**
* Get presentational attributes
*
* @private
* @function Highcharts.seriesTypes.column#pointAttribs
*
* @param {Highcharts.ColumnPoint} point
*
* @param {string} state
*
* @return {Highcharts.SVGAttributes}
*/
pointAttribs: function (point, state) {
var options = this.options, stateOptions, ret, p2o = this.pointAttrToOptions || {}, strokeOption = p2o.stroke || 'borderColor', strokeWidthOption = p2o['stroke-width'] || 'borderWidth', fill = (point && point.color) || this.color,
// set to fill when borderColor null:
stroke = ((point && point[strokeOption]) ||
options[strokeOption] ||
this.color ||
fill), strokeWidth = (point && point[strokeWidthOption]) ||
options[strokeWidthOption] ||
this[strokeWidthOption] || 0, dashstyle = (point && point.options.dashStyle) || options.dashStyle, opacity = pick(point && point.opacity, options.opacity, 1), zone, brightness;
// Handle zone colors
if (point && this.zones.length) {
zone = point.getZone();
// When zones are present, don't use point.color (#4267).
// Changed order (#6527), added support for colorAxis (#10670)
fill = (point.options.color ||
(zone && (zone.color || point.nonZonedColor)) ||
this.color);
if (zone) {
stroke = zone.borderColor || stroke;
dashstyle = zone.dashStyle || dashstyle;
strokeWidth = zone.borderWidth || strokeWidth;
}
}
// Select or hover states
if (state && point) {
stateOptions = merge(options.states[state],
// #6401
point.options.states &&
point.options.states[state] ||
{});
brightness = stateOptions.brightness;
fill =
stateOptions.color || (typeof brightness !== 'undefined' &&
color(fill)
.brighten(stateOptions.brightness)
.get()) || fill;
stroke = stateOptions[strokeOption] || stroke;
strokeWidth =
stateOptions[strokeWidthOption] || strokeWidth;
dashstyle = stateOptions.dashStyle || dashstyle;
opacity = pick(stateOptions.opacity, opacity);
}
ret = {
fill: fill,
stroke: stroke,
'stroke-width': strokeWidth,
opacity: opacity
};
if (dashstyle) {
ret.dashstyle = dashstyle;
}
return ret;
},
/**
* Draw the columns. For bars, the series.group is rotated, so the same
* coordinates apply for columns and bars. This method is inherited by
* scatter series.
*
* @private
* @function Highcharts.seriesTypes.column#drawPoints
*/
drawPoints: function () {
var series = this, chart = this.chart, options = series.options, renderer = chart.renderer, animationLimit = options.animationLimit || 250, shapeArgs;
// draw the columns
series.points.forEach(function (point) {
var plotY = point.plotY, graphic = point.graphic, hasGraphic = !!graphic, verb = graphic && chart.pointCount < animationLimit ?
'animate' : 'attr';
if (isNumber(plotY) && point.y !== null) {
shapeArgs = point.shapeArgs;
// When updating a series between 2d and 3d or cartesian and
// polar, the shape type changes.
if (graphic && point.hasNewShapeType()) {
graphic = graphic.destroy();
}
// Set starting position for point sliding animation.
if (series.enabledDataSorting) {
point.startXPos = series.xAxis.reversed ?
-(shapeArgs ? shapeArgs.width : 0) :
series.xAxis.width;
}
if (!graphic) {
point.graphic = graphic =
renderer[point.shapeType](shapeArgs)
.add(point.group || series.group);
if (graphic &&
series.enabledDataSorting &&
chart.hasRendered &&
chart.pointCount < animationLimit) {
graphic.attr({
x: point.startXPos
});
hasGraphic = true;
verb = 'animate';
}
}
if (graphic && hasGraphic) { // update
graphic[verb](merge(shapeArgs));
}
// Border radius is not stylable (#6900)
if (options.borderRadius) {
graphic[verb]({
r: options.borderRadius
});
}
// Presentational
if (!chart.styledMode) {
graphic[verb](series.pointAttribs(point, (point.selected && 'select')))
.shadow(point.allowShadow !== false && options.shadow, null, options.stacking && !options.borderRadius);
}
graphic.addClass(point.getClassName(), true);
}
else if (graphic) {
point.graphic = graphic.destroy(); // #1269
}
});
},
/**
* Animate the column heights one by one from zero.
*
* @private
* @function Highcharts.seriesTypes.column#animate
*
* @param {boolean} init
* Whether to initialize the animation or run it
*/
animate: function (init) {
var series = this, yAxis = this.yAxis, options = series.options, inverted = this.chart.inverted, attr = {}, translateProp = inverted ? 'translateX' : 'translateY', translateStart, translatedThreshold;
if (init) {
attr.scaleY = 0.001;
translatedThreshold = clamp(yAxis.toPixels(options.threshold), yAxis.pos, yAxis.pos + yAxis.len);
if (inverted) {
attr.translateX = translatedThreshold - yAxis.len;
}
else {
attr.translateY = translatedThreshold;
}
// apply finnal clipping (used in Highstock) (#7083)
// animation is done by scaleY, so cliping is for panes
if (series.clipBox) {
series.setClip();
}
series.group.attr(attr);
}
else { // run the animation
translateStart = series.group.attr(translateProp);
series.group.animate({ scaleY: 1 }, extend(animObject(series.options.animation), {
// Do the scale synchronously to ensure smooth
// updating (#5030, #7228)
step: function (val, fx) {
if (series.group) {
attr[translateProp] = translateStart +
fx.pos * (yAxis.pos - translateStart);
series.group.attr(attr);
}
}
}));
}
},
/**
* Remove this series from the chart
*
* @private
* @function Highcharts.seriesTypes.column#remove
*/
remove: function () {
var series = this, chart = series.chart;
// column and bar series affects other series of the same type
// as they are either stacked or grouped
if (chart.hasRendered) {
chart.series.forEach(function (otherSeries) {
if (otherSeries.type === series.type) {
otherSeries.isDirty = true;
}
});
}
Series.prototype.remove.apply(series, arguments);
}
});
/* eslint-enable valid-jsdoc */
/**
* A `column` series. If the [type](#series.column.type) option is
* not specified, it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.column
* @excluding connectNulls, dataParser, dataURL, gapSize, gapUnit, linecap,
* lineWidth, marker, connectEnds, step
* @product highcharts highstock
* @apioption series.column
*/
/**
* An array of data points for the series. For the `column` series type,
* points can be given in the following ways:
*
* 1. An array of numerical values. In this case, the numerical values will be
* interpreted as `y` options. The `x` values will be automatically
* calculated, either starting at 0 and incremented by 1, or from
* `pointStart` and `pointInterval` given in the series options. If the axis
* has categories, these will be used. Example:
* ```js
* data: [0, 5, 3, 5]
* ```
*
* 2. An array of arrays with 2 values. In this case, the values correspond to
* `x,y`. If the first value is a string, it is applied as the name of the
* point, and the `x` value is inferred.
* ```js
* data: [
* [0, 6],
* [1, 2],
* [2, 6]
* ]
* ```
*
* 3. An array of objects with named values. The following snippet shows only a
* few settings, see the complete options set below. If the total number of
* data points exceeds the series'
* [turboThreshold](#series.column.turboThreshold), this option is not
* available.
* ```js
* data: [{
* x: 1,
* y: 9,
* name: "Point2",
* color: "#00FF00"
* }, {
* x: 1,
* y: 6,
* name: "Point1",
* color: "#FF00FF"
* }]
* ```
*
* @sample {highcharts} highcharts/chart/reflow-true/
* Numerical values
* @sample {highcharts} highcharts/series/data-array-of-arrays/
* Arrays of numeric x and y
* @sample {highcharts} highcharts/series/data-array-of-arrays-datetime/
* Arrays of datetime x and y
* @sample {highcharts} highcharts/series/data-array-of-name-value/
* Arrays of point.name and y
* @sample {highcharts} highcharts/series/data-array-of-objects/
* Config objects
*
* @type {Array<number|Array<(number|string),(number|null)>|null|*>}
* @extends series.line.data
* @excluding marker
* @product highcharts highstock
* @apioption series.column.data
*/
/**
* The color of the border surrounding the column or bar.
*
* In styled mode, the border stroke can be set with the `.highcharts-point`
* rule.
*
* @sample {highcharts} highcharts/plotoptions/column-bordercolor/
* Dark gray border
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @product highcharts highstock
* @apioption series.column.data.borderColor
*/
/**
* The width of the border surrounding the column or bar.
*
* In styled mode, the stroke width can be set with the `.highcharts-point`
* rule.
*
* @sample {highcharts} highcharts/plotoptions/column-borderwidth/
* 2px black border
*
* @type {number}
* @product highcharts highstock
* @apioption series.column.data.borderWidth
*/
/**
* A name for the dash style to use for the column or bar. Overrides
* dashStyle on the series.
*
* In styled mode, the stroke dash-array can be set with the same classes as
* listed under [data.color](#series.column.data.color).
*
* @see [series.pointWidth](#plotOptions.column.dashStyle)
*
* @type {Highcharts.DashStyleValue}
* @apioption series.column.data.dashStyle
*/
/**
* A pixel value specifying a fixed width for the column or bar. Overrides
* pointWidth on the series.
*
* @see [series.pointWidth](#plotOptions.column.pointWidth)
*
* @type {number}
* @apioption series.column.data.pointWidth
*/
/**
* @excluding halo, lineWidth, lineWidthPlus, marker
* @product highcharts highstock
* @apioption series.column.states.hover
*/
/**
* @excluding halo, lineWidth, lineWidthPlus, marker
* @product highcharts highstock
* @apioption series.column.states.select
*/
''; // includes above doclets in transpilat

View File

@@ -0,0 +1,897 @@
/* *
*
* (c) 2010-2020 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from './Globals.js';
/**
* @typedef {"average"|"averages"|"open"|"high"|"low"|"close"|"sum"} Highcharts.DataGroupingApproximationValue
*/
/**
* @interface Highcharts.DataGroupingInfoObject
*/ /**
* @name Highcharts.DataGroupingInfoObject#length
* @type {number}
*/ /**
* @name Highcharts.DataGroupingInfoObject#options
* @type {Highcharts.SeriesOptionsType|undefined}
*/ /**
* @name Highcharts.DataGroupingInfoObject#start
* @type {number}
*/
''; // detach doclets above
import Point from './Point.js';
import Tooltip from './Tooltip.js';
import U from './Utilities.js';
var addEvent = U.addEvent, arrayMax = U.arrayMax, arrayMin = U.arrayMin, correctFloat = U.correctFloat, defined = U.defined, error = U.error, extend = U.extend, format = U.format, isNumber = U.isNumber, merge = U.merge, pick = U.pick;
import './Axis.js';
import './Series.js';
var Axis = H.Axis, defaultPlotOptions = H.defaultPlotOptions, Series = H.Series;
/* ************************************************************************** *
* Start data grouping module *
* ************************************************************************** */
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* Define the available approximation types. The data grouping
* approximations takes an array or numbers as the first parameter. In case
* of ohlc, four arrays are sent in as four parameters. Each array consists
* only of numbers. In case null values belong to the group, the property
* .hasNulls will be set to true on the array.
*
* @product highstock
*
* @private
* @name Highcharts.approximations
* @type {Highcharts.Dictionary<Function>}
*/
var approximations = H.approximations = {
sum: function (arr) {
var len = arr.length, ret;
// 1. it consists of nulls exclusive
if (!len && arr.hasNulls) {
ret = null;
// 2. it has a length and real values
}
else if (len) {
ret = 0;
while (len--) {
ret += arr[len];
}
}
// 3. it has zero length, so just return undefined
// => doNothing()
return ret;
},
average: function (arr) {
var len = arr.length, ret = approximations.sum(arr);
// If we have a number, return it divided by the length. If not,
// return null or undefined based on what the sum method finds.
if (isNumber(ret) && len) {
ret = correctFloat(ret / len);
}
return ret;
},
// The same as average, but for series with multiple values, like area
// ranges.
averages: function () {
var ret = [];
[].forEach.call(arguments, function (arr) {
ret.push(approximations.average(arr));
});
// Return undefined when first elem. is undefined and let
// sum method handle null (#7377)
return typeof ret[0] === 'undefined' ? void 0 : ret;
},
open: function (arr) {
return arr.length ? arr[0] : (arr.hasNulls ? null : void 0);
},
high: function (arr) {
return arr.length ?
arrayMax(arr) :
(arr.hasNulls ? null : void 0);
},
low: function (arr) {
return arr.length ?
arrayMin(arr) :
(arr.hasNulls ? null : void 0);
},
close: function (arr) {
return arr.length ?
arr[arr.length - 1] :
(arr.hasNulls ? null : void 0);
},
// ohlc and range are special cases where a multidimensional array is
// input and an array is output
ohlc: function (open, high, low, close) {
open = approximations.open(open);
high = approximations.high(high);
low = approximations.low(low);
close = approximations.close(close);
if (isNumber(open) ||
isNumber(high) ||
isNumber(low) ||
isNumber(close)) {
return [open, high, low, close];
}
// else, return is undefined
},
range: function (low, high) {
low = approximations.low(low);
high = approximations.high(high);
if (isNumber(low) || isNumber(high)) {
return [low, high];
}
if (low === null && high === null) {
return null;
}
// else, return is undefined
}
};
var groupData = function (xData, yData, groupPositions, approximation) {
var series = this, data = series.data, dataOptions = series.options && series.options.data, groupedXData = [], groupedYData = [], groupMap = [], dataLength = xData.length, pointX, pointY, groupedY,
// when grouping the fake extended axis for panning,
// we don't need to consider y
handleYData = !!yData, values = [], approximationFn, pointArrayMap = series.pointArrayMap, pointArrayMapLength = pointArrayMap && pointArrayMap.length, extendedPointArrayMap = ['x'].concat(pointArrayMap || ['y']), pos = 0, start = 0, valuesLen, i, j;
/**
* @private
*/
function getApproximation(approx) {
if (typeof approx === 'function') {
return approx;
}
if (approximations[approx]) {
return approximations[approx];
}
return approximations[(series.getDGApproximation && series.getDGApproximation()) ||
'average'];
}
approximationFn = getApproximation(approximation);
// Calculate values array size from pointArrayMap length
if (pointArrayMapLength) {
pointArrayMap.forEach(function () {
values.push([]);
});
}
else {
values.push([]);
}
valuesLen = pointArrayMapLength || 1;
// Start with the first point within the X axis range (#2696)
for (i = 0; i <= dataLength; i++) {
if (xData[i] >= groupPositions[0]) {
break;
}
}
for (i; i <= dataLength; i++) {
// when a new group is entered, summarize and initialize
// the previous group
while ((typeof groupPositions[pos + 1] !== 'undefined' &&
xData[i] >= groupPositions[pos + 1]) ||
i === dataLength) { // get the last group
// get group x and y
pointX = groupPositions[pos];
series.dataGroupInfo = {
start: series.cropStart + start,
length: values[0].length
};
groupedY = approximationFn.apply(series, values);
// By default, let options of the first grouped point be passed over
// to the grouped point. This allows preserving properties like
// `name` and `color` or custom properties. Implementers can
// override this from the approximation function, where they can
// write custom options to `this.dataGroupInfo.options`.
if (series.pointClass && !defined(series.dataGroupInfo.options)) {
// Convert numbers and arrays into objects
series.dataGroupInfo.options = merge(series.pointClass.prototype
.optionsToObject.call({ series: series }, series.options.data[series.cropStart + start]));
// Make sure the raw data (x, y, open, high etc) is not copied
// over and overwriting approximated data.
extendedPointArrayMap.forEach(function (key) {
delete series.dataGroupInfo.options[key];
});
}
// push the grouped data
if (typeof groupedY !== 'undefined') {
groupedXData.push(pointX);
groupedYData.push(groupedY);
groupMap.push(series.dataGroupInfo);
}
// reset the aggregate arrays
start = i;
for (j = 0; j < valuesLen; j++) {
values[j].length = 0; // faster than values[j] = []
values[j].hasNulls = false;
}
// Advance on the group positions
pos += 1;
// don't loop beyond the last group
if (i === dataLength) {
break;
}
}
// break out
if (i === dataLength) {
break;
}
// for each raw data point, push it to an array that contains all values
// for this specific group
if (pointArrayMap) {
var index = series.cropStart + i, point = (data && data[index]) ||
series.pointClass.prototype.applyOptions.apply({
series: series
}, [dataOptions[index]]), val;
for (j = 0; j < pointArrayMapLength; j++) {
val = point[pointArrayMap[j]];
if (isNumber(val)) {
values[j].push(val);
}
else if (val === null) {
values[j].hasNulls = true;
}
}
}
else {
pointY = handleYData ? yData[i] : null;
if (isNumber(pointY)) {
values[0].push(pointY);
}
else if (pointY === null) {
values[0].hasNulls = true;
}
}
}
return {
groupedXData: groupedXData,
groupedYData: groupedYData,
groupMap: groupMap
};
};
var dataGrouping = {
approximations: approximations,
groupData: groupData
};
// -----------------------------------------------------------------------------
// The following code applies to implementation of data grouping on a Series
var seriesProto = Series.prototype, baseProcessData = seriesProto.processData, baseGeneratePoints = seriesProto.generatePoints,
/** @ignore */
commonOptions = {
// enabled: null, // (true for stock charts, false for basic),
// forced: undefined,
groupPixelWidth: 2,
// the first one is the point or start value, the second is the start
// value if we're dealing with range, the third one is the end value if
// dealing with a range
dateTimeLabelFormats: {
millisecond: [
'%A, %b %e, %H:%M:%S.%L',
'%A, %b %e, %H:%M:%S.%L',
'-%H:%M:%S.%L'
],
second: [
'%A, %b %e, %H:%M:%S',
'%A, %b %e, %H:%M:%S',
'-%H:%M:%S'
],
minute: [
'%A, %b %e, %H:%M',
'%A, %b %e, %H:%M',
'-%H:%M'
],
hour: [
'%A, %b %e, %H:%M',
'%A, %b %e, %H:%M',
'-%H:%M'
],
day: [
'%A, %b %e, %Y',
'%A, %b %e',
'-%A, %b %e, %Y'
],
week: [
'Week from %A, %b %e, %Y',
'%A, %b %e',
'-%A, %b %e, %Y'
],
month: [
'%B %Y',
'%B',
'-%B %Y'
],
year: [
'%Y',
'%Y',
'-%Y'
]
}
// smoothed = false, // enable this for navigator series only
}, specificOptions = {
line: {},
spline: {},
area: {},
areaspline: {},
arearange: {},
column: {
groupPixelWidth: 10
},
columnrange: {
groupPixelWidth: 10
},
candlestick: {
groupPixelWidth: 10
},
ohlc: {
groupPixelWidth: 5
}
},
// units are defined in a separate array to allow complete overriding in
// case of a user option
defaultDataGroupingUnits = H.defaultDataGroupingUnits = [
[
'millisecond',
[1, 2, 5, 10, 20, 25, 50, 100, 200, 500] // allowed multiples
], [
'second',
[1, 2, 5, 10, 15, 30]
], [
'minute',
[1, 2, 5, 10, 15, 30]
], [
'hour',
[1, 2, 3, 4, 6, 8, 12]
], [
'day',
[1]
], [
'week',
[1]
], [
'month',
[1, 3, 6]
], [
'year',
null
]
];
// Set default approximations to the prototypes if present. Properties are
// inherited down. Can be overridden for individual series types.
seriesProto.getDGApproximation = function () {
if (this.is('arearange')) {
return 'range';
}
if (this.is('ohlc')) {
return 'ohlc';
}
if (this.is('column')) {
return 'sum';
}
return 'average';
};
/**
* Takes parallel arrays of x and y data and groups the data into intervals
* defined by groupPositions, a collection of starting x values for each group.
*
* @private
* @function Highcharts.Series#groupData
*
* @param {Array<number>} xData
*
* @param {Array<number>|Array<Array<number>>} yData
*
* @param {boolean} groupPositions
*
* @param {string|Function} approximation
*
* @return {void}
*/
seriesProto.groupData = groupData;
// Extend the basic processData method, that crops the data to the current zoom
// range, with data grouping logic.
seriesProto.processData = function () {
var series = this, chart = series.chart, options = series.options, dataGroupingOptions = options.dataGrouping, groupingEnabled = series.allowDG !== false && dataGroupingOptions &&
pick(dataGroupingOptions.enabled, chart.options.isStock), visible = (series.visible || !chart.options.chart.ignoreHiddenSeries), hasGroupedData, skip, lastDataGrouping = this.currentDataGrouping, currentDataGrouping, croppedData, revertRequireSorting = false;
// Run base method
series.forceCrop = groupingEnabled; // #334
series.groupPixelWidth = null; // #2110
series.hasProcessed = true; // #2692
// Data needs to be sorted for dataGrouping
if (groupingEnabled && !series.requireSorting) {
series.requireSorting = revertRequireSorting = true;
}
// Skip if processData returns false or if grouping is disabled (in that
// order)
skip = (baseProcessData.apply(series, arguments) === false ||
!groupingEnabled);
// Revert original requireSorting value if changed
if (revertRequireSorting) {
series.requireSorting = false;
}
if (!skip) {
series.destroyGroupedData();
var i, processedXData = dataGroupingOptions.groupAll ?
series.xData :
series.processedXData, processedYData = dataGroupingOptions.groupAll ?
series.yData :
series.processedYData, plotSizeX = chart.plotSizeX, xAxis = series.xAxis, ordinal = xAxis.options.ordinal, groupPixelWidth = series.groupPixelWidth =
xAxis.getGroupPixelWidth && xAxis.getGroupPixelWidth();
// Execute grouping if the amount of points is greater than the limit
// defined in groupPixelWidth
if (groupPixelWidth) {
hasGroupedData = true;
// Force recreation of point instances in series.translate, #5699
series.isDirty = true;
series.points = null; // #6709
var extremes = xAxis.getExtremes(), xMin = extremes.min, xMax = extremes.max, groupIntervalFactor = (ordinal &&
xAxis.getGroupIntervalFactor(xMin, xMax, series)) || 1, interval = (groupPixelWidth * (xMax - xMin) / plotSizeX) *
groupIntervalFactor, groupPositions = xAxis.getTimeTicks(xAxis.normalizeTimeTickInterval(interval, dataGroupingOptions.units ||
defaultDataGroupingUnits),
// Processed data may extend beyond axis (#4907)
Math.min(xMin, processedXData[0]), Math.max(xMax, processedXData[processedXData.length - 1]), xAxis.options.startOfWeek, processedXData, series.closestPointRange), groupedData = seriesProto.groupData.apply(series, [
processedXData,
processedYData,
groupPositions,
dataGroupingOptions.approximation
]), groupedXData = groupedData.groupedXData, groupedYData = groupedData.groupedYData, gapSize = 0;
// Prevent the smoothed data to spill out left and right, and make
// sure data is not shifted to the left
if (dataGroupingOptions.smoothed && groupedXData.length) {
i = groupedXData.length - 1;
groupedXData[i] = Math.min(groupedXData[i], xMax);
while (i-- && i > 0) {
groupedXData[i] += interval / 2;
}
groupedXData[0] = Math.max(groupedXData[0], xMin);
}
// Record what data grouping values were used
for (i = 1; i < groupPositions.length; i++) {
// The grouped gapSize needs to be the largest distance between
// the group to capture varying group sizes like months or DST
// crossing (#10000). Also check that the gap is not at the
// start of a segment.
if (!groupPositions.info.segmentStarts ||
groupPositions.info.segmentStarts.indexOf(i) === -1) {
gapSize = Math.max(groupPositions[i] - groupPositions[i - 1], gapSize);
}
}
currentDataGrouping = groupPositions.info;
currentDataGrouping.gapSize = gapSize;
series.closestPointRange = groupPositions.info.totalRange;
series.groupMap = groupedData.groupMap;
// Make sure the X axis extends to show the first group (#2533)
// But only for visible series (#5493, #6393)
if (defined(groupedXData[0]) &&
groupedXData[0] < xAxis.min &&
visible) {
if ((!defined(xAxis.options.min) &&
xAxis.min <= xAxis.dataMin) ||
xAxis.min === xAxis.dataMin) {
xAxis.min = Math.min(groupedXData[0], xAxis.min);
}
xAxis.dataMin = Math.min(groupedXData[0], xAxis.dataMin);
}
// We calculated all group positions but we should render
// only the ones within the visible range
if (dataGroupingOptions.groupAll) {
croppedData = series.cropData(groupedXData, groupedYData, xAxis.min, xAxis.max, 1 // Ordinal xAxis will remove left-most points otherwise
);
groupedXData = croppedData.xData;
groupedYData = croppedData.yData;
}
// Set series props
series.processedXData = groupedXData;
series.processedYData = groupedYData;
}
else {
series.groupMap = null;
}
series.hasGroupedData = hasGroupedData;
series.currentDataGrouping = currentDataGrouping;
series.preventGraphAnimation =
(lastDataGrouping && lastDataGrouping.totalRange) !==
(currentDataGrouping && currentDataGrouping.totalRange);
}
};
// Destroy the grouped data points. #622, #740
seriesProto.destroyGroupedData = function () {
// Clear previous groups
if (this.groupedData) {
this.groupedData.forEach(function (point, i) {
if (point) {
this.groupedData[i] = point.destroy ?
point.destroy() : null;
}
}, this);
// Clears all:
// - `this.groupedData`
// - `this.points`
// - `preserve` object in series.update()
this.groupedData.length = 0;
}
};
// Override the generatePoints method by adding a reference to grouped data
seriesProto.generatePoints = function () {
baseGeneratePoints.apply(this);
// Record grouped data in order to let it be destroyed the next time
// processData runs
this.destroyGroupedData(); // #622
this.groupedData = this.hasGroupedData ? this.points : null;
};
// Override point prototype to throw a warning when trying to update grouped
// points.
addEvent(Point, 'update', function () {
if (this.dataGroup) {
error(24, false, this.series.chart);
return false;
}
});
// Extend the original method, make the tooltip's header reflect the grouped
// range.
addEvent(Tooltip, 'headerFormatter', function (e) {
var tooltip = this, chart = this.chart, time = chart.time, labelConfig = e.labelConfig, series = labelConfig.series, options = series.options, tooltipOptions = series.tooltipOptions, dataGroupingOptions = options.dataGrouping, xDateFormat = tooltipOptions.xDateFormat, xDateFormatEnd, xAxis = series.xAxis, currentDataGrouping, dateTimeLabelFormats, labelFormats, formattedKey, formatString = tooltipOptions[(e.isFooter ? 'footer' : 'header') + 'Format'];
// apply only to grouped series
if (xAxis &&
xAxis.options.type === 'datetime' &&
dataGroupingOptions &&
isNumber(labelConfig.key)) {
// set variables
currentDataGrouping = series.currentDataGrouping;
dateTimeLabelFormats = dataGroupingOptions.dateTimeLabelFormats ||
// Fallback to commonOptions (#9693)
commonOptions.dateTimeLabelFormats;
// if we have grouped data, use the grouping information to get the
// right format
if (currentDataGrouping) {
labelFormats =
dateTimeLabelFormats[currentDataGrouping.unitName];
if (currentDataGrouping.count === 1) {
xDateFormat = labelFormats[0];
}
else {
xDateFormat = labelFormats[1];
xDateFormatEnd = labelFormats[2];
}
// if not grouped, and we don't have set the xDateFormat option, get the
// best fit, so if the least distance between points is one minute, show
// it, but if the least distance is one day, skip hours and minutes etc.
}
else if (!xDateFormat && dateTimeLabelFormats) {
xDateFormat = tooltip.getXDateFormat(labelConfig, tooltipOptions, xAxis);
}
// now format the key
formattedKey = time.dateFormat(xDateFormat, labelConfig.key);
if (xDateFormatEnd) {
formattedKey += time.dateFormat(xDateFormatEnd, labelConfig.key + currentDataGrouping.totalRange - 1);
}
// Replace default header style with class name
if (series.chart.styledMode) {
formatString = this.styledModeFormat(formatString);
}
// return the replaced format
e.text = format(formatString, {
point: extend(labelConfig.point, { key: formattedKey }),
series: series
}, chart);
e.preventDefault();
}
});
// Destroy grouped data on series destroy
addEvent(Series, 'destroy', seriesProto.destroyGroupedData);
// Handle default options for data grouping. This must be set at runtime because
// some series types are defined after this.
addEvent(Series, 'afterSetOptions', function (e) {
var options = e.options, type = this.type, plotOptions = this.chart.options.plotOptions, defaultOptions = defaultPlotOptions[type].dataGrouping,
// External series, for example technical indicators should also
// inherit commonOptions which are not available outside this module
baseOptions = this.useCommonDataGrouping && commonOptions;
if (specificOptions[type] || baseOptions) { // #1284
if (!defaultOptions) {
defaultOptions = merge(commonOptions, specificOptions[type]);
}
options.dataGrouping = merge(baseOptions, defaultOptions, plotOptions.series && plotOptions.series.dataGrouping, // #1228
// Set by the StockChart constructor:
plotOptions[type].dataGrouping, this.userOptions.dataGrouping);
}
});
// When resetting the scale reset the hasProccessed flag to avoid taking
// previous data grouping of neighbour series into accound when determining
// group pixel width (#2692).
addEvent(Axis, 'afterSetScale', function () {
this.series.forEach(function (series) {
series.hasProcessed = false;
});
});
// Get the data grouping pixel width based on the greatest defined individual
// width of the axis' series, and if whether one of the axes need grouping.
Axis.prototype.getGroupPixelWidth = function () {
var series = this.series, len = series.length, i, groupPixelWidth = 0, doGrouping = false, dataLength, dgOptions;
// If multiple series are compared on the same x axis, give them the same
// group pixel width (#334)
i = len;
while (i--) {
dgOptions = series[i].options.dataGrouping;
if (dgOptions) {
groupPixelWidth = Math.max(groupPixelWidth,
// Fallback to commonOptions (#9693)
pick(dgOptions.groupPixelWidth, commonOptions.groupPixelWidth));
}
}
// If one of the series needs grouping, apply it to all (#1634)
i = len;
while (i--) {
dgOptions = series[i].options.dataGrouping;
if (dgOptions && series[i].hasProcessed) { // #2692
dataLength = (series[i].processedXData || series[i].data).length;
// Execute grouping if the amount of points is greater than the
// limit defined in groupPixelWidth
if (series[i].groupPixelWidth ||
dataLength >
(this.chart.plotSizeX / groupPixelWidth) ||
(dataLength && dgOptions.forced)) {
doGrouping = true;
}
}
}
return doGrouping ? groupPixelWidth : 0;
};
/**
* Highstock only. Force data grouping on all the axis' series.
*
* @product highstock
*
* @function Highcharts.Axis#setDataGrouping
*
* @param {boolean|Highcharts.DataGroupingOptionsObject} [dataGrouping]
* A `dataGrouping` configuration. Use `false` to disable data grouping
* dynamically.
*
* @param {boolean} [redraw=true]
* Whether to redraw the chart or wait for a later call to
* {@link Chart#redraw}.
*
* @return {void}
*/
Axis.prototype.setDataGrouping = function (dataGrouping, redraw) {
var i;
redraw = pick(redraw, true);
if (!dataGrouping) {
dataGrouping = {
forced: false,
units: null
};
}
// Axis is instantiated, update all series
if (this instanceof Axis) {
i = this.series.length;
while (i--) {
this.series[i].update({
dataGrouping: dataGrouping
}, false);
}
// Axis not yet instanciated, alter series options
}
else {
this.chart.options.series.forEach(function (seriesOptions) {
seriesOptions.dataGrouping = dataGrouping;
}, false);
}
// Clear ordinal slope, so we won't accidentaly use the old one (#7827)
this.ordinalSlope = null;
if (redraw) {
this.chart.redraw();
}
};
H.dataGrouping = dataGrouping;
export default dataGrouping;
/* eslint-enable no-invalid-this, valid-jsdoc */
/**
* Data grouping is the concept of sampling the data values into larger
* blocks in order to ease readability and increase performance of the
* JavaScript charts. Highstock by default applies data grouping when
* the points become closer than a certain pixel value, determined by
* the `groupPixelWidth` option.
*
* If data grouping is applied, the grouping information of grouped
* points can be read from the [Point.dataGroup](
* /class-reference/Highcharts.Point#dataGroup). If point options other than
* the data itself are set, for example `name` or `color` or custom properties,
* the grouping logic doesn't know how to group it. In this case the options of
* the first point instance are copied over to the group point. This can be
* altered through a custom `approximation` callback function.
*
* @declare Highcharts.DataGroupingOptionsObject
* @product highstock
* @requires modules/datagrouping
* @apioption plotOptions.series.dataGrouping
*/
/**
* The method of approximation inside a group. When for example 30 days
* are grouped into one month, this determines what value should represent
* the group. Possible values are "average", "averages", "open", "high",
* "low", "close" and "sum". For OHLC and candlestick series the approximation
* is "ohlc" by default, which finds the open, high, low and close values
* within all the grouped data. For ranges, the approximation is "range",
* which finds the low and high values. For multi-dimensional data,
* like ranges and OHLC, "averages" will compute the average for each
* dimension.
*
* Custom aggregate methods can be added by assigning a callback function
* as the approximation. This function takes a numeric array as the
* argument and should return a single numeric value or `null`. Note
* that the numeric array will never contain null values, only true
* numbers. Instead, if null values are present in the raw data, the
* numeric array will have an `.hasNulls` property set to `true`. For
* single-value data sets the data is available in the first argument
* of the callback function. For OHLC data sets, all the open values
* are in the first argument, all high values in the second etc.
*
* Since v4.2.7, grouping meta data is available in the approximation
* callback from `this.dataGroupInfo`. It can be used to extract information
* from the raw data.
*
* Defaults to `average` for line-type series, `sum` for columns, `range`
* for range series and `ohlc` for OHLC and candlestick.
*
* @sample {highstock} stock/plotoptions/series-datagrouping-approximation
* Approximation callback with custom data
*
* @type {Highcharts.DataGroupingApproximationValue|Function}
* @product highstock
* @apioption plotOptions.series.dataGrouping.approximation
*/
/**
* Datetime formats for the header of the tooltip in a stock chart.
* The format can vary within a chart depending on the currently selected
* time range and the current data grouping.
*
* The default formats are:
* ```js
* {
* millisecond: [
* '%A, %b %e, %H:%M:%S.%L', '%A, %b %e, %H:%M:%S.%L', '-%H:%M:%S.%L'
* ],
* second: ['%A, %b %e, %H:%M:%S', '%A, %b %e, %H:%M:%S', '-%H:%M:%S'],
* minute: ['%A, %b %e, %H:%M', '%A, %b %e, %H:%M', '-%H:%M'],
* hour: ['%A, %b %e, %H:%M', '%A, %b %e, %H:%M', '-%H:%M'],
* day: ['%A, %b %e, %Y', '%A, %b %e', '-%A, %b %e, %Y'],
* week: ['Week from %A, %b %e, %Y', '%A, %b %e', '-%A, %b %e, %Y'],
* month: ['%B %Y', '%B', '-%B %Y'],
* year: ['%Y', '%Y', '-%Y']
* }
* ```
*
* For each of these array definitions, the first item is the format
* used when the active time span is one unit. For instance, if the
* current data applies to one week, the first item of the week array
* is used. The second and third items are used when the active time
* span is more than two units. For instance, if the current data applies
* to two weeks, the second and third item of the week array are used,
* and applied to the start and end date of the time span.
*
* @type {object}
* @product highstock
* @apioption plotOptions.series.dataGrouping.dateTimeLabelFormats
*/
/**
* Enable or disable data grouping.
*
* @type {boolean}
* @default true
* @product highstock
* @apioption plotOptions.series.dataGrouping.enabled
*/
/**
* When data grouping is forced, it runs no matter how small the intervals
* are. This can be handy for example when the sum should be calculated
* for values appearing at random times within each hour.
*
* @type {boolean}
* @default false
* @product highstock
* @apioption plotOptions.series.dataGrouping.forced
*/
/**
* The approximate pixel width of each group. If for example a series
* with 30 points is displayed over a 600 pixel wide plot area, no grouping
* is performed. If however the series contains so many points that
* the spacing is less than the groupPixelWidth, Highcharts will try
* to group it into appropriate groups so that each is more or less
* two pixels wide. If multiple series with different group pixel widths
* are drawn on the same x axis, all series will take the greatest width.
* For example, line series have 2px default group width, while column
* series have 10px. If combined, both the line and the column will
* have 10px by default.
*
* @type {number}
* @default 2
* @product highstock
* @apioption plotOptions.series.dataGrouping.groupPixelWidth
*/
/**
* By default only points within the visible range are grouped. Enabling this
* option will force data grouping to calculate all grouped points for a given
* dataset. That option prevents for example a column series from calculating
* a grouped point partially. The effect is similar to
* [Series.getExtremesFromAll](#plotOptions.series.getExtremesFromAll) but does
* not affect yAxis extremes.
*
* @sample {highstock} stock/plotoptions/series-datagrouping-groupall/
* Two series with the same data but different groupAll setting
*
* @type {boolean}
* @default false
* @since 6.1.0
* @product highstock
* @apioption plotOptions.series.dataGrouping.groupAll
*/
/**
* Normally, a group is indexed by the start of that group, so for example
* when 30 daily values are grouped into one month, that month's x value
* will be the 1st of the month. This apparently shifts the data to
* the left. When the smoothed option is true, this is compensated for.
* The data is shifted to the middle of the group, and min and max
* values are preserved. Internally, this is used in the Navigator series.
*
* @type {boolean}
* @default false
* @product highstock
* @apioption plotOptions.series.dataGrouping.smoothed
*/
/**
* An array determining what time intervals the data is allowed to be
* grouped to. Each array item is an array where the first value is
* the time unit and the second value another array of allowed multiples.
*
* Defaults to:
* ```js
* units: [[
* 'millisecond', // unit name
* [1, 2, 5, 10, 20, 25, 50, 100, 200, 500] // allowed multiples
* ], [
* 'second',
* [1, 2, 5, 10, 15, 30]
* ], [
* 'minute',
* [1, 2, 5, 10, 15, 30]
* ], [
* 'hour',
* [1, 2, 3, 4, 6, 8, 12]
* ], [
* 'day',
* [1]
* ], [
* 'week',
* [1]
* ], [
* 'month',
* [1, 3, 6]
* ], [
* 'year',
* null
* ]]
* ```
*
* @type {Array<Array<string,(Array<number>|null)>>}
* @product highstock
* @apioption plotOptions.series.dataGrouping.units
*/
/**
* The approximate pixel width of each group. If for example a series
* with 30 points is displayed over a 600 pixel wide plot area, no grouping
* is performed. If however the series contains so many points that
* the spacing is less than the groupPixelWidth, Highcharts will try
* to group it into appropriate groups so that each is more or less
* two pixels wide. Defaults to `10`.
*
* @sample {highstock} stock/plotoptions/series-datagrouping-grouppixelwidth/
* Two series with the same data density but different groupPixelWidth
*
* @type {number}
* @default 10
* @product highstock
* @apioption plotOptions.column.dataGrouping.groupPixelWidth
*/
''; // required by JSDoc parsing

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,112 @@
/* *
*
* (c) 2010-2020 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from './Globals.js';
import U from './Utilities.js';
var getMagnitude = U.getMagnitude, normalizeTickInterval = U.normalizeTickInterval, timeUnits = U.timeUnits;
var Axis = H.Axis;
/* eslint-disable valid-jsdoc */
/**
* Set the tick positions to a time unit that makes sense, for example
* on the first of each month or on every Monday. Return an array
* with the time positions. Used in datetime axes as well as for grouping
* data on a datetime axis.
*
* @private
* @function Highcharts.Axis#getTimeTicks
*
* @param {Highcharts.DateTimeAxisNormalizedObject} normalizedInterval
* The interval in axis values (ms) and thecount
*
* @param {number} min
* The minimum in axis values
*
* @param {number} max
* The maximum in axis values
*
* @param {number} startOfWeek
*
* @return {Highcharts.AxisTickPositionsArray}
*/
Axis.prototype.getTimeTicks = function () {
return this.chart.time.getTimeTicks.apply(this.chart.time, arguments);
};
/**
* Get a normalized tick interval for dates. Returns a configuration object with
* unit range (interval), count and name. Used to prepare data for getTimeTicks.
* Previously this logic was part of getTimeTicks, but as getTimeTicks now runs
* of segments in stock charts, the normalizing logic was extracted in order to
* prevent it for running over again for each segment having the same interval.
* #662, #697.
*
* @private
* @function Highcharts.Axis#normalizeTimeTickInterval
* @param {number} tickInterval
* @param {Array<Array<string,(Array<number>|null)>>} [unitsOption]
* @return {Highcharts.DateTimeAxisNormalizedObject}
*/
Axis.prototype.normalizeTimeTickInterval = function (tickInterval, unitsOption) {
var units = unitsOption || [[
'millisecond',
[1, 2, 5, 10, 20, 25, 50, 100, 200, 500] // allowed multiples
], [
'second',
[1, 2, 5, 10, 15, 30]
], [
'minute',
[1, 2, 5, 10, 15, 30]
], [
'hour',
[1, 2, 3, 4, 6, 8, 12]
], [
'day',
[1, 2]
], [
'week',
[1, 2]
], [
'month',
[1, 2, 3, 4, 6]
], [
'year',
null
]], unit = units[units.length - 1], // default unit is years
interval = timeUnits[unit[0]], multiples = unit[1], count, i;
// loop through the units to find the one that best fits the tickInterval
for (i = 0; i < units.length; i++) {
unit = units[i];
interval = timeUnits[unit[0]];
multiples = unit[1];
if (units[i + 1]) {
// lessThan is in the middle between the highest multiple and the
// next unit.
var lessThan = (interval *
multiples[multiples.length - 1] +
timeUnits[units[i + 1][0]]) / 2;
// break and keep the current unit
if (tickInterval <= lessThan) {
break;
}
}
}
// prevent 2.5 years intervals, though 25, 250 etc. are allowed
if (interval === timeUnits.year && tickInterval < 5 * interval) {
multiples = [1, 2, 5];
}
// get the count
count = normalizeTickInterval(tickInterval / interval, multiples, unit[0] === 'year' ?
Math.max(getMagnitude(tickInterval / interval), 1) : // #1913, #2360
1);
return {
unitRange: interval,
count: count,
unitName: unit[0]
};
};

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,633 @@
/* *
*
* (c) 2010-2020 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from './Globals.js';
/**
* @typedef {"circlepin"|"flag"|"squarepin"} Highcharts.FlagsShapeValue
*/
import U from './Utilities.js';
var addEvent = U.addEvent, defined = U.defined, isNumber = U.isNumber, merge = U.merge, objectEach = U.objectEach, seriesType = U.seriesType, wrap = U.wrap;
import './Series.js';
import './SvgRenderer.js';
import onSeriesMixin from '../mixins/on-series.js';
var noop = H.noop, Renderer = H.Renderer, Series = H.Series, SVGRenderer = H.SVGRenderer, TrackerMixin = H.TrackerMixin, VMLRenderer = H.VMLRenderer, symbols = SVGRenderer.prototype.symbols;
/**
* The Flags series.
*
* @private
* @class
* @name Highcharts.seriesTypes.flags
*
* @augments Highcharts.Series
*/
seriesType('flags', 'column'
/**
* Flags are used to mark events in stock charts. They can be added on the
* timeline, or attached to a specific series.
*
* @sample stock/demo/flags-general/
* Flags on a line series
*
* @extends plotOptions.column
* @excluding animation, borderColor, borderRadius, borderWidth,
* colorByPoint, dataGrouping, pointPadding, pointWidth,
* turboThreshold
* @product highstock
* @optionparent plotOptions.flags
*/
, {
/**
* In case the flag is placed on a series, on what point key to place
* it. Line and columns have one key, `y`. In range or OHLC-type series,
* however, the flag can optionally be placed on the `open`, `high`,
* `low` or `close` key.
*
* @sample {highstock} stock/plotoptions/flags-onkey/
* Range series, flag on high
*
* @type {string}
* @default y
* @since 4.2.2
* @product highstock
* @validvalue ["y", "open", "high", "low", "close"]
* @apioption plotOptions.flags.onKey
*/
/**
* The id of the series that the flags should be drawn on. If no id
* is given, the flags are drawn on the x axis.
*
* @sample {highstock} stock/plotoptions/flags/
* Flags on series and on x axis
*
* @type {string}
* @product highstock
* @apioption plotOptions.flags.onSeries
*/
pointRange: 0,
/**
* Whether the flags are allowed to overlap sideways. If `false`, the
* flags are moved sideways using an algorithm that seeks to place every
* flag as close as possible to its original position.
*
* @sample {highstock} stock/plotoptions/flags-allowoverlapx
* Allow sideways overlap
*
* @since 6.0.4
*/
allowOverlapX: false,
/**
* The shape of the marker. Can be one of "flag", "circlepin",
* "squarepin", or an image of the format `url(/path-to-image.jpg)`.
* Individual shapes can also be set for each point.
*
* @sample {highstock} stock/plotoptions/flags/
* Different shapes
*
* @type {Highcharts.FlagsShapeValue}
* @product highstock
*/
shape: 'flag',
/**
* When multiple flags in the same series fall on the same value, this
* number determines the vertical offset between them.
*
* @sample {highstock} stock/plotoptions/flags-stackdistance/
* A greater stack distance
*
* @product highstock
*/
stackDistance: 12,
/**
* Text alignment for the text inside the flag.
*
* @since 5.0.0
* @product highstock
* @validvalue ["left", "center", "right"]
*/
textAlign: 'center',
/**
* Specific tooltip options for flag series. Flag series tooltips are
* different from most other types in that a flag doesn't have a data
* value, so the tooltip rather displays the `text` option for each
* point.
*
* @extends plotOptions.series.tooltip
* @excluding changeDecimals, valueDecimals, valuePrefix, valueSuffix
* @product highstock
*/
tooltip: {
pointFormat: '{point.text}<br/>'
},
threshold: null,
/**
* The text to display on each flag. This can be defined on series
* level, or individually for each point. Defaults to `"A"`.
*
* @type {string}
* @default A
* @product highstock
* @apioption plotOptions.flags.title
*/
/**
* The y position of the top left corner of the flag relative to either
* the series (if onSeries is defined), or the x axis. Defaults to
* `-30`.
*
* @product highstock
*/
y: -30,
/**
* Whether to use HTML to render the flag texts. Using HTML allows for
* advanced formatting, images and reliable bi-directional text
* rendering. Note that exported images won't respect the HTML, and that
* HTML won't respect Z-index settings.
*
* @type {boolean}
* @default false
* @since 1.3
* @product highstock
* @apioption plotOptions.flags.useHTML
*/
/**
* Fixed width of the flag's shape. By default, width is autocalculated
* according to the flag's title.
*
* @sample {highstock} stock/demo/flags-shapes/
* Flags with fixed width
*
* @type {number}
* @product highstock
* @apioption plotOptions.flags.width
*/
/**
* Fixed height of the flag's shape. By default, height is
* autocalculated according to the flag's title.
*
* @type {number}
* @product highstock
* @apioption plotOptions.flags.height
*/
/**
* The fill color for the flags.
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @product highstock
*/
fillColor: '#ffffff',
/**
* The color of the line/border of the flag.
*
* In styled mode, the stroke is set in the
* `.highcharts-flag-series.highcharts-point` rule.
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @default #000000
* @product highstock
* @apioption plotOptions.flags.lineColor
*/
/**
* The pixel width of the flag's line/border.
*
* @product highstock
*/
lineWidth: 1,
states: {
/**
* @extends plotOptions.column.states.hover
* @product highstock
*/
hover: {
/**
* The color of the line/border of the flag.
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @product highstock
*/
lineColor: '#000000',
/**
* The fill or background color of the flag.
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @product highstock
*/
fillColor: '#ccd6eb'
}
},
/**
* The text styles of the flag.
*
* In styled mode, the styles are set in the
* `.highcharts-flag-series .highcharts-point` rule.
*
* @type {Highcharts.CSSObject}
* @default {"fontSize": "11px", "fontWeight": "bold"}
* @product highstock
*/
style: {
/** @ignore-option */
fontSize: '11px',
/** @ignore-option */
fontWeight: 'bold'
}
},
/**
* @lends seriesTypes.flags.prototype
*/
{
sorted: false,
noSharedTooltip: true,
allowDG: false,
takeOrdinalPosition: false,
trackerGroups: ['markerGroup'],
forceCrop: true,
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* Inherit the initialization from base Series.
*
* @private
* @borrows Highcharts.Series#init as Highcharts.seriesTypes.flags#init
*/
init: Series.prototype.init,
/**
* Get presentational attributes
*
* @private
* @function Highcharts.seriesTypes.flags#pointAttribs
*
* @param {Highcharts.Point} point
*
* @param {string} [state]
*
* @return {Highcharts.SVGAttributes}
*/
pointAttribs: function (point, state) {
var options = this.options, color = (point && point.color) || this.color, lineColor = options.lineColor, lineWidth = (point && point.lineWidth), fill = (point && point.fillColor) || options.fillColor;
if (state) {
fill = options.states[state].fillColor;
lineColor = options.states[state].lineColor;
lineWidth = options.states[state].lineWidth;
}
return {
fill: fill || color,
stroke: lineColor || color,
'stroke-width': lineWidth || options.lineWidth || 0
};
},
translate: onSeriesMixin.translate,
getPlotBox: onSeriesMixin.getPlotBox,
/**
* Draw the markers.
*
* @private
* @function Highcharts.seriesTypes.flags#drawPoints
* @return {void}
*/
drawPoints: function () {
var series = this, points = series.points, chart = series.chart, renderer = chart.renderer, plotX, plotY, inverted = chart.inverted, options = series.options, optionsY = options.y, shape, i, point, graphic, stackIndex, anchorY, attribs, outsideRight, yAxis = series.yAxis, boxesMap = {}, boxes = [], centered;
i = points.length;
while (i--) {
point = points[i];
outsideRight =
(inverted ? point.plotY : point.plotX) >
series.xAxis.len;
plotX = point.plotX;
stackIndex = point.stackIndex;
shape = point.options.shape || options.shape;
plotY = point.plotY;
if (typeof plotY !== 'undefined') {
plotY = point.plotY + optionsY -
(typeof stackIndex !== 'undefined' &&
(stackIndex * options.stackDistance));
}
// skip connectors for higher level stacked points
point.anchorX = stackIndex ? void 0 : point.plotX;
anchorY = stackIndex ? void 0 : point.plotY;
centered = shape !== 'flag';
graphic = point.graphic;
// Only draw the point if y is defined and the flag is within
// the visible area
if (typeof plotY !== 'undefined' &&
plotX >= 0 &&
!outsideRight) {
// Create the flag
if (!graphic) {
graphic = point.graphic = renderer.label('', null, null, shape, null, null, options.useHTML);
if (!chart.styledMode) {
graphic
.attr(series.pointAttribs(point))
.css(merge(options.style, point.style));
}
graphic.attr({
align: centered ? 'center' : 'left',
width: options.width,
height: options.height,
'text-align': options.textAlign
})
.addClass('highcharts-point')
.add(series.markerGroup);
// Add reference to the point for tracker (#6303)
if (point.graphic.div) {
point.graphic.div.point = point;
}
if (!chart.styledMode) {
graphic.shadow(options.shadow);
}
graphic.isNew = true;
}
if (plotX > 0) { // #3119
plotX -= graphic.strokeWidth() % 2; // #4285
}
// Plant the flag
attribs = {
y: plotY,
anchorY: anchorY
};
if (options.allowOverlapX) {
attribs.x = plotX;
attribs.anchorX = point.anchorX;
}
graphic.attr({
text: point.options.title || options.title || 'A'
})[graphic.isNew ? 'attr' : 'animate'](attribs);
// Rig for the distribute function
if (!options.allowOverlapX) {
if (!boxesMap[point.plotX]) {
boxesMap[point.plotX] = {
align: centered ? 0.5 : 0,
size: graphic.width,
target: plotX,
anchorX: plotX
};
}
else {
boxesMap[point.plotX].size = Math.max(boxesMap[point.plotX].size, graphic.width);
}
}
// Set the tooltip anchor position
point.tooltipPos = [
plotX,
plotY + yAxis.pos - chart.plotTop
]; // #6327
}
else if (graphic) {
point.graphic = graphic.destroy();
}
}
// Handle X-dimension overlapping
if (!options.allowOverlapX) {
objectEach(boxesMap, function (box) {
box.plotX = box.anchorX;
boxes.push(box);
});
H.distribute(boxes, inverted ? yAxis.len : this.xAxis.len, 100);
points.forEach(function (point) {
var box = point.graphic && boxesMap[point.plotX];
if (box) {
point.graphic[point.graphic.isNew ? 'attr' : 'animate']({
x: box.pos + box.align * box.size,
anchorX: point.anchorX
});
// Hide flag when its box position is not specified
// (#8573, #9299)
if (!defined(box.pos)) {
point.graphic.attr({
x: -9999,
anchorX: -9999
});
point.graphic.isNew = true;
}
else {
point.graphic.isNew = false;
}
}
});
}
// Can be a mix of SVG and HTML and we need events for both (#6303)
if (options.useHTML) {
wrap(series.markerGroup, 'on', function (proceed) {
return H.SVGElement.prototype.on.apply(
// for HTML
proceed.apply(this, [].slice.call(arguments, 1)),
// and for SVG
[].slice.call(arguments, 1));
});
}
},
/**
* Extend the column trackers with listeners to expand and contract
* stacks.
*
* @private
* @function Highcharts.seriesTypes.flags#drawTracker
* @return {void}
*/
drawTracker: function () {
var series = this, points = series.points;
TrackerMixin.drawTrackerPoint.apply(this);
/* *
* Bring each stacked flag up on mouse over, this allows readability
* of vertically stacked elements as well as tight points on the x
* axis. #1924.
*/
points.forEach(function (point) {
var graphic = point.graphic;
if (graphic) {
addEvent(graphic.element, 'mouseover', function () {
// Raise this point
if (point.stackIndex > 0 &&
!point.raised) {
point._y = graphic.y;
graphic.attr({
y: point._y - 8
});
point.raised = true;
}
// Revert other raised points
points.forEach(function (otherPoint) {
if (otherPoint !== point &&
otherPoint.raised &&
otherPoint.graphic) {
otherPoint.graphic.attr({
y: otherPoint._y
});
otherPoint.raised = false;
}
});
});
}
});
},
/**
* Disable animation, but keep clipping (#8546).
*
* @private
* @function Highcharts.seriesTypes.flags#animate
* @param {boolean} [init]
* @return {void}
*/
animate: function (init) {
if (init) {
this.setClip();
}
},
/**
* @private
* @function Highcharts.seriesTypes.flags#setClip
* @return {void}
*/
setClip: function () {
Series.prototype.setClip.apply(this, arguments);
if (this.options.clip !== false && this.sharedClipKey) {
this.markerGroup
.clip(this.chart[this.sharedClipKey]);
}
},
/**
* @private
* @function Highcharts.seriesTypes.flags#buildKDTree
*/
buildKDTree: noop,
/**
* Don't invert the flag marker group (#4960).
*
* @private
* @function Highcharts.seriesTypes.flags#invertGroups
*/
invertGroups: noop
/* eslint-enable no-invalid-this, valid-jsdoc */
},
/**
* @lends Highcharts.seriesTypes.flag.prototype.pointClass.prototype
*/
{
isValid: function () {
// #9233 - Prevent from treating flags as null points (even if
// they have no y values defined).
return isNumber(this.y) || typeof this.y === 'undefined';
}
});
// create the flag icon with anchor
symbols.flag = function (x, y, w, h, options) {
var anchorX = (options && options.anchorX) || x, anchorY = (options && options.anchorY) || y;
return symbols.circle(anchorX - 1, anchorY - 1, 2, 2).concat([
'M', anchorX, anchorY,
'L', x, y + h,
x, y,
x + w, y,
x + w, y + h,
x, y + h,
'Z'
]);
};
/**
* Create the circlepin and squarepin icons with anchor.
* @private
* @param {string} shape - circle or square
* @return {void}
*/
function createPinSymbol(shape) {
symbols[shape + 'pin'] = function (x, y, w, h, options) {
var anchorX = options && options.anchorX, anchorY = options && options.anchorY, path, labelTopOrBottomY;
// For single-letter flags, make sure circular flags are not taller
// than their width
if (shape === 'circle' && h > w) {
x -= Math.round((h - w) / 2);
w = h;
}
path = symbols[shape](x, y, w, h);
if (anchorX && anchorY) {
/**
* If the label is below the anchor, draw the connecting line
* from the top edge of the label
* otherwise start drawing from the bottom edge
*/
labelTopOrBottomY = (y > anchorY) ? y : y + h;
path.push('M', shape === 'circle' ?
x + w / 2 :
path[1] + path[4] / 2, labelTopOrBottomY, 'L', anchorX, anchorY);
path = path.concat(symbols.circle(anchorX - 1, anchorY - 1, 2, 2));
}
return path;
};
}
createPinSymbol('circle');
createPinSymbol('square');
/**
* The symbol callbacks are generated on the SVGRenderer object in all browsers.
* Even VML browsers need this in order to generate shapes in export. Now share
* them with the VMLRenderer.
*/
if (Renderer === VMLRenderer) {
['circlepin', 'flag', 'squarepin'].forEach(function (shape) {
VMLRenderer.prototype.symbols[shape] = symbols[shape];
});
}
/**
* A `flags` series. If the [type](#series.flags.type) option is not
* specified, it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.flags
* @excluding animation, borderColor, borderRadius, borderWidth, colorByPoint,
* connectNulls, dashStyle, dataGrouping, dataParser, dataURL,
* gapSize, gapUnit, linecap, lineWidth, marker, pointPadding,
* pointWidth, step, turboThreshold, useOhlcData
* @product highstock
* @apioption series.flags
*/
/**
* An array of data points for the series. For the `flags` series type,
* points can be given in the following ways:
*
* 1. An array of objects with named values. The following snippet shows only a
* few settings, see the complete options set below. If the total number of
* data points exceeds the series'
* [turboThreshold](#series.flags.turboThreshold), this option is not
* available.
* ```js
* data: [{
* x: 1,
* title: "A",
* text: "First event"
* }, {
* x: 1,
* title: "B",
* text: "Second event"
* }]
* ```
*
* @type {Array<*>}
* @extends series.line.data
* @excluding dataLabels, marker, name, y
* @product highstock
* @apioption series.flags.data
*/
/**
* The fill color of an individual flag. By default it inherits from
* the series color.
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @product highstock
* @apioption series.flags.data.fillColor
*/
/**
* The longer text to be shown in the flag's tooltip.
*
* @type {string}
* @product highstock
* @apioption series.flags.data.text
*/
/**
* The short text to be shown on the flag.
*
* @type {string}
* @product highstock
* @apioption series.flags.data.title
*/
''; // adds doclets above to transpiled file

View File

@@ -0,0 +1,77 @@
/* *
*
* (c) 2010-2020 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
/* globals Image, window */
/**
* Reference to the global SVGElement class as a workaround for a name conflict
* in the Highcharts namespace.
*
* @global
* @typedef {global.SVGElement} GlobalSVGElement
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/SVGElement
*/
// glob is a temporary fix to allow our es-modules to work.
var glob = ( // @todo UMD variable named `window`, and glob named `win`
typeof win !== 'undefined' ?
win :
typeof window !== 'undefined' ?
window :
{}), doc = glob.document, SVG_NS = 'http://www.w3.org/2000/svg', userAgent = (glob.navigator && glob.navigator.userAgent) || '', svg = (doc &&
doc.createElementNS &&
!!doc.createElementNS(SVG_NS, 'svg').createSVGRect), isMS = /(edge|msie|trident)/i.test(userAgent) && !glob.opera, isFirefox = userAgent.indexOf('Firefox') !== -1, isChrome = userAgent.indexOf('Chrome') !== -1, hasBidiBug = (isFirefox &&
parseInt(userAgent.split('Firefox/')[1], 10) < 4 // issue #38
);
var H = {
product: 'Highcharts',
version: '8.0.4',
deg2rad: Math.PI * 2 / 360,
doc: doc,
hasBidiBug: hasBidiBug,
hasTouch: !!glob.TouchEvent,
isMS: isMS,
isWebKit: userAgent.indexOf('AppleWebKit') !== -1,
isFirefox: isFirefox,
isChrome: isChrome,
isSafari: !isChrome && userAgent.indexOf('Safari') !== -1,
isTouchDevice: /(Mobile|Android|Windows Phone)/.test(userAgent),
SVG_NS: SVG_NS,
chartCount: 0,
seriesTypes: {},
symbolSizes: {},
svg: svg,
win: glob,
marginNames: ['plotTop', 'marginRight', 'marginBottom', 'plotLeft'],
noop: function () { },
/**
* An array containing the current chart objects in the page. A chart's
* position in the array is preserved throughout the page's lifetime. When
* a chart is destroyed, the array item becomes `undefined`.
*
* @name Highcharts.charts
* @type {Array<Highcharts.Chart|undefined>}
*/
charts: [],
/**
* A hook for defining additional date format specifiers. New
* specifiers are defined as key-value pairs by using the
* specifier as key, and a function which takes the timestamp as
* value. This function returns the formatted portion of the
* date.
*
* @sample highcharts/global/dateformats/
* Adding support for week number
*
* @name Highcharts.dateFormats
* @type {Highcharts.Dictionary<Highcharts.TimeFormatCallbackFunction>}
*/
dateFormats: {}
};
export default H;

View File

@@ -0,0 +1,424 @@
/* *
*
* (c) 2010-2020 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from './Globals.js';
import U from './Utilities.js';
var attr = U.attr, createElement = U.createElement, css = U.css, defined = U.defined, extend = U.extend, pick = U.pick, pInt = U.pInt;
import './SvgRenderer.js';
var isFirefox = H.isFirefox, isMS = H.isMS, isWebKit = H.isWebKit, SVGElement = H.SVGElement, SVGRenderer = H.SVGRenderer, win = H.win;
/* eslint-disable valid-jsdoc */
// Extend SvgElement for useHTML option.
extend(SVGElement.prototype, /** @lends SVGElement.prototype */ {
/**
* Apply CSS to HTML elements. This is used in text within SVG rendering and
* by the VML renderer
*
* @private
* @function Highcharts.SVGElement#htmlCss
*
* @param {Highcharts.CSSObject} styles
*
* @return {Highcharts.SVGElement}
*/
htmlCss: function (styles) {
var wrapper = this, element = wrapper.element,
// When setting or unsetting the width style, we need to update
// transform (#8809)
isSettingWidth = (element.tagName === 'SPAN' &&
styles &&
'width' in styles), textWidth = pick(isSettingWidth && styles.width, void 0), doTransform;
if (isSettingWidth) {
delete styles.width;
wrapper.textWidth = textWidth;
doTransform = true;
}
if (styles && styles.textOverflow === 'ellipsis') {
styles.whiteSpace = 'nowrap';
styles.overflow = 'hidden';
}
wrapper.styles = extend(wrapper.styles, styles);
css(wrapper.element, styles);
// Now that all styles are applied, to the transform
if (doTransform) {
wrapper.htmlUpdateTransform();
}
return wrapper;
},
/**
* VML and useHTML method for calculating the bounding box based on offsets.
*
* @private
* @function Highcharts.SVGElement#htmlGetBBox
*
* @param {boolean} refresh
* Whether to force a fresh value from the DOM or to use the cached
* value.
*
* @return {Highcharts.BBoxObject}
* A hash containing values for x, y, width and height.
*/
htmlGetBBox: function () {
var wrapper = this, element = wrapper.element;
return {
x: element.offsetLeft,
y: element.offsetTop,
width: element.offsetWidth,
height: element.offsetHeight
};
},
/**
* VML override private method to update elements based on internal
* properties based on SVG transform.
*
* @private
* @function Highcharts.SVGElement#htmlUpdateTransform
* @return {void}
*/
htmlUpdateTransform: function () {
// aligning non added elements is expensive
if (!this.added) {
this.alignOnAdd = true;
return;
}
var wrapper = this, renderer = wrapper.renderer, elem = wrapper.element, translateX = wrapper.translateX || 0, translateY = wrapper.translateY || 0, x = wrapper.x || 0, y = wrapper.y || 0, align = wrapper.textAlign || 'left', alignCorrection = {
left: 0, center: 0.5, right: 1
}[align], styles = wrapper.styles, whiteSpace = styles && styles.whiteSpace;
/**
* @private
* @return {number}
*/
function getTextPxLength() {
// Reset multiline/ellipsis in order to read width (#4928,
// #5417)
css(elem, {
width: '',
whiteSpace: whiteSpace || 'nowrap'
});
return elem.offsetWidth;
}
// apply translate
css(elem, {
marginLeft: translateX,
marginTop: translateY
});
if (!renderer.styledMode && wrapper.shadows) { // used in labels/tooltip
wrapper.shadows.forEach(function (shadow) {
css(shadow, {
marginLeft: translateX + 1,
marginTop: translateY + 1
});
});
}
// apply inversion
if (wrapper.inverted) { // wrapper is a group
[].forEach.call(elem.childNodes, function (child) {
renderer.invertChild(child, elem);
});
}
if (elem.tagName === 'SPAN') {
var rotation = wrapper.rotation, baseline, textWidth = wrapper.textWidth && pInt(wrapper.textWidth), currentTextTransform = [
rotation,
align,
elem.innerHTML,
wrapper.textWidth,
wrapper.textAlign
].join(',');
// Update textWidth. Use the memoized textPxLength if possible, to
// avoid the getTextPxLength function using elem.offsetWidth.
// Calling offsetWidth affects rendering time as it forces layout
// (#7656).
if (textWidth !== wrapper.oldTextWidth &&
((textWidth > wrapper.oldTextWidth) ||
(wrapper.textPxLength || getTextPxLength()) > textWidth) && (
// Only set the width if the text is able to word-wrap, or
// text-overflow is ellipsis (#9537)
/[ \-]/.test(elem.textContent || elem.innerText) ||
elem.style.textOverflow === 'ellipsis')) { // #983, #1254
css(elem, {
width: textWidth + 'px',
display: 'block',
whiteSpace: whiteSpace || 'normal' // #3331
});
wrapper.oldTextWidth = textWidth;
wrapper.hasBoxWidthChanged = true; // #8159
}
else {
wrapper.hasBoxWidthChanged = false; // #8159
}
// Do the calculations and DOM access only if properties changed
if (currentTextTransform !== wrapper.cTT) {
baseline = renderer.fontMetrics(elem.style.fontSize, elem).b;
// Renderer specific handling of span rotation, but only if we
// have something to update.
if (defined(rotation) &&
((rotation !== (wrapper.oldRotation || 0)) ||
(align !== wrapper.oldAlign))) {
wrapper.setSpanRotation(rotation, alignCorrection, baseline);
}
wrapper.getSpanCorrection(
// Avoid elem.offsetWidth if we can, it affects rendering
// time heavily (#7656)
((!defined(rotation) && wrapper.textPxLength) || // #7920
elem.offsetWidth), baseline, alignCorrection, rotation, align);
}
// apply position with correction
css(elem, {
left: (x + (wrapper.xCorr || 0)) + 'px',
top: (y + (wrapper.yCorr || 0)) + 'px'
});
// record current text transform
wrapper.cTT = currentTextTransform;
wrapper.oldRotation = rotation;
wrapper.oldAlign = align;
}
},
/**
* Set the rotation of an individual HTML span.
*
* @private
* @function Highcharts.SVGElement#setSpanRotation
* @param {number} rotation
* @param {number} alignCorrection
* @param {number} baseline
* @return {void}
*/
setSpanRotation: function (rotation, alignCorrection, baseline) {
var rotationStyle = {}, cssTransformKey = this.renderer.getTransformKey();
rotationStyle[cssTransformKey] = rotationStyle.transform =
'rotate(' + rotation + 'deg)';
rotationStyle[cssTransformKey + (isFirefox ? 'Origin' : '-origin')] =
rotationStyle.transformOrigin =
(alignCorrection * 100) + '% ' + baseline + 'px';
css(this.element, rotationStyle);
},
/**
* Get the correction in X and Y positioning as the element is rotated.
*
* @private
* @function Highcharts.SVGElement#getSpanCorrection
* @param {number} width
* @param {number} baseline
* @param {number} alignCorrection
* @return {void}
*/
getSpanCorrection: function (width, baseline, alignCorrection) {
this.xCorr = -width * alignCorrection;
this.yCorr = -baseline;
}
});
// Extend SvgRenderer for useHTML option.
extend(SVGRenderer.prototype, /** @lends SVGRenderer.prototype */ {
/**
* @private
* @function Highcharts.SVGRenderer#getTransformKey
*
* @return {string}
*/
getTransformKey: function () {
return isMS && !/Edge/.test(win.navigator.userAgent) ?
'-ms-transform' :
isWebKit ?
'-webkit-transform' :
isFirefox ?
'MozTransform' :
win.opera ?
'-o-transform' :
'';
},
/**
* Create HTML text node. This is used by the VML renderer as well as the
* SVG renderer through the useHTML option.
*
* @private
* @function Highcharts.SVGRenderer#html
*
* @param {string} str
* The text of (subset) HTML to draw.
*
* @param {number} x
* The x position of the text's lower left corner.
*
* @param {number} y
* The y position of the text's lower left corner.
*
* @return {Highcharts.HTMLDOMElement}
*/
html: function (str, x, y) {
var wrapper = this.createElement('span'), element = wrapper.element, renderer = wrapper.renderer, isSVG = renderer.isSVG, addSetters = function (gWrapper, style) {
// These properties are set as attributes on the SVG group, and
// as identical CSS properties on the div. (#3542)
['opacity', 'visibility'].forEach(function (prop) {
gWrapper[prop + 'Setter'] = function (value, key, elem) {
var styleObject = gWrapper.div ?
gWrapper.div.style :
style;
SVGElement.prototype[prop + 'Setter']
.call(this, value, key, elem);
if (styleObject) {
styleObject[key] = value;
}
};
});
gWrapper.addedSetters = true;
};
// Text setter
wrapper.textSetter = function (value) {
if (value !== element.innerHTML) {
delete this.bBox;
delete this.oldTextWidth;
}
this.textStr = value;
element.innerHTML = pick(value, '');
wrapper.doTransform = true;
};
// Add setters for the element itself (#4938)
if (isSVG) { // #4938, only for HTML within SVG
addSetters(wrapper, wrapper.element.style);
}
// Various setters which rely on update transform
wrapper.xSetter =
wrapper.ySetter =
wrapper.alignSetter =
wrapper.rotationSetter =
function (value, key) {
if (key === 'align') {
// Do not overwrite the SVGElement.align method. Same as VML.
key = 'textAlign';
}
wrapper[key] = value;
wrapper.doTransform = true;
};
// Runs at the end of .attr()
wrapper.afterSetters = function () {
// Update transform. Do this outside the loop to prevent redundant
// updating for batch setting of attributes.
if (this.doTransform) {
this.htmlUpdateTransform();
this.doTransform = false;
}
};
// Set the default attributes
wrapper
.attr({
text: str,
x: Math.round(x),
y: Math.round(y)
})
.css({
position: 'absolute'
});
if (!renderer.styledMode) {
wrapper.css({
fontFamily: this.style.fontFamily,
fontSize: this.style.fontSize
});
}
// Keep the whiteSpace style outside the wrapper.styles collection
element.style.whiteSpace = 'nowrap';
// Use the HTML specific .css method
wrapper.css = wrapper.htmlCss;
// This is specific for HTML within SVG
if (isSVG) {
wrapper.add = function (svgGroupWrapper) {
var htmlGroup, container = renderer.box.parentNode, parentGroup, parents = [];
this.parentGroup = svgGroupWrapper;
// Create a mock group to hold the HTML elements
if (svgGroupWrapper) {
htmlGroup = svgGroupWrapper.div;
if (!htmlGroup) {
// Read the parent chain into an array and read from top
// down
parentGroup = svgGroupWrapper;
while (parentGroup) {
parents.push(parentGroup);
// Move up to the next parent group
parentGroup = parentGroup.parentGroup;
}
// Ensure dynamically updating position when any parent
// is translated
parents.reverse().forEach(function (parentGroup) {
var htmlGroupStyle, cls = attr(parentGroup.element, 'class');
/**
* Common translate setter for X and Y on the HTML
* group. Reverted the fix for #6957 du to
* positioning problems and offline export (#7254,
* #7280, #7529)
* @private
* @param {*} value
* @param {string} key
* @return {void}
*/
function translateSetter(value, key) {
parentGroup[key] = value;
if (key === 'translateX') {
htmlGroupStyle.left = value + 'px';
}
else {
htmlGroupStyle.top = value + 'px';
}
parentGroup.doTransform = true;
}
// Create a HTML div and append it to the parent div
// to emulate the SVG group structure
htmlGroup =
parentGroup.div =
parentGroup.div || createElement('div', cls ? { className: cls } : void 0, {
position: 'absolute',
left: (parentGroup.translateX || 0) + 'px',
top: (parentGroup.translateY || 0) + 'px',
display: parentGroup.display,
opacity: parentGroup.opacity,
pointerEvents: (parentGroup.styles &&
parentGroup.styles.pointerEvents) // #5595
// the top group is appended to container
}, htmlGroup || container);
// Shortcut
htmlGroupStyle = htmlGroup.style;
// Set listeners to update the HTML div's position
// whenever the SVG group position is changed.
extend(parentGroup, {
// (#7287) Pass htmlGroup to use
// the related group
classSetter: (function (htmlGroup) {
return function (value) {
this.element.setAttribute('class', value);
htmlGroup.className = value;
};
}(htmlGroup)),
on: function () {
if (parents[0].div) { // #6418
wrapper.on.apply({ element: parents[0].div }, arguments);
}
return parentGroup;
},
translateXSetter: translateSetter,
translateYSetter: translateSetter
});
if (!parentGroup.addedSetters) {
addSetters(parentGroup);
}
});
}
}
else {
htmlGroup = container;
}
htmlGroup.appendChild(element);
// Shared with VML:
wrapper.added = true;
if (wrapper.alignOnAdd) {
wrapper.htmlUpdateTransform();
}
return wrapper;
};
}
return wrapper;
}
});

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,121 @@
/* *
*
* (c) 2010-2020 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from './Globals.js';
import U from './Utilities.js';
var getMagnitude = U.getMagnitude, normalizeTickInterval = U.normalizeTickInterval, pick = U.pick;
var Axis = H.Axis;
/* ************************************************************************** *
* Methods defined on the Axis prototype
* ************************************************************************** */
/* eslint-disable valid-jsdoc */
/**
* Set the tick positions of a logarithmic axis.
*
* @private
* @function Highcharts.Axis#getLogTickPositions
* @param {number} interval
* @param {number} min
* @param {number} max
* @param {boolean} [minor]
* @return {Array<number>}
*/
Axis.prototype.getLogTickPositions = function (interval, min, max, minor) {
var axis = this, options = axis.options, axisLength = axis.len,
// Since we use this method for both major and minor ticks,
// use a local variable and return the result
positions = [];
// Reset
if (!minor) {
axis._minorAutoInterval = null;
}
// First case: All ticks fall on whole logarithms: 1, 10, 100 etc.
if (interval >= 0.5) {
interval = Math.round(interval);
positions = axis.getLinearTickPositions(interval, min, max);
// Second case: We need intermediary ticks. For example
// 1, 2, 4, 6, 8, 10, 20, 40 etc.
}
else if (interval >= 0.08) {
var roundedMin = Math.floor(min), intermediate, i, j, len, pos, lastPos, break2;
if (interval > 0.3) {
intermediate = [1, 2, 4];
// 0.2 equals five minor ticks per 1, 10, 100 etc
}
else if (interval > 0.15) {
intermediate = [1, 2, 4, 6, 8];
}
else { // 0.1 equals ten minor ticks per 1, 10, 100 etc
intermediate = [1, 2, 3, 4, 5, 6, 7, 8, 9];
}
for (i = roundedMin; i < max + 1 && !break2; i++) {
len = intermediate.length;
for (j = 0; j < len && !break2; j++) {
pos = axis.log2lin(axis.lin2log(i) * intermediate[j]);
// #1670, lastPos is #3113
if (pos > min &&
(!minor || lastPos <= max) &&
typeof lastPos !== 'undefined') {
positions.push(lastPos);
}
if (lastPos > max) {
break2 = true;
}
lastPos = pos;
}
}
// Third case: We are so deep in between whole logarithmic values that
// we might as well handle the tick positions like a linear axis. For
// example 1.01, 1.02, 1.03, 1.04.
}
else {
var realMin = axis.lin2log(min), realMax = axis.lin2log(max), tickIntervalOption = minor ?
this.getMinorTickInterval() :
options.tickInterval, filteredTickIntervalOption = tickIntervalOption === 'auto' ?
null :
tickIntervalOption, tickPixelIntervalOption = options.tickPixelInterval / (minor ? 5 : 1), totalPixelLength = minor ?
axisLength / axis.tickPositions.length :
axisLength;
interval = pick(filteredTickIntervalOption, axis._minorAutoInterval, (realMax - realMin) *
tickPixelIntervalOption / (totalPixelLength || 1));
interval = normalizeTickInterval(interval, null, getMagnitude(interval));
positions = axis.getLinearTickPositions(interval, realMin, realMax).map(axis.log2lin);
if (!minor) {
axis._minorAutoInterval = interval / 5;
}
}
// Set the axis-level tickInterval variable
if (!minor) {
axis.tickInterval = interval;
}
return positions;
};
/**
* @private
* @function Highcharts.Axis#log2lin
*
* @param {number} num
*
* @return {number}
*/
Axis.prototype.log2lin = function (num) {
return Math.log(num) / Math.LN10;
};
/**
* @private
* @function Highcharts.Axis#lin2log
*
* @param {number} num
*
* @return {number}
*/
Axis.prototype.lin2log = function (num) {
return Math.pow(10, num);
};

View File

@@ -0,0 +1,160 @@
/* *
*
* (c) 2010-2020 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
import H from './Globals.js';
/* globals MSPointerEvent, PointerEvent */
import Pointer from './Pointer.js';
import U from './Utilities.js';
var addEvent = U.addEvent, css = U.css, objectEach = U.objectEach, removeEvent = U.removeEvent;
var charts = H.charts, doc = H.doc, noop = H.noop, win = H.win;
// The touches object keeps track of the points being touched at all times
var touches = {};
var hasPointerEvent = !!win.PointerEvent;
/* eslint-disable valid-jsdoc */
/** @private */
function getWebkitTouches() {
var fake = [];
fake.item = function (i) {
return this[i];
};
objectEach(touches, function (touch) {
fake.push({
pageX: touch.pageX,
pageY: touch.pageY,
target: touch.target
});
});
return fake;
}
/** @private */
function translateMSPointer(e, method, wktype, func) {
var p;
if ((e.pointerType === 'touch' ||
e.pointerType === e.MSPOINTER_TYPE_TOUCH) && charts[H.hoverChartIndex]) {
func(e);
p = charts[H.hoverChartIndex].pointer;
p[method]({
type: wktype,
target: e.currentTarget,
preventDefault: noop,
touches: getWebkitTouches()
});
}
}
/** @private */
var MSPointer = /** @class */ (function (_super) {
__extends(MSPointer, _super);
function MSPointer() {
return _super !== null && _super.apply(this, arguments) || this;
}
/* *
*
* Functions
*
* */
/**
* Add or remove the MS Pointer specific events
*
* @private
* @function Highcharts.Pointer#batchMSEvents
*
* @param {Function} fn
*
* @return {void}
*/
MSPointer.prototype.batchMSEvents = function (fn) {
fn(this.chart.container, hasPointerEvent ? 'pointerdown' : 'MSPointerDown', this.onContainerPointerDown);
fn(this.chart.container, hasPointerEvent ? 'pointermove' : 'MSPointerMove', this.onContainerPointerMove);
fn(doc, hasPointerEvent ? 'pointerup' : 'MSPointerUp', this.onDocumentPointerUp);
};
// Destroy MS events also
MSPointer.prototype.destroy = function () {
this.batchMSEvents(removeEvent);
_super.prototype.destroy.call(this);
};
// Disable default IE actions for pinch and such on chart element
MSPointer.prototype.init = function (chart, options) {
_super.prototype.init.call(this, chart, options);
if (this.hasZoom) { // #4014
css(chart.container, {
'-ms-touch-action': 'none',
'touch-action': 'none'
});
}
};
/**
* @private
* @function Highcharts.Pointer#onContainerPointerDown
*
* @param {Highcharts.PointerEventObject} e
*
* @return {void}
*/
MSPointer.prototype.onContainerPointerDown = function (e) {
translateMSPointer(e, 'onContainerTouchStart', 'touchstart', function (e) {
touches[e.pointerId] = {
pageX: e.pageX,
pageY: e.pageY,
target: e.currentTarget
};
});
};
/**
* @private
* @function Highcharts.Pointer#onContainerPointerMove
*
* @param {Highcharts.PointerEventObject} e
*
* @return {void}
*/
MSPointer.prototype.onContainerPointerMove = function (e) {
translateMSPointer(e, 'onContainerTouchMove', 'touchmove', function (e) {
touches[e.pointerId] = ({ pageX: e.pageX, pageY: e.pageY });
if (!touches[e.pointerId].target) {
touches[e.pointerId].target = e.currentTarget;
}
});
};
/**
* @private
* @function Highcharts.Pointer#onDocumentPointerUp
*
* @param {Highcharts.PointerEventObject} e
*
* @return {void}
*/
MSPointer.prototype.onDocumentPointerUp = function (e) {
translateMSPointer(e, 'onDocumentTouchEnd', 'touchend', function (e) {
delete touches[e.pointerId];
});
};
// Add IE specific touch events to chart
MSPointer.prototype.setDOMEvents = function () {
_super.prototype.setDOMEvents.call(this);
if (this.hasZoom || this.followTouchMove) {
this.batchMSEvents(addEvent);
}
};
return MSPointer;
}(Pointer));
export default MSPointer;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,351 @@
/* *
*
* (c) 2010-2020 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from './Globals.js';
import Point from './Point.js';
import U from './Utilities.js';
var seriesType = U.seriesType;
var seriesTypes = H.seriesTypes;
/**
* The ohlc series type.
*
* @private
* @class
* @name Highcharts.seriesTypes.ohlc
*
* @augments Highcharts.Series
*/
seriesType('ohlc', 'column'
/**
* An OHLC chart is a style of financial chart used to describe price
* movements over time. It displays open, high, low and close values per
* data point.
*
* @sample stock/demo/ohlc/
* OHLC chart
*
* @extends plotOptions.column
* @excluding borderColor, borderRadius, borderWidth, crisp, stacking,
* stack
* @product highstock
* @optionparent plotOptions.ohlc
*/
, {
/**
* The approximate pixel width of each group. If for example a series
* with 30 points is displayed over a 600 pixel wide plot area, no
* grouping is performed. If however the series contains so many points
* that the spacing is less than the groupPixelWidth, Highcharts will
* try to group it into appropriate groups so that each is more or less
* two pixels wide. Defaults to `5`.
*
* @type {number}
* @default 5
* @product highstock
* @apioption plotOptions.ohlc.dataGrouping.groupPixelWidth
*/
/**
* The pixel width of the line/border. Defaults to `1`.
*
* @sample {highstock} stock/plotoptions/ohlc-linewidth/
* A greater line width
*
* @type {number}
* @default 1
* @product highstock
*
* @private
*/
lineWidth: 1,
tooltip: {
pointFormat: '<span style="color:{point.color}">\u25CF</span> ' +
'<b> {series.name}</b><br/>' +
'Open: {point.open}<br/>' +
'High: {point.high}<br/>' +
'Low: {point.low}<br/>' +
'Close: {point.close}<br/>'
},
threshold: null,
states: {
/**
* @extends plotOptions.column.states.hover
* @product highstock
*/
hover: {
/**
* The pixel width of the line representing the OHLC point.
*
* @type {number}
* @default 3
* @product highstock
*/
lineWidth: 3
}
},
/**
* Determines which one of `open`, `high`, `low`, `close` values should
* be represented as `point.y`, which is later used to set dataLabel
* position and [compare](#plotOptions.series.compare).
*
* @sample {highstock} stock/plotoptions/ohlc-pointvalkey/
* Possible values
*
* @type {string}
* @default close
* @validvalue ["open", "high", "low", "close"]
* @product highstock
* @apioption plotOptions.ohlc.pointValKey
*/
/**
* @default close
* @apioption plotOptions.ohlc.colorKey
*/
/**
* Line color for up points.
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @product highstock
* @apioption plotOptions.ohlc.upColor
*/
stickyTracking: true
},
/**
* @lends Highcharts.seriesTypes.ohlc
*/
{
/* eslint-disable valid-jsdoc */
directTouch: false,
pointArrayMap: ['open', 'high', 'low', 'close'],
toYData: function (point) {
// return a plain array for speedy calculation
return [point.open, point.high, point.low, point.close];
},
pointValKey: 'close',
pointAttrToOptions: {
stroke: 'color',
'stroke-width': 'lineWidth'
},
/**
* @private
* @function Highcarts.seriesTypes.ohlc#init
* @return {void}
*/
init: function () {
seriesTypes.column.prototype.init.apply(this, arguments);
this.options.stacking = false; // #8817
},
/**
* Postprocess mapping between options and SVG attributes
*
* @private
* @function Highcharts.seriesTypes.ohlc#pointAttribs
* @param {Highcharts.OHLCPoint} point
* @param {string} state
* @return {Highcharts.SVGAttributes}
*/
pointAttribs: function (point, state) {
var attribs = seriesTypes.column.prototype.pointAttribs.call(this, point, state), options = this.options;
delete attribs.fill;
if (!point.options.color &&
options.upColor &&
point.open < point.close) {
attribs.stroke = options.upColor;
}
return attribs;
},
/**
* Translate data points from raw values x and y to plotX and plotY
*
* @private
* @function Highcharts.seriesTypes.ohlc#translate
* @return {void}
*/
translate: function () {
var series = this, yAxis = series.yAxis, hasModifyValue = !!series.modifyValue, translated = [
'plotOpen',
'plotHigh',
'plotLow',
'plotClose',
'yBottom'
]; // translate OHLC for
seriesTypes.column.prototype.translate.apply(series);
// Do the translation
series.points.forEach(function (point) {
[point.open, point.high, point.low, point.close, point.low]
.forEach(function (value, i) {
if (value !== null) {
if (hasModifyValue) {
value = series.modifyValue(value);
}
point[translated[i]] =
yAxis.toPixels(value, true);
}
});
// Align the tooltip to the high value to avoid covering the
// point
point.tooltipPos[1] =
point.plotHigh + yAxis.pos - series.chart.plotTop;
});
},
/**
* Draw the data points
*
* @private
* @function Highcharts.seriesTypes.ohlc#drawPoints
* @return {void}
*/
drawPoints: function () {
var series = this, points = series.points, chart = series.chart,
/**
* Extend vertical stem to open and close values.
*/
extendStem = function (path, halfStrokeWidth, openOrClose) {
// We don't need to worry about crisp - openOrClose value
// is already crisped and halfStrokeWidth should remove it.
path[2] = Math.max(openOrClose + halfStrokeWidth, path[2]);
path[5] = Math.min(openOrClose - halfStrokeWidth, path[5]);
};
points.forEach(function (point) {
var plotOpen, plotClose, crispCorr, halfWidth, path, graphic = point.graphic, crispX, isNew = !graphic, strokeWidth;
if (typeof point.plotY !== 'undefined') {
// Create and/or update the graphic
if (!graphic) {
point.graphic = graphic = chart.renderer.path()
.add(series.group);
}
if (!chart.styledMode) {
graphic.attr(series.pointAttribs(point, (point.selected && 'select'))); // #3897
}
// crisp vector coordinates
strokeWidth = graphic.strokeWidth();
crispCorr = (strokeWidth % 2) / 2;
// #2596:
crispX = Math.round(point.plotX) - crispCorr;
halfWidth = Math.round(point.shapeArgs.width / 2);
// the vertical stem
path = [
'M',
crispX, Math.round(point.yBottom),
'L',
crispX, Math.round(point.plotHigh)
];
// open
if (point.open !== null) {
plotOpen = Math.round(point.plotOpen) + crispCorr;
path.push('M', crispX, plotOpen, 'L', crispX - halfWidth, plotOpen);
extendStem(path, strokeWidth / 2, plotOpen);
}
// close
if (point.close !== null) {
plotClose = Math.round(point.plotClose) + crispCorr;
path.push('M', crispX, plotClose, 'L', crispX + halfWidth, plotClose);
extendStem(path, strokeWidth / 2, plotClose);
}
graphic[isNew ? 'attr' : 'animate']({ d: path })
.addClass(point.getClassName(), true);
}
});
},
animate: null // Disable animation
/* eslint-enable valid-jsdoc */
},
/**
* @lends Highcharts.seriesTypes.ohlc.prototype.pointClass.prototype
*/
{
/* eslint-disable valid-jsdoc */
/**
* Extend the parent method by adding up or down to the class name.
* @private
* @function Highcharts.seriesTypes.ohlc#getClassName
* @return {string}
*/
getClassName: function () {
return Point.prototype.getClassName.call(this) +
(this.open < this.close ?
' highcharts-point-up' :
' highcharts-point-down');
}
/* eslint-enable valid-jsdoc */
});
/**
* A `ohlc` series. If the [type](#series.ohlc.type) option is not
* specified, it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.ohlc
* @excluding dataParser, dataURL
* @product highstock
* @apioption series.ohlc
*/
/**
* An array of data points for the series. For the `ohlc` series type,
* points can be given in the following ways:
*
* 1. An array of arrays with 5 or 4 values. In this case, the values correspond
* to `x,open,high,low,close`. If the first value is a string, it is applied
* as the name of the point, and the `x` value is inferred. The `x` value can
* also be omitted, in which case the inner arrays should be of length 4\.
* Then the `x` value is automatically calculated, either starting at 0 and
* incremented by 1, or from `pointStart` and `pointInterval` given in the
* series options.
* ```js
* data: [
* [0, 6, 5, 6, 7],
* [1, 9, 4, 8, 2],
* [2, 6, 3, 4, 10]
* ]
* ```
*
* 2. An array of objects with named values. The following snippet shows only a
* few settings, see the complete options set below. If the total number of
* data points exceeds the series'
* [turboThreshold](#series.ohlc.turboThreshold), this option is not
* available.
* ```js
* data: [{
* x: 1,
* open: 3,
* high: 4,
* low: 5,
* close: 2,
* name: "Point2",
* color: "#00FF00"
* }, {
* x: 1,
* open: 4,
* high: 3,
* low: 6,
* close: 7,
* name: "Point1",
* color: "#FF00FF"
* }]
* ```
*
* @type {Array<Array<(number|string),number,number,number>|Array<(number|string),number,number,number,number>|*>}
* @extends series.arearange.data
* @excluding y, marker
* @product highstock
* @apioption series.ohlc.data
*/
/**
* The closing value of each data point.
*
* @type {number}
* @product highstock
* @apioption series.ohlc.data.close
*/
/**
* The opening value of each data point.
*
* @type {number}
* @product highstock
* @apioption series.ohlc.data.open
*/
''; // adds doclets above to transpilat

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,713 @@
/* *
*
* (c) 2010-2020 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from './Globals.js';
import './Axis.js';
import U from './Utilities.js';
var addEvent = U.addEvent, css = U.css, defined = U.defined, extend = U.extend, pick = U.pick, timeUnits = U.timeUnits;
import './Chart.js';
import './Series.js';
// Has a dependency on Navigator due to the use of Axis.toFixedRange
import './Navigator.js';
var Axis = H.Axis, Chart = H.Chart, noop = H.noop, Series = H.Series;
/* eslint-disable no-invalid-this, valid-jsdoc */
/* ************************************************************************** *
* Start ordinal axis logic *
* ************************************************************************** */
addEvent(Series, 'updatedData', function () {
var xAxis = this.xAxis;
// Destroy the extended ordinal index on updated data
if (xAxis && xAxis.options.ordinal) {
delete xAxis.ordinalIndex;
}
});
/**
* In an ordinal axis, there might be areas with dense consentrations of points,
* then large gaps between some. Creating equally distributed ticks over this
* entire range may lead to a huge number of ticks that will later be removed.
* So instead, break the positions up in segments, find the tick positions for
* each segment then concatenize them. This method is used from both data
* grouping logic and X axis tick position logic.
* @private
*/
Axis.prototype.getTimeTicks = function (normalizedInterval, min, max, startOfWeek, positions, closestDistance, findHigherRanks) {
var start = 0, end, segmentPositions, higherRanks = {}, hasCrossedHigherRank, info, posLength, outsideMax, groupPositions = [], lastGroupPosition = -Number.MAX_VALUE, tickPixelIntervalOption = this.options.tickPixelInterval, time = this.chart.time,
// Record all the start positions of a segment, to use when deciding
// what's a gap in the data.
segmentStarts = [];
// The positions are not always defined, for example for ordinal positions
// when data has regular interval (#1557, #2090)
if ((!this.options.ordinal && !this.options.breaks) ||
!positions ||
positions.length < 3 ||
typeof min === 'undefined') {
return time.getTimeTicks.apply(time, arguments);
}
// Analyze the positions array to split it into segments on gaps larger than
// 5 times the closest distance. The closest distance is already found at
// this point, so we reuse that instead of computing it again.
posLength = positions.length;
for (end = 0; end < posLength; end++) {
outsideMax = end && positions[end - 1] > max;
if (positions[end] < min) { // Set the last position before min
start = end;
}
if (end === posLength - 1 ||
positions[end + 1] - positions[end] > closestDistance * 5 ||
outsideMax) {
// For each segment, calculate the tick positions from the
// getTimeTicks utility function. The interval will be the same
// regardless of how long the segment is.
if (positions[end] > lastGroupPosition) { // #1475
segmentPositions = time.getTimeTicks(normalizedInterval, positions[start], positions[end], startOfWeek);
// Prevent duplicate groups, for example for multiple segments
// within one larger time frame (#1475)
while (segmentPositions.length &&
segmentPositions[0] <= lastGroupPosition) {
segmentPositions.shift();
}
if (segmentPositions.length) {
lastGroupPosition =
segmentPositions[segmentPositions.length - 1];
}
segmentStarts.push(groupPositions.length);
groupPositions = groupPositions.concat(segmentPositions);
}
// Set start of next segment
start = end + 1;
}
if (outsideMax) {
break;
}
}
// Get the grouping info from the last of the segments. The info is the same
// for all segments.
info = segmentPositions.info;
// Optionally identify ticks with higher rank, for example when the ticks
// have crossed midnight.
if (findHigherRanks && info.unitRange <= timeUnits.hour) {
end = groupPositions.length - 1;
// Compare points two by two
for (start = 1; start < end; start++) {
if (time.dateFormat('%d', groupPositions[start]) !==
time.dateFormat('%d', groupPositions[start - 1])) {
higherRanks[groupPositions[start]] = 'day';
hasCrossedHigherRank = true;
}
}
// If the complete array has crossed midnight, we want to mark the first
// positions also as higher rank
if (hasCrossedHigherRank) {
higherRanks[groupPositions[0]] = 'day';
}
info.higherRanks = higherRanks;
}
// Save the info
info.segmentStarts = segmentStarts;
groupPositions.info = info;
// Don't show ticks within a gap in the ordinal axis, where the space
// between two points is greater than a portion of the tick pixel interval
if (findHigherRanks && defined(tickPixelIntervalOption)) {
var length = groupPositions.length, i = length, itemToRemove, translated, translatedArr = [], lastTranslated, medianDistance, distance, distances = [];
// Find median pixel distance in order to keep a reasonably even
// distance between ticks (#748)
while (i--) {
translated = this.translate(groupPositions[i]);
if (lastTranslated) {
distances[i] = lastTranslated - translated;
}
translatedArr[i] = lastTranslated = translated;
}
distances.sort();
medianDistance = distances[Math.floor(distances.length / 2)];
if (medianDistance < tickPixelIntervalOption * 0.6) {
medianDistance = null;
}
// Now loop over again and remove ticks where needed
i = groupPositions[length - 1] > max ? length - 1 : length; // #817
lastTranslated = void 0;
while (i--) {
translated = translatedArr[i];
distance = Math.abs(lastTranslated - translated);
// #4175 - when axis is reversed, the distance, is negative but
// tickPixelIntervalOption positive, so we need to compare the same
// values
// Remove ticks that are closer than 0.6 times the pixel interval
// from the one to the right, but not if it is close to the median
// distance (#748).
if (lastTranslated &&
distance < tickPixelIntervalOption * 0.8 &&
(medianDistance === null || distance < medianDistance * 0.8)) {
// Is this a higher ranked position with a normal position to
// the right?
if (higherRanks[groupPositions[i]] &&
!higherRanks[groupPositions[i + 1]]) {
// Yes: remove the lower ranked neighbour to the right
itemToRemove = i + 1;
lastTranslated = translated; // #709
}
else {
// No: remove this one
itemToRemove = i;
}
groupPositions.splice(itemToRemove, 1);
}
else {
lastTranslated = translated;
}
}
}
return groupPositions;
};
// Extend the Axis prototype
extend(Axis.prototype, /** @lends Axis.prototype */ {
/**
* Calculate the ordinal positions before tick positions are calculated.
*
* @private
* @function Highcharts.Axis#beforeSetTickPositions
* @return {void}
*/
beforeSetTickPositions: function () {
var axis = this, len, ordinalPositions = [], uniqueOrdinalPositions, useOrdinal = false, dist, extremes = axis.getExtremes(), min = extremes.min, max = extremes.max, minIndex, maxIndex, slope, hasBreaks = axis.isXAxis && !!axis.options.breaks, isOrdinal = axis.options.ordinal, overscrollPointsRange = Number.MAX_VALUE, ignoreHiddenSeries = axis.chart.options.chart.ignoreHiddenSeries, i, hasBoostedSeries;
// Apply the ordinal logic
if (isOrdinal || hasBreaks) { // #4167 YAxis is never ordinal ?
axis.series.forEach(function (series, i) {
uniqueOrdinalPositions = [];
if ((!ignoreHiddenSeries || series.visible !== false) &&
(series.takeOrdinalPosition !== false || hasBreaks)) {
// concatenate the processed X data into the existing
// positions, or the empty array
ordinalPositions = ordinalPositions.concat(series.processedXData);
len = ordinalPositions.length;
// remove duplicates (#1588)
ordinalPositions.sort(function (a, b) {
// without a custom function it is sorted as strings
return a - b;
});
overscrollPointsRange = Math.min(overscrollPointsRange, pick(
// Check for a single-point series:
series.closestPointRange, overscrollPointsRange));
if (len) {
i = 0;
while (i < len - 1) {
if (ordinalPositions[i] !== ordinalPositions[i + 1]) {
uniqueOrdinalPositions.push(ordinalPositions[i + 1]);
}
i++;
}
// Check first item:
if (uniqueOrdinalPositions[0] !== ordinalPositions[0]) {
uniqueOrdinalPositions.unshift(ordinalPositions[0]);
}
ordinalPositions = uniqueOrdinalPositions;
}
}
if (series.isSeriesBoosting) {
hasBoostedSeries = true;
}
});
if (hasBoostedSeries) {
ordinalPositions.length = 0;
}
// cache the length
len = ordinalPositions.length;
// Check if we really need the overhead of mapping axis data against
// the ordinal positions. If the series consist of evenly spaced
// data any way, we don't need any ordinal logic.
if (len > 2) { // two points have equal distance by default
dist = ordinalPositions[1] - ordinalPositions[0];
i = len - 1;
while (i-- && !useOrdinal) {
if (ordinalPositions[i + 1] - ordinalPositions[i] !== dist) {
useOrdinal = true;
}
}
// When zooming in on a week, prevent axis padding for weekends
// even though the data within the week is evenly spaced.
if (!axis.options.keepOrdinalPadding &&
(ordinalPositions[0] - min > dist ||
max - ordinalPositions[ordinalPositions.length - 1] >
dist)) {
useOrdinal = true;
}
}
else if (axis.options.overscroll) {
if (len === 2) {
// Exactly two points, distance for overscroll is fixed:
overscrollPointsRange =
ordinalPositions[1] - ordinalPositions[0];
}
else if (len === 1) {
// We have just one point, closest distance is unknown.
// Assume then it is last point and overscrolled range:
overscrollPointsRange = axis.options.overscroll;
ordinalPositions = [
ordinalPositions[0],
ordinalPositions[0] + overscrollPointsRange
];
}
else {
// In case of zooming in on overscrolled range, stick to the
// old range:
overscrollPointsRange = axis.overscrollPointsRange;
}
}
// Record the slope and offset to compute the linear values from the
// array index. Since the ordinal positions may exceed the current
// range, get the start and end positions within it (#719, #665b)
if (useOrdinal) {
if (axis.options.overscroll) {
axis.overscrollPointsRange = overscrollPointsRange;
ordinalPositions = ordinalPositions.concat(axis.getOverscrollPositions());
}
// Register
axis.ordinalPositions = ordinalPositions;
// This relies on the ordinalPositions being set. Use Math.max
// and Math.min to prevent padding on either sides of the data.
minIndex = axis.ordinal2lin(// #5979
Math.max(min, ordinalPositions[0]), true);
maxIndex = Math.max(axis.ordinal2lin(Math.min(max, ordinalPositions[ordinalPositions.length - 1]), true), 1); // #3339
// Set the slope and offset of the values compared to the
// indices in the ordinal positions
axis.ordinalSlope = slope = (max - min) / (maxIndex - minIndex);
axis.ordinalOffset = min - (minIndex * slope);
}
else {
axis.overscrollPointsRange = pick(axis.closestPointRange, axis.overscrollPointsRange);
axis.ordinalPositions = axis.ordinalSlope = axis.ordinalOffset =
void 0;
}
}
axis.isOrdinal = isOrdinal && useOrdinal; // #3818, #4196, #4926
axis.groupIntervalFactor = null; // reset for next run
},
/**
* Translate from a linear axis value to the corresponding ordinal axis
* position. If there are no gaps in the ordinal axis this will be the same.
* The translated value is the value that the point would have if the axis
* were linear, using the same min and max.
*
* @private
* @function Highcharts.Axis#val2lin
*
* @param {number} val
* The axis value.
*
* @param {boolean} [toIndex]
* Whether to return the index in the ordinalPositions or the new
* value.
*
* @return {number}
*/
val2lin: function (val, toIndex) {
var axis = this, ordinalPositions = axis.ordinalPositions, ret;
if (!ordinalPositions) {
ret = val;
}
else {
var ordinalLength = ordinalPositions.length, i, distance, ordinalIndex;
// first look for an exact match in the ordinalpositions array
i = ordinalLength;
while (i--) {
if (ordinalPositions[i] === val) {
ordinalIndex = i;
break;
}
}
// if that failed, find the intermediate position between the two
// nearest values
i = ordinalLength - 1;
while (i--) {
if (val > ordinalPositions[i] || i === 0) { // interpolate
// something between 0 and 1
distance = (val - ordinalPositions[i]) /
(ordinalPositions[i + 1] - ordinalPositions[i]);
ordinalIndex = i + distance;
break;
}
}
ret = toIndex ?
ordinalIndex :
axis.ordinalSlope *
(ordinalIndex || 0) +
axis.ordinalOffset;
}
return ret;
},
/**
* Translate from linear (internal) to axis value.
*
* @private
* @function Highcharts.Axis#lin2val
*
* @param {number} val
* The linear abstracted value.
*
* @param {boolean} [fromIndex]
* Translate from an index in the ordinal positions rather than a
* value.
*
* @return {number}
*/
lin2val: function (val, fromIndex) {
var axis = this, ordinalPositions = axis.ordinalPositions, ret;
// the visible range contains only equally spaced values
if (!ordinalPositions) {
ret = val;
}
else {
var ordinalSlope = axis.ordinalSlope, ordinalOffset = axis.ordinalOffset, i = ordinalPositions.length - 1, linearEquivalentLeft, linearEquivalentRight, distance;
// Handle the case where we translate from the index directly, used
// only when panning an ordinal axis
if (fromIndex) {
if (val < 0) { // out of range, in effect panning to the left
val = ordinalPositions[0];
}
else if (val > i) { // out of range, panning to the right
val = ordinalPositions[i];
}
else { // split it up
i = Math.floor(val);
distance = val - i; // the decimal
}
// Loop down along the ordinal positions. When the linear equivalent
// of i matches an ordinal position, interpolate between the left
// and right values.
}
else {
while (i--) {
linearEquivalentLeft =
(ordinalSlope * i) + ordinalOffset;
if (val >= linearEquivalentLeft) {
linearEquivalentRight =
(ordinalSlope *
(i + 1)) +
ordinalOffset;
// something between 0 and 1
distance = (val - linearEquivalentLeft) /
(linearEquivalentRight - linearEquivalentLeft);
break;
}
}
}
// If the index is within the range of the ordinal positions, return
// the associated or interpolated value. If not, just return the
// value
return (typeof distance !== 'undefined' &&
typeof ordinalPositions[i] !== 'undefined' ?
ordinalPositions[i] + (distance ?
distance *
(ordinalPositions[i + 1] - ordinalPositions[i]) :
0) :
val);
}
return ret;
},
/**
* Get the ordinal positions for the entire data set. This is necessary in
* chart panning because we need to find out what points or data groups are
* available outside the visible range. When a panning operation starts, if
* an index for the given grouping does not exists, it is created and
* cached. This index is deleted on updated data, so it will be regenerated
* the next time a panning operation starts.
*
* @private
* @function Highcharts.Axis#getExtendedPositions
*
* @return {Array<number>}
*/
getExtendedPositions: function () {
var axis = this, chart = axis.chart, grouping = axis.series[0].currentDataGrouping, ordinalIndex = axis.ordinalIndex, key = grouping ?
grouping.count + grouping.unitName :
'raw', overscroll = axis.options.overscroll, extremes = axis.getExtremes(), fakeAxis, fakeSeries;
// If this is the first time, or the ordinal index is deleted by
// updatedData,
// create it.
if (!ordinalIndex) {
ordinalIndex = axis.ordinalIndex = {};
}
if (!ordinalIndex[key]) {
// Create a fake axis object where the extended ordinal positions
// are emulated
fakeAxis = {
series: [],
chart: chart,
getExtremes: function () {
return {
min: extremes.dataMin,
max: extremes.dataMax + overscroll
};
},
options: {
ordinal: true
},
val2lin: Axis.prototype.val2lin,
ordinal2lin: Axis.prototype.ordinal2lin // #6276
};
// Add the fake series to hold the full data, then apply processData
// to it
axis.series.forEach(function (series) {
fakeSeries = {
xAxis: fakeAxis,
xData: series.xData.slice(),
chart: chart,
destroyGroupedData: noop
};
fakeSeries.xData = fakeSeries.xData.concat(axis.getOverscrollPositions());
fakeSeries.options = {
dataGrouping: grouping ? {
enabled: true,
forced: true,
// doesn't matter which, use the fastest
approximation: 'open',
units: [[
grouping.unitName,
[grouping.count]
]]
} : {
enabled: false
}
};
series.processData.apply(fakeSeries);
fakeAxis.series.push(fakeSeries);
});
// Run beforeSetTickPositions to compute the ordinalPositions
axis.beforeSetTickPositions.apply(fakeAxis);
// Cache it
ordinalIndex[key] = fakeAxis.ordinalPositions;
}
return ordinalIndex[key];
},
/**
* Get ticks for an ordinal axis within a range where points don't exist.
* It is required when overscroll is enabled. We can't base on points,
* because we may not have any, so we use approximated pointRange and
* generate these ticks between Axis.dataMax, Axis.dataMax + Axis.overscroll
* evenly spaced. Used in panning and navigator scrolling.
*
* @private
* @function Highcharts.Axis#getOverscrollPositions
*
* @returns {Array<number>}
* Generated ticks
*/
getOverscrollPositions: function () {
var axis = this, extraRange = axis.options.overscroll, distance = axis.overscrollPointsRange, positions = [], max = axis.dataMax;
if (defined(distance)) {
// Max + pointRange because we need to scroll to the last
positions.push(max);
while (max <= axis.dataMax + extraRange) {
max += distance;
positions.push(max);
}
}
return positions;
},
/**
* Find the factor to estimate how wide the plot area would have been if
* ordinal gaps were included. This value is used to compute an imagined
* plot width in order to establish the data grouping interval.
*
* A real world case is the intraday-candlestick example. Without this
* logic, it would show the correct data grouping when viewing a range
* within each day, but once moving the range to include the gap between two
* days, the interval would include the cut-away night hours and the data
* grouping would be wrong. So the below method tries to compensate by
* identifying the most common point interval, in this case days.
*
* An opposite case is presented in issue #718. We have a long array of
* daily data, then one point is appended one hour after the last point. We
* expect the data grouping not to change.
*
* In the future, if we find cases where this estimation doesn't work
* optimally, we might need to add a second pass to the data grouping logic,
* where we do another run with a greater interval if the number of data
* groups is more than a certain fraction of the desired group count.
*
* @private
* @function Highcharts.Axis#getGroupIntervalFactor
*
* @param {number} xMin
*
* @param {number} xMax
*
* @param {Highcharts.Series} series
*
* @return {number}
*/
getGroupIntervalFactor: function (xMin, xMax, series) {
var i, processedXData = series.processedXData, len = processedXData.length, distances = [], median, groupIntervalFactor = this.groupIntervalFactor;
// Only do this computation for the first series, let the other inherit
// it (#2416)
if (!groupIntervalFactor) {
// Register all the distances in an array
for (i = 0; i < len - 1; i++) {
distances[i] =
processedXData[i + 1] - processedXData[i];
}
// Sort them and find the median
distances.sort(function (a, b) {
return a - b;
});
median = distances[Math.floor(len / 2)];
// Compensate for series that don't extend through the entire axis
// extent. #1675.
xMin = Math.max(xMin, processedXData[0]);
xMax = Math.min(xMax, processedXData[len - 1]);
this.groupIntervalFactor = groupIntervalFactor =
(len * median) / (xMax - xMin);
}
// Return the factor needed for data grouping
return groupIntervalFactor;
},
/**
* Make the tick intervals closer because the ordinal gaps make the ticks
* spread out or cluster.
*
* @private
* @function Highcharts.Axis#postProcessTickInterval
*
* @param {number} tickInterval
*
* @return {number}
*/
postProcessTickInterval: function (tickInterval) {
// Problem: https://jsfiddle.net/highcharts/FQm4E/1/
// This is a case where this algorithm doesn't work optimally. In this
// case, the tick labels are spread out per week, but all the gaps
// reside within weeks. So we have a situation where the labels are
// courser than the ordinal gaps, and thus the tick interval should not
// be altered
var ordinalSlope = this.ordinalSlope, ret;
if (ordinalSlope) {
if (!this.options.breaks) {
ret = tickInterval / (ordinalSlope / this.closestPointRange);
}
else {
ret = this.closestPointRange || tickInterval; // #7275
}
}
else {
ret = tickInterval;
}
return ret;
}
});
// Record this to prevent overwriting by broken-axis module (#5979)
Axis.prototype.ordinal2lin = Axis.prototype.val2lin;
// Extending the Chart.pan method for ordinal axes
addEvent(Chart, 'pan', function (e) {
var chart = this, xAxis = chart.xAxis[0], overscroll = xAxis.options.overscroll, chartX = e.originalEvent.chartX, panning = chart.options.chart &&
chart.options.chart.panning, runBase = false;
if (panning &&
panning.type !== 'y' &&
xAxis.options.ordinal &&
xAxis.series.length) {
var mouseDownX = chart.mouseDownX, extremes = xAxis.getExtremes(), dataMax = extremes.dataMax, min = extremes.min, max = extremes.max, trimmedRange, hoverPoints = chart.hoverPoints, closestPointRange = xAxis.closestPointRange || xAxis.overscrollPointsRange, pointPixelWidth = (xAxis.translationSlope *
(xAxis.ordinalSlope || closestPointRange)),
// how many ordinal units did we move?
movedUnits = (mouseDownX - chartX) / pointPixelWidth,
// get index of all the chart's points
extendedAxis = { ordinalPositions: xAxis.getExtendedPositions() }, ordinalPositions, searchAxisLeft, lin2val = xAxis.lin2val, val2lin = xAxis.val2lin, searchAxisRight;
// we have an ordinal axis, but the data is equally spaced
if (!extendedAxis.ordinalPositions) {
runBase = true;
}
else if (Math.abs(movedUnits) > 1) {
// Remove active points for shared tooltip
if (hoverPoints) {
hoverPoints.forEach(function (point) {
point.setState();
});
}
if (movedUnits < 0) {
searchAxisLeft = extendedAxis;
searchAxisRight = xAxis.ordinalPositions ? xAxis : extendedAxis;
}
else {
searchAxisLeft = xAxis.ordinalPositions ? xAxis : extendedAxis;
searchAxisRight = extendedAxis;
}
// In grouped data series, the last ordinal position represents the
// grouped data, which is to the left of the real data max. If we
// don't compensate for this, we will be allowed to pan grouped data
// series passed the right of the plot area.
ordinalPositions = searchAxisRight.ordinalPositions;
if (dataMax >
ordinalPositions[ordinalPositions.length - 1]) {
ordinalPositions.push(dataMax);
}
// Get the new min and max values by getting the ordinal index for
// the current extreme, then add the moved units and translate back
// to values. This happens on the extended ordinal positions if the
// new position is out of range, else it happens on the current x
// axis which is smaller and faster.
chart.fixedRange = max - min;
trimmedRange = xAxis.toFixedRange(null, null, lin2val.apply(searchAxisLeft, [
val2lin.apply(searchAxisLeft, [min, true]) + movedUnits,
true // translate from index
]), lin2val.apply(searchAxisRight, [
val2lin.apply(searchAxisRight, [max, true]) + movedUnits,
true // translate from index
]));
// Apply it if it is within the available data range
if (trimmedRange.min >= Math.min(extremes.dataMin, min) &&
trimmedRange.max <= Math.max(dataMax, max) + overscroll) {
xAxis.setExtremes(trimmedRange.min, trimmedRange.max, true, false, { trigger: 'pan' });
}
chart.mouseDownX = chartX; // set new reference for next run
css(chart.container, { cursor: 'move' });
}
}
else {
runBase = true;
}
// revert to the linear chart.pan version
if (runBase || (panning && /y/.test(panning.type))) {
if (overscroll) {
xAxis.max = xAxis.dataMax + overscroll;
}
}
else {
e.preventDefault();
}
});
addEvent(Axis, 'foundExtremes', function () {
var axis = this;
if (axis.isXAxis &&
defined(axis.options.overscroll) &&
axis.max === axis.dataMax &&
(
// Panning is an execption,
// We don't want to apply overscroll when panning over the dataMax
!axis.chart.mouseIsDown ||
axis.isInternal) && (
// Scrollbar buttons are the other execption:
!axis.eventArgs ||
axis.eventArgs && axis.eventArgs.trigger !== 'navigator')) {
axis.max += axis.options.overscroll;
// Live data and buttons require translation for the min:
if (!axis.isInternal && defined(axis.userMin)) {
axis.min += axis.options.overscroll;
}
}
});
// For ordinal axis, that loads data async, redraw axis after data is loaded.
// If we don't do that, axis will have the same extremes as previously, but
// ordinal positions won't be calculated. See #10290
addEvent(Axis, 'afterSetScale', function () {
var axis = this;
if (axis.horiz && !axis.isDirty) {
axis.isDirty = axis.isOrdinal &&
axis.chart.navigator &&
!axis.chart.navigator.adaptToUpdatedData;
}
});

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,804 @@
/* *
*
* (c) 2010-2020 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import Highcharts from './Globals.js';
/**
* Function callback when a series point is clicked. Return false to cancel the
* action.
*
* @callback Highcharts.PointClickCallbackFunction
*
* @param {Highcharts.Point} this
* The point where the event occured.
*
* @param {Highcharts.PointClickEventObject} event
* Event arguments.
*/
/**
* Common information for a click event on a series point.
*
* @interface Highcharts.PointClickEventObject
* @extends Highcharts.PointerEventObject
*/ /**
* Clicked point.
* @name Highcharts.PointClickEventObject#point
* @type {Highcharts.Point}
*/
/**
* Configuration hash for the data label and tooltip formatters.
*
* @interface Highcharts.PointLabelObject
*/ /**
* The point's current color.
* @name Highcharts.PointLabelObject#color
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject|undefined}
*/ /**
* The point's current color index, used in styled mode instead of `color`. The
* color index is inserted in class names used for styling.
* @name Highcharts.PointLabelObject#colorIndex
* @type {number}
*/ /**
* The name of the related point.
* @name Highcharts.PointLabelObject#key
* @type {string|undefined}
*/ /**
* The percentage for related points in a stacked series or pies.
* @name Highcharts.PointLabelObject#percentage
* @type {number}
*/ /**
* The related point. The point name, if defined, is available through
* `this.point.name`.
* @name Highcharts.PointLabelObject#point
* @type {Highcharts.Point}
*/ /**
* The related series. The series name is available through `this.series.name`.
* @name Highcharts.PointLabelObject#series
* @type {Highcharts.Series}
*/ /**
* The total of values in either a stack for stacked series, or a pie in a pie
* series.
* @name Highcharts.PointLabelObject#total
* @type {number|undefined}
*/ /**
* For categorized axes this property holds the category name for the point. For
* other axes it holds the X value.
* @name Highcharts.PointLabelObject#x
* @type {number|string|undefined}
*/ /**
* The y value of the point.
* @name Highcharts.PointLabelObject#y
* @type {number|undefined}
*/
/**
* Gets fired when the mouse leaves the area close to the point.
*
* @callback Highcharts.PointMouseOutCallbackFunction
*
* @param {Highcharts.Point} this
* Point where the event occured.
*
* @param {global.PointerEvent} event
* Event that occured.
*/
/**
* Gets fired when the mouse enters the area close to the point.
*
* @callback Highcharts.PointMouseOverCallbackFunction
*
* @param {Highcharts.Point} this
* Point where the event occured.
*
* @param {global.Event} event
* Event that occured.
*/
/**
* The generic point options for all series.
*
* In TypeScript you have to extend `PointOptionsObject` with an additional
* declaration to allow custom data options:
*
* ```
* declare interface PointOptionsObject {
* customProperty: string;
* }
* ```
*
* @interface Highcharts.PointOptionsObject
*/
/**
* Possible option types for a data point.
*
* @typedef {number|string|Array<(number|string)>|Highcharts.PointOptionsObject|null} Highcharts.PointOptionsType
*/
/**
* Gets fired when the point is removed using the `.remove()` method.
*
* @callback Highcharts.PointRemoveCallbackFunction
*
* @param {Highcharts.Point} this
* Point where the event occured.
*
* @param {global.Event} event
* Event that occured.
*/
/**
* Possible key values for the point state options.
*
* @typedef {"hover"|"inactive"|"normal"|"select"} Highcharts.PointStateValue
*/
/**
* Gets fired when the point is updated programmatically through the `.update()`
* method.
*
* @callback Highcharts.PointUpdateCallbackFunction
*
* @param {Highcharts.Point} this
* Point where the event occured.
*
* @param {Highcharts.PointUpdateEventObject} event
* Event that occured.
*/
/**
* Information about the update event.
*
* @interface Highcharts.PointUpdateEventObject
* @extends global.Event
*/ /**
* Options data of the update event.
* @name Highcharts.PointUpdateEventObject#options
* @type {Highcharts.PointOptionsType}
*/
''; // detach doclet above
import U from './Utilities.js';
var animObject = U.animObject, defined = U.defined, erase = U.erase, extend = U.extend, format = U.format, getNestedProperty = U.getNestedProperty, isArray = U.isArray, isNumber = U.isNumber, isObject = U.isObject, syncTimeout = U.syncTimeout, pick = U.pick, removeEvent = U.removeEvent, uniqueKey = U.uniqueKey;
var H = Highcharts, fireEvent = H.fireEvent;
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* The Point object. The point objects are generated from the `series.data`
* configuration objects or raw numbers. They can be accessed from the
* `Series.points` array. Other ways to instantiate points are through {@link
* Highcharts.Series#addPoint} or {@link Highcharts.Series#setData}.
*
* @class
* @name Highcharts.Point
*/
var Point = /** @class */ (function () {
function Point() {
/* *
*
* Properties
*
* */
/**
* For categorized axes this property holds the category name for the
* point. For other axes it holds the X value.
*
* @name Highcharts.Point#category
* @type {string}
*/
this.category = void 0;
/**
* The point's current color index, used in styled mode instead of
* `color`. The color index is inserted in class names used for styling.
*
* @name Highcharts.Point#colorIndex
* @type {number}
*/
this.colorIndex = void 0;
this.formatPrefix = 'point';
this.id = void 0;
this.isNull = false;
/**
* The name of the point. The name can be given as the first position of the
* point configuration array, or as a `name` property in the configuration:
*
* @example
* // Array config
* data: [
* ['John', 1],
* ['Jane', 2]
* ]
*
* // Object config
* data: [{
* name: 'John',
* y: 1
* }, {
* name: 'Jane',
* y: 2
* }]
*
* @name Highcharts.Point#name
* @type {string}
*/
this.name = void 0;
/**
* The point's options as applied in the initial configuration, or
* extended through `Point.update`.
*
* In TypeScript you have to extend `PointOptionsObject` via an
* additional interface to allow custom data options:
*
* ```
* declare interface PointOptionsObject {
* customProperty: string;
* }
* ```
*
* @name Highcharts.Point#options
* @type {Highcharts.PointOptionsObject}
*/
this.options = void 0;
/**
* The percentage for points in a stacked series or pies.
*
* @name Highcharts.Point#percentage
* @type {number|undefined}
*/
this.percentage = void 0;
this.selected = false;
/**
* The series object associated with the point.
*
* @name Highcharts.Point#series
* @type {Highcharts.Series}
*/
this.series = void 0;
/**
* The total of values in either a stack for stacked series, or a pie in a
* pie series.
*
* @name Highcharts.Point#total
* @type {number|undefined}
*/
this.total = void 0;
/**
* For certain series types, like pie charts, where individual points can
* be shown or hidden.
*
* @name Highcharts.Point#visible
* @type {boolean}
* @default true
*/
this.visible = true;
this.x = void 0;
}
/* *
*
* Functions
*
* */
/**
* Animate SVG elements associated with the point.
*
* @private
* @function Highcharts.Point#animateBeforeDestroy
* @return {void}
*/
Point.prototype.animateBeforeDestroy = function () {
var point = this, animateParams = { x: point.startXPos, opacity: 0 }, isDataLabel, graphicalProps = point.getGraphicalProps();
graphicalProps.singular.forEach(function (prop) {
isDataLabel = prop === 'dataLabel';
point[prop] = point[prop].animate(isDataLabel ? {
x: point[prop].startXPos,
y: point[prop].startYPos,
opacity: 0
} : animateParams);
});
graphicalProps.plural.forEach(function (plural) {
point[plural].forEach(function (item) {
if (item.element) {
item.animate(extend({ x: point.startXPos }, (item.startYPos ? {
x: item.startXPos,
y: item.startYPos
} : {})));
}
});
});
};
/**
* Apply the options containing the x and y data and possible some extra
* properties. Called on point init or from point.update.
*
* @private
* @function Highcharts.Point#applyOptions
*
* @param {Highcharts.PointOptionsType} options
* The point options as defined in series.data.
*
* @param {number} [x]
* Optionally, the x value.
*
* @return {Highcharts.Point}
* The Point instance.
*/
Point.prototype.applyOptions = function (options, x) {
var point = this, series = point.series, pointValKey = series.options.pointValKey || series.pointValKey;
options = Point.prototype.optionsToObject.call(this, options);
// copy options directly to point
extend(point, options);
point.options = point.options ? extend(point.options, options) : options;
// Since options are copied into the Point instance, some accidental
// options must be shielded (#5681)
if (options.group) {
delete point.group;
}
if (options.dataLabels) {
delete point.dataLabels;
}
/**
* The y value of the point.
* @name Highcharts.Point#y
* @type {number|undefined}
*/
// For higher dimension series types. For instance, for ranges, point.y
// is mapped to point.low.
if (pointValKey) {
point.y = Point.prototype.getNestedProperty.call(point, pointValKey);
}
point.isNull = pick(point.isValid && !point.isValid(), point.x === null || !isNumber(point.y)); // #3571, check for NaN
point.formatPrefix = point.isNull ? 'null' : 'point'; // #9233, #10874
// The point is initially selected by options (#5777)
if (point.selected) {
point.state = 'select';
}
/**
* The x value of the point.
* @name Highcharts.Point#x
* @type {number}
*/
// If no x is set by now, get auto incremented value. All points must
// have an x value, however the y value can be null to create a gap in
// the series
if ('name' in point &&
typeof x === 'undefined' &&
series.xAxis &&
series.xAxis.hasNames) {
point.x = series.xAxis.nameToX(point);
}
if (typeof point.x === 'undefined' && series) {
if (typeof x === 'undefined') {
point.x = series.autoIncrement(point);
}
else {
point.x = x;
}
}
return point;
};
/**
* Destroy a point to clear memory. Its reference still stays in
* `series.data`.
*
* @private
* @function Highcharts.Point#destroy
* @return {void}
*/
Point.prototype.destroy = function () {
var point = this, series = point.series, chart = series.chart, dataSorting = series.options.dataSorting, hoverPoints = chart.hoverPoints, globalAnimation = point.series.chart.renderer.globalAnimation, animation = animObject(globalAnimation), prop;
/**
* Allow to call after animation.
* @private
*/
function destroyPoint() {
// Remove all events and elements
if (point.graphic || point.dataLabel || point.dataLabels) {
removeEvent(point);
point.destroyElements();
}
for (prop in point) { // eslint-disable-line guard-for-in
point[prop] = null;
}
}
if (point.legendItem) { // pies have legend items
chart.legend.destroyItem(point);
}
if (hoverPoints) {
point.setState();
erase(hoverPoints, point);
if (!hoverPoints.length) {
chart.hoverPoints = null;
}
}
if (point === chart.hoverPoint) {
point.onMouseOut();
}
// Remove properties after animation
if (!dataSorting || !dataSorting.enabled) {
destroyPoint();
}
else {
this.animateBeforeDestroy();
syncTimeout(destroyPoint, animation.duration);
}
chart.pointCount--;
};
/**
* Destroy SVG elements associated with the point.
*
* @private
* @function Highcharts.Point#destroyElements
* @param {Highcharts.Dictionary<number>} [kinds]
* @return {void}
*/
Point.prototype.destroyElements = function (kinds) {
var point = this, props = point.getGraphicalProps(kinds);
props.singular.forEach(function (prop) {
point[prop] = point[prop].destroy();
});
props.plural.forEach(function (plural) {
point[plural].forEach(function (item) {
if (item.element) {
item.destroy();
}
});
delete point[plural];
});
};
/**
* Fire an event on the Point object.
*
* @private
* @function Highcharts.Point#firePointEvent
*
* @param {string} eventType
* Type of the event.
*
* @param {Highcharts.Dictionary<any>|Event} [eventArgs]
* Additional event arguments.
*
* @param {Highcharts.EventCallbackFunction<Highcharts.Point>|Function} [defaultFunction]
* Default event handler.
*
* @fires Highcharts.Point#event:*
*/
Point.prototype.firePointEvent = function (eventType, eventArgs, defaultFunction) {
var point = this, series = this.series, seriesOptions = series.options;
// load event handlers on demand to save time on mouseover/out
if (seriesOptions.point.events[eventType] ||
(point.options &&
point.options.events &&
point.options.events[eventType])) {
point.importEvents();
}
// add default handler if in selection mode
if (eventType === 'click' && seriesOptions.allowPointSelect) {
defaultFunction = function (event) {
// Control key is for Windows, meta (= Cmd key) for Mac, Shift
// for Opera.
if (point.select) { // #2911
point.select(null, event.ctrlKey || event.metaKey || event.shiftKey);
}
};
}
fireEvent(point, eventType, eventArgs, defaultFunction);
};
/**
* Get the CSS class names for individual points. Used internally where the
* returned value is set on every point.
*
* @function Highcharts.Point#getClassName
*
* @return {string}
* The class names.
*/
Point.prototype.getClassName = function () {
var point = this;
return 'highcharts-point' +
(point.selected ? ' highcharts-point-select' : '') +
(point.negative ? ' highcharts-negative' : '') +
(point.isNull ? ' highcharts-null-point' : '') +
(typeof point.colorIndex !== 'undefined' ?
' highcharts-color-' + point.colorIndex : '') +
(point.options.className ? ' ' + point.options.className : '') +
(point.zone && point.zone.className ? ' ' +
point.zone.className.replace('highcharts-negative', '') : '');
};
/**
* Get props of all existing graphical point elements.
*
* @private
* @function Highcharts.Point#getGraphicalProps
* @param {Highcharts.Dictionary<number>} [kinds]
* @return {Highcharts.PointGraphicalProps}
*/
Point.prototype.getGraphicalProps = function (kinds) {
var point = this, props = [], prop, i, graphicalProps = { singular: [], plural: [] };
kinds = kinds || { graphic: 1, dataLabel: 1 };
if (kinds.graphic) {
props.push('graphic', 'shadowGroup');
}
if (kinds.dataLabel) {
props.push('dataLabel', 'dataLabelUpper', 'connector');
}
i = props.length;
while (i--) {
prop = props[i];
if (point[prop]) {
graphicalProps.singular.push(prop);
}
}
['dataLabel', 'connector'].forEach(function (prop) {
var plural = prop + 's';
if (kinds[prop] && point[plural]) {
graphicalProps.plural.push(plural);
}
});
return graphicalProps;
};
/**
* Return the configuration hash needed for the data label and tooltip
* formatters.
*
* @function Highcharts.Point#getLabelConfig
*
* @return {Highcharts.PointLabelObject}
* Abstract object used in formatters and formats.
*/
Point.prototype.getLabelConfig = function () {
return {
x: this.category,
y: this.y,
color: this.color,
colorIndex: this.colorIndex,
key: this.name || this.category,
series: this.series,
point: this,
percentage: this.percentage,
total: this.total || this.stackTotal
};
};
/**
* Returns the value of the point property for a given value.
* @private
*/
Point.prototype.getNestedProperty = function (key) {
if (!key) {
return;
}
if (key.indexOf('custom.') === 0) {
return getNestedProperty(key, this.options);
}
return this[key];
};
/**
* In a series with `zones`, return the zone that the point belongs to.
*
* @function Highcharts.Point#getZone
*
* @return {Highcharts.SeriesZonesOptionsObject}
* The zone item.
*/
Point.prototype.getZone = function () {
var series = this.series, zones = series.zones, zoneAxis = series.zoneAxis || 'y', i = 0, zone;
zone = zones[i];
while (this[zoneAxis] >= zone.value) {
zone = zones[++i];
}
// For resetting or reusing the point (#8100)
if (!this.nonZonedColor) {
this.nonZonedColor = this.color;
}
if (zone && zone.color && !this.options.color) {
this.color = zone.color;
}
else {
this.color = this.nonZonedColor;
}
return zone;
};
/**
* Utility to check if point has new shape type. Used in column series and
* all others that are based on column series.
*
* @return boolean|undefined
*/
Point.prototype.hasNewShapeType = function () {
var point = this;
var oldShapeType = point.graphic &&
(point.graphic.symbolName || point.graphic.element.nodeName);
return oldShapeType !== this.shapeType;
};
/**
* Initialize the point. Called internally based on the `series.data`
* option.
*
* @function Highcharts.Point#init
*
* @param {Highcharts.Series} series
* The series object containing this point.
*
* @param {Highcharts.PointOptionsType} options
* The data in either number, array or object format.
*
* @param {number} [x]
* Optionally, the X value of the point.
*
* @return {Highcharts.Point}
* The Point instance.
*
* @fires Highcharts.Point#event:afterInit
*/
Point.prototype.init = function (series, options, x) {
this.series = series;
this.applyOptions(options, x);
// Add a unique ID to the point if none is assigned
this.id = defined(this.id) ? this.id : uniqueKey();
this.resolveColor();
series.chart.pointCount++;
fireEvent(this, 'afterInit');
return this;
};
/**
* Transform number or array configs into objects. Also called for object
* configs. Used internally to unify the different configuration formats for
* points. For example, a simple number `10` in a line series will be
* transformed to `{ y: 10 }`, and an array config like `[1, 10]` in a
* scatter series will be transformed to `{ x: 1, y: 10 }`.
*
* @function Highcharts.Point#optionsToObject
*
* @param {Highcharts.PointOptionsType} options
* The input option.
*
* @return {Highcharts.Dictionary<*>}
* Transformed options.
*/
Point.prototype.optionsToObject = function (options) {
var ret = {}, series = this.series, keys = series.options.keys, pointArrayMap = keys || series.pointArrayMap || ['y'], valueCount = pointArrayMap.length, firstItemType, i = 0, j = 0;
if (isNumber(options) || options === null) {
ret[pointArrayMap[0]] = options;
}
else if (isArray(options)) {
// with leading x value
if (!keys && options.length > valueCount) {
firstItemType = typeof options[0];
if (firstItemType === 'string') {
ret.name = options[0];
}
else if (firstItemType === 'number') {
ret.x = options[0];
}
i++;
}
while (j < valueCount) {
// Skip undefined positions for keys
if (!keys || typeof options[i] !== 'undefined') {
if (pointArrayMap[j].indexOf('.') > 0) {
// Handle nested keys, e.g. ['color.pattern.image']
// Avoid function call unless necessary.
Point.prototype.setNestedProperty(ret, options[i], pointArrayMap[j]);
}
else {
ret[pointArrayMap[j]] = options[i];
}
}
i++;
j++;
}
}
else if (typeof options === 'object') {
ret = options;
// This is the fastest way to detect if there are individual point
// dataLabels that need to be considered in drawDataLabels. These
// can only occur in object configs.
if (options.dataLabels) {
series._hasPointLabels = true;
}
// Same approach as above for markers
if (options.marker) {
series._hasPointMarkers = true;
}
}
return ret;
};
/**
* @private
* @function Highcharts.Point#resolveColor
* @return {void}
*/
Point.prototype.resolveColor = function () {
var series = this.series, colors, optionsChart = series.chart.options.chart, colorCount = optionsChart.colorCount, styledMode = series.chart.styledMode, colorIndex;
/**
* The point's current color.
*
* @name Highcharts.Point#color
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject|undefined}
*/
if (!styledMode && !this.options.color) {
this.color = series.color; // #3445
}
if (series.options.colorByPoint) {
if (!styledMode) {
colors = series.options.colors || series.chart.options.colors;
this.color = this.color || colors[series.colorCounter];
colorCount = colors.length;
}
colorIndex = series.colorCounter;
series.colorCounter++;
// loop back to zero
if (series.colorCounter === colorCount) {
series.colorCounter = 0;
}
}
else {
colorIndex = series.colorIndex;
}
this.colorIndex = pick(this.colorIndex, colorIndex);
};
/**
* Set a value in an object, on the property defined by key. The key
* supports nested properties using dot notation. The function modifies the
* input object and does not make a copy.
*
* @function Highcharts.Point#setNestedProperty<T>
*
* @param {T} object
* The object to set the value on.
*
* @param {*} value
* The value to set.
*
* @param {string} key
* Key to the property to set.
*
* @return {T}
* The modified object.
*/
Point.prototype.setNestedProperty = function (object, value, key) {
var nestedKeys = key.split('.');
nestedKeys.reduce(function (result, key, i, arr) {
var isLastKey = arr.length - 1 === i;
result[key] = (isLastKey ?
value :
isObject(result[key], true) ?
result[key] :
{});
return result[key];
}, object);
return object;
};
/**
* Extendable method for formatting each point's tooltip line.
*
* @function Highcharts.Point#tooltipFormatter
*
* @param {string} pointFormat
* The point format.
*
* @return {string}
* A string to be concatenated in to the common tooltip text.
*/
Point.prototype.tooltipFormatter = function (pointFormat) {
// Insert options for valueDecimals, valuePrefix, and valueSuffix
var series = this.series, seriesTooltipOptions = series.tooltipOptions, valueDecimals = pick(seriesTooltipOptions.valueDecimals, ''), valuePrefix = seriesTooltipOptions.valuePrefix || '', valueSuffix = seriesTooltipOptions.valueSuffix || '';
// Replace default point style with class name
if (series.chart.styledMode) {
pointFormat =
series.chart.tooltip.styledModeFormat(pointFormat);
}
// Loop over the point array map and replace unformatted values with
// sprintf formatting markup
(series.pointArrayMap || ['y']).forEach(function (key) {
key = '{point.' + key; // without the closing bracket
if (valuePrefix || valueSuffix) {
pointFormat = pointFormat.replace(RegExp(key + '}', 'g'), valuePrefix + key + '}' + valueSuffix);
}
pointFormat = pointFormat.replace(RegExp(key + '}', 'g'), key + ':,.' + valueDecimals + 'f}');
});
return format(pointFormat, {
point: this,
series: this.series
}, series.chart);
};
return Point;
}());
H.Point = Point;
export default H.Point;

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,258 @@
/* *
*
* (c) 2010-2020 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from './Globals.js';
/**
* A callback function to gain complete control on when the responsive rule
* applies.
*
* @callback Highcharts.ResponsiveCallbackFunction
*
* @param {Highcharts.Chart} this
* Chart context.
*
* @return {boolean}
* Return `true` if it applies.
*/
import './Chart.js';
import U from './Utilities.js';
var find = U.find, isArray = U.isArray, isObject = U.isObject, merge = U.merge, objectEach = U.objectEach, pick = U.pick, splat = U.splat, uniqueKey = U.uniqueKey;
var Chart = H.Chart;
/**
* Allows setting a set of rules to apply for different screen or chart
* sizes. Each rule specifies additional chart options.
*
* @sample {highstock} stock/demo/responsive/
* Stock chart
* @sample highcharts/responsive/axis/
* Axis
* @sample highcharts/responsive/legend/
* Legend
* @sample highcharts/responsive/classname/
* Class name
*
* @since 5.0.0
* @apioption responsive
*/
/**
* A set of rules for responsive settings. The rules are executed from
* the top down.
*
* @sample {highcharts} highcharts/responsive/axis/
* Axis changes
* @sample {highstock} highcharts/responsive/axis/
* Axis changes
* @sample {highmaps} highcharts/responsive/axis/
* Axis changes
*
* @type {Array<*>}
* @since 5.0.0
* @apioption responsive.rules
*/
/**
* A full set of chart options to apply as overrides to the general
* chart options. The chart options are applied when the given rule
* is active.
*
* A special case is configuration objects that take arrays, for example
* [xAxis](#xAxis), [yAxis](#yAxis) or [series](#series). For these
* collections, an `id` option is used to map the new option set to
* an existing object. If an existing object of the same id is not found,
* the item of the same indexupdated. So for example, setting `chartOptions`
* with two series items without an `id`, will cause the existing chart's
* two series to be updated with respective options.
*
* @sample {highstock} stock/demo/responsive/
* Stock chart
* @sample highcharts/responsive/axis/
* Axis
* @sample highcharts/responsive/legend/
* Legend
* @sample highcharts/responsive/classname/
* Class name
*
* @type {Highcharts.Options}
* @since 5.0.0
* @apioption responsive.rules.chartOptions
*/
/**
* Under which conditions the rule applies.
*
* @since 5.0.0
* @apioption responsive.rules.condition
*/
/**
* A callback function to gain complete control on when the responsive
* rule applies. Return `true` if it applies. This opens for checking
* against other metrics than the chart size, for example the document
* size or other elements.
*
* @type {Highcharts.ResponsiveCallbackFunction}
* @since 5.0.0
* @context Highcharts.Chart
* @apioption responsive.rules.condition.callback
*/
/**
* The responsive rule applies if the chart height is less than this.
*
* @type {number}
* @since 5.0.0
* @apioption responsive.rules.condition.maxHeight
*/
/**
* The responsive rule applies if the chart width is less than this.
*
* @sample highcharts/responsive/axis/
* Max width is 500
*
* @type {number}
* @since 5.0.0
* @apioption responsive.rules.condition.maxWidth
*/
/**
* The responsive rule applies if the chart height is greater than this.
*
* @type {number}
* @default 0
* @since 5.0.0
* @apioption responsive.rules.condition.minHeight
*/
/**
* The responsive rule applies if the chart width is greater than this.
*
* @type {number}
* @default 0
* @since 5.0.0
* @apioption responsive.rules.condition.minWidth
*/
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* Update the chart based on the current chart/document size and options for
* responsiveness.
*
* @private
* @function Highcharts.Chart#setResponsive
* @param {boolean} [redraw=true]
* @param {boolean} [reset=false]
* Reset by un-applying all rules. Chart.update resets all rules before
* applying updated options.
* @return {void}
*/
Chart.prototype.setResponsive = function (redraw, reset) {
var options = this.options.responsive, ruleIds = [], currentResponsive = this.currentResponsive, currentRuleIds, undoOptions;
if (!reset && options && options.rules) {
options.rules.forEach(function (rule) {
if (typeof rule._id === 'undefined') {
rule._id = uniqueKey();
}
this.matchResponsiveRule(rule, ruleIds /* , redraw */);
}, this);
}
// Merge matching rules
var mergedOptions = merge.apply(0, ruleIds.map(function (ruleId) {
return find(options.rules, function (rule) {
return rule._id === ruleId;
}).chartOptions;
}));
mergedOptions.isResponsiveOptions = true;
// Stringified key for the rules that currently apply.
ruleIds = (ruleIds.toString() || void 0);
currentRuleIds = currentResponsive && currentResponsive.ruleIds;
// Changes in what rules apply
if (ruleIds !== currentRuleIds) {
// Undo previous rules. Before we apply a new set of rules, we need to
// roll back completely to base options (#6291).
if (currentResponsive) {
this.update(currentResponsive.undoOptions, redraw, true);
}
if (ruleIds) {
// Get undo-options for matching rules
undoOptions = this.currentOptions(mergedOptions);
undoOptions.isResponsiveOptions = true;
this.currentResponsive = {
ruleIds: ruleIds,
mergedOptions: mergedOptions,
undoOptions: undoOptions
};
this.update(mergedOptions, redraw, true);
}
else {
this.currentResponsive = void 0;
}
}
};
/**
* Handle a single responsiveness rule.
*
* @private
* @function Highcharts.Chart#matchResponsiveRule
* @param {Highcharts.ResponsiveRulesOptions} rule
* @param {Array<string>} matches
* @return {void}
*/
Chart.prototype.matchResponsiveRule = function (rule, matches) {
var condition = rule.condition, fn = condition.callback || function () {
return (this.chartWidth <= pick(condition.maxWidth, Number.MAX_VALUE) &&
this.chartHeight <=
pick(condition.maxHeight, Number.MAX_VALUE) &&
this.chartWidth >= pick(condition.minWidth, 0) &&
this.chartHeight >= pick(condition.minHeight, 0));
};
if (fn.call(this)) {
matches.push(rule._id);
}
};
/**
* Get the current values for a given set of options. Used before we update
* the chart with a new responsiveness rule.
* TODO: Restore axis options (by id?)
*
* @private
* @function Highcharts.Chart#currentOptions
* @param {Highcharts.Options} options
* @return {Highcharts.Options}
*/
Chart.prototype.currentOptions = function (options) {
var chart = this, ret = {};
/**
* Recurse over a set of options and its current values,
* and store the current values in the ret object.
*/
function getCurrent(options, curr, ret, depth) {
var i;
objectEach(options, function (val, key) {
if (!depth &&
chart.collectionsWithUpdate.indexOf(key) > -1) {
val = splat(val);
ret[key] = [];
// Iterate over collections like series, xAxis or yAxis and map
// the items by index.
for (i = 0; i < val.length; i++) {
if (curr[key][i]) { // Item exists in current data (#6347)
ret[key][i] = {};
getCurrent(val[i], curr[key][i], ret[key][i], depth + 1);
}
}
}
else if (isObject(val)) {
ret[key] = isArray(val) ? [] : {};
getCurrent(val, curr[key] || {}, ret[key], depth + 1);
}
else if (typeof curr[key] === 'undefined') { // #10286
ret[key] = null;
}
else {
ret[key] = curr[key];
}
});
}
getCurrent(options, this.options, ret, 0);
return ret;
};

View File

@@ -0,0 +1,252 @@
/* *
*
* (c) 2010-2020 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from './Globals.js';
import U from './Utilities.js';
var addEvent = U.addEvent, seriesType = U.seriesType;
import './Options.js';
import './Series.js';
var Series = H.Series;
/**
* Scatter series type.
*
* @private
* @class
* @name Highcharts.seriesTypes.scatter
*
* @augments Highcharts.Series
*/
seriesType('scatter', 'line',
/**
* A scatter plot uses cartesian coordinates to display values for two
* variables for a set of data.
*
* @sample {highcharts} highcharts/demo/scatter/
* Scatter plot
*
* @extends plotOptions.line
* @excluding pointPlacement, shadow, useOhlcData
* @product highcharts highstock
* @optionparent plotOptions.scatter
*/
{
/**
* The width of the line connecting the data points.
*
* @sample {highcharts} highcharts/plotoptions/scatter-linewidth-none/
* 0 by default
* @sample {highcharts} highcharts/plotoptions/scatter-linewidth-1/
* 1px
*
* @product highcharts highstock
*/
lineWidth: 0,
findNearestPointBy: 'xy',
/**
* Apply a jitter effect for the rendered markers. When plotting
* discrete values, a little random noise may help telling the points
* apart. The jitter setting applies a random displacement of up to `n`
* axis units in either direction. So for example on a horizontal X
* axis, setting the `jitter.x` to 0.24 will render the point in a
* random position between 0.24 units to the left and 0.24 units to the
* right of the true axis position. On a category axis, setting it to
* 0.5 will fill up the bin and make the data appear continuous.
*
* When rendered on top of a box plot or a column series, a jitter value
* of 0.24 will correspond to the underlying series' default
* [groupPadding](
* https://api.highcharts.com/highcharts/plotOptions.column.groupPadding)
* and [pointPadding](
* https://api.highcharts.com/highcharts/plotOptions.column.pointPadding)
* settings.
*
* @sample {highcharts} highcharts/series-scatter/jitter
* Jitter on a scatter plot
*
* @sample {highcharts} highcharts/series-scatter/jitter-boxplot
* Jittered scatter plot on top of a box plot
*
* @product highcharts highstock
* @since 7.0.2
*/
jitter: {
/**
* The maximal X offset for the random jitter effect.
*/
x: 0,
/**
* The maximal Y offset for the random jitter effect.
*/
y: 0
},
marker: {
enabled: true // Overrides auto-enabling in line series (#3647)
},
/**
* Sticky tracking of mouse events. When true, the `mouseOut` event
* on a series isn't triggered until the mouse moves over another
* series, or out of the plot area. When false, the `mouseOut` event on
* a series is triggered when the mouse leaves the area around the
* series' graph or markers. This also implies the tooltip. When
* `stickyTracking` is false and `tooltip.shared` is false, the tooltip
* will be hidden when moving the mouse between series.
*
* @type {boolean}
* @default false
* @product highcharts highstock
* @apioption plotOptions.scatter.stickyTracking
*/
/**
* A configuration object for the tooltip rendering of each single
* series. Properties are inherited from [tooltip](#tooltip).
* Overridable properties are `headerFormat`, `pointFormat`,
* `yDecimals`, `xDateFormat`, `yPrefix` and `ySuffix`. Unlike other
* series, in a scatter plot the series.name by default shows in the
* headerFormat and point.x and point.y in the pointFormat.
*
* @product highcharts highstock
*/
tooltip: {
headerFormat: '<span style="color:{point.color}">\u25CF</span> ' +
'<span style="font-size: 10px"> {series.name}</span><br/>',
pointFormat: 'x: <b>{point.x}</b><br/>y: <b>{point.y}</b><br/>'
}
// Prototype members
}, {
sorted: false,
requireSorting: false,
noSharedTooltip: true,
trackerGroups: ['group', 'markerGroup', 'dataLabelsGroup'],
takeOrdinalPosition: false,
/* eslint-disable valid-jsdoc */
/**
* @private
* @function Highcharts.seriesTypes.scatter#drawGraph
*/
drawGraph: function () {
if (this.options.lineWidth) {
Series.prototype.drawGraph.call(this);
}
},
// Optionally add the jitter effect
applyJitter: function () {
var series = this, jitter = this.options.jitter, len = this.points.length;
/**
* Return a repeatable, pseudo-random number based on an integer
* seed.
* @private
*/
function unrandom(seed) {
var rand = Math.sin(seed) * 10000;
return rand - Math.floor(rand);
}
if (jitter) {
this.points.forEach(function (point, i) {
['x', 'y'].forEach(function (dim, j) {
var axis, plotProp = 'plot' + dim.toUpperCase(), min, max, translatedJitter;
if (jitter[dim] && !point.isNull) {
axis = series[dim + 'Axis'];
translatedJitter =
jitter[dim] * axis.transA;
if (axis && !axis.isLog) {
// Identify the outer bounds of the jitter range
min = Math.max(0, point[plotProp] - translatedJitter);
max = Math.min(axis.len, point[plotProp] + translatedJitter);
// Find a random position within this range
point[plotProp] = min +
(max - min) * unrandom(i + j * len);
// Update clientX for the tooltip k-d-tree
if (dim === 'x') {
point.clientX = point.plotX;
}
}
}
});
});
}
}
/* eslint-enable valid-jsdoc */
});
/* eslint-disable no-invalid-this */
addEvent(Series, 'afterTranslate', function () {
if (this.applyJitter) {
this.applyJitter();
}
});
/* eslint-enable no-invalid-this */
/**
* A `scatter` series. If the [type](#series.scatter.type) option is
* not specified, it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.scatter
* @excluding dataParser, dataURL, useOhlcData
* @product highcharts highstock
* @apioption series.scatter
*/
/**
* An array of data points for the series. For the `scatter` series
* type, points can be given in the following ways:
*
* 1. An array of numerical values. In this case, the numerical values will be
* interpreted as `y` options. The `x` values will be automatically
* calculated, either starting at 0 and incremented by 1, or from
* `pointStart` and `pointInterval` given in the series options. If the axis
* has categories, these will be used. Example:
* ```js
* data: [0, 5, 3, 5]
* ```
*
* 2. An array of arrays with 2 values. In this case, the values correspond to
* `x,y`. If the first value is a string, it is applied as the name of the
* point, and the `x` value is inferred.
* ```js
* data: [
* [0, 0],
* [1, 8],
* [2, 9]
* ]
* ```
*
* 3. An array of objects with named values. The following snippet shows only a
* few settings, see the complete options set below. If the total number of
* data points exceeds the series'
* [turboThreshold](#series.scatter.turboThreshold), this option is not
* available.
* ```js
* data: [{
* x: 1,
* y: 2,
* name: "Point2",
* color: "#00FF00"
* }, {
* x: 1,
* y: 4,
* name: "Point1",
* color: "#FF00FF"
* }]
* ```
*
* @sample {highcharts} highcharts/chart/reflow-true/
* Numerical values
* @sample {highcharts} highcharts/series/data-array-of-arrays/
* Arrays of numeric x and y
* @sample {highcharts} highcharts/series/data-array-of-arrays-datetime/
* Arrays of datetime x and y
* @sample {highcharts} highcharts/series/data-array-of-name-value/
* Arrays of point.name and y
* @sample {highcharts} highcharts/series/data-array-of-objects/
* Config objects
*
* @type {Array<number|Array<(number|string),(number|null)>|null|*>}
* @extends series.line.data
* @product highcharts highstock
* @apioption series.scatter.data
*/
''; // adds doclets above to transpilat

View File

@@ -0,0 +1,360 @@
/* *
*
* (c) 2010-2020 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* Highcharts feature to make the Y axis stay fixed when scrolling the chart
* horizontally on mobile devices. Supports left and right side axes.
*/
/*
WIP on vertical scrollable plot area (#9378). To do:
- Bottom axis positioning
- Test with Gantt
- Look for size optimizing the code
- API and demos
*/
'use strict';
import H from './Globals.js';
import U from './Utilities.js';
var addEvent = U.addEvent, createElement = U.createElement, pick = U.pick, stop = U.stop;
var Chart = H.Chart;
/**
* Options for a scrollable plot area. This feature provides a minimum size for
* the plot area of the chart. If the size gets smaller than this, typically
* on mobile devices, a native browser scrollbar is presented. This scrollbar
* provides smooth scrolling for the contents of the plot area, whereas the
* title, legend and unaffected axes are fixed.
*
* Since v7.1.2, a scrollable plot area can be defined for either horizontal or
* vertical scrolling, depending on whether the `minWidth` or `minHeight`
* option is set.
*
* @sample highcharts/chart/scrollable-plotarea
* Scrollable plot area
* @sample highcharts/chart/scrollable-plotarea-vertical
* Vertically scrollable plot area
* @sample {gantt} highcharts/chart/scrollable-plotarea-vertical
* Gantt chart with vertically scrollable plot area
*
* @since 6.1.0
* @product highcharts gantt
* @apioption chart.scrollablePlotArea
*/
/**
* The minimum height for the plot area. If it gets smaller than this, the plot
* area will become scrollable.
*
* @type {number}
* @apioption chart.scrollablePlotArea.minHeight
*/
/**
* The minimum width for the plot area. If it gets smaller than this, the plot
* area will become scrollable.
*
* @type {number}
* @apioption chart.scrollablePlotArea.minWidth
*/
/**
* The initial scrolling position of the scrollable plot area. Ranges from 0 to
* 1, where 0 aligns the plot area to the left and 1 aligns it to the right.
* Typically we would use 1 if the chart has right aligned Y axes.
*
* @type {number}
* @apioption chart.scrollablePlotArea.scrollPositionX
*/
/**
* The initial scrolling position of the scrollable plot area. Ranges from 0 to
* 1, where 0 aligns the plot area to the top and 1 aligns it to the bottom.
*
* @type {number}
* @apioption chart.scrollablePlotArea.scrollPositionY
*/
/**
* The opacity of mask applied on one of the sides of the plot
* area.
*
* @sample {highcharts} highcharts/chart/scrollable-plotarea-opacity
* Disabled opacity for the mask
*
* @type {number}
* @default 0.85
* @since 7.1.1
* @apioption chart.scrollablePlotArea.opacity
*/
''; // detach API doclets
/* eslint-disable no-invalid-this, valid-jsdoc */
addEvent(Chart, 'afterSetChartSize', function (e) {
var scrollablePlotArea = this.options.chart.scrollablePlotArea, scrollableMinWidth = scrollablePlotArea && scrollablePlotArea.minWidth, scrollableMinHeight = scrollablePlotArea && scrollablePlotArea.minHeight, scrollablePixelsX, scrollablePixelsY, corrections;
if (!this.renderer.forExport) {
// The amount of pixels to scroll, the difference between chart
// width and scrollable width
if (scrollableMinWidth) {
this.scrollablePixelsX = scrollablePixelsX = Math.max(0, scrollableMinWidth - this.chartWidth);
if (scrollablePixelsX) {
this.plotWidth += scrollablePixelsX;
if (this.inverted) {
this.clipBox.height += scrollablePixelsX;
this.plotBox.height += scrollablePixelsX;
}
else {
this.clipBox.width += scrollablePixelsX;
this.plotBox.width += scrollablePixelsX;
}
corrections = {
// Corrections for right side
1: { name: 'right', value: scrollablePixelsX }
};
}
// Currently we can only do either X or Y
}
else if (scrollableMinHeight) {
this.scrollablePixelsY = scrollablePixelsY = Math.max(0, scrollableMinHeight - this.chartHeight);
if (scrollablePixelsY) {
this.plotHeight += scrollablePixelsY;
if (this.inverted) {
this.clipBox.width += scrollablePixelsY;
this.plotBox.width += scrollablePixelsY;
}
else {
this.clipBox.height += scrollablePixelsY;
this.plotBox.height += scrollablePixelsY;
}
corrections = {
2: { name: 'bottom', value: scrollablePixelsY }
};
}
}
if (corrections && !e.skipAxes) {
this.axes.forEach(function (axis) {
// For right and bottom axes, only fix the plot line length
if (corrections[axis.side]) {
// Get the plot lines right in getPlotLinePath,
// temporarily set it to the adjusted plot width.
axis.getPlotLinePath = function () {
var marginName = corrections[axis.side].name, correctionValue = corrections[axis.side].value,
// axis.right or axis.bottom
margin = this[marginName], path;
// Temporarily adjust
this[marginName] = margin - correctionValue;
path = H.Axis.prototype.getPlotLinePath.apply(this, arguments);
// Reset
this[marginName] = margin;
return path;
};
}
else {
// Apply the corrected plotWidth
axis.setAxisSize();
axis.setAxisTranslation();
}
});
}
}
});
addEvent(Chart, 'render', function () {
if (this.scrollablePixelsX || this.scrollablePixelsY) {
if (this.setUpScrolling) {
this.setUpScrolling();
}
this.applyFixed();
}
else if (this.fixedDiv) { // Has been in scrollable mode
this.applyFixed();
}
});
/**
* @private
* @function Highcharts.Chart#setUpScrolling
* @return {void}
*/
Chart.prototype.setUpScrolling = function () {
var _this = this;
var attribs = {
WebkitOverflowScrolling: 'touch',
overflowX: 'hidden',
overflowY: 'hidden'
};
if (this.scrollablePixelsX) {
attribs.overflowX = 'auto';
}
if (this.scrollablePixelsY) {
attribs.overflowY = 'auto';
}
// Add the necessary divs to provide scrolling
this.scrollingContainer = createElement('div', {
'className': 'highcharts-scrolling'
}, attribs, this.renderTo);
// On scroll, reset the chart position because it applies to the scrolled
// container
addEvent(this.scrollingContainer, 'scroll', function () {
if (_this.pointer) {
delete _this.pointer.chartPosition;
}
});
this.innerContainer = createElement('div', {
'className': 'highcharts-inner-container'
}, null, this.scrollingContainer);
// Now move the container inside
this.innerContainer.appendChild(this.container);
// Don't run again
this.setUpScrolling = null;
};
/**
* These elements are moved over to the fixed renderer and stay fixed when the
* user scrolls the chart
* @private
*/
Chart.prototype.moveFixedElements = function () {
var container = this.container, fixedRenderer = this.fixedRenderer, fixedSelectors = [
'.highcharts-contextbutton',
'.highcharts-credits',
'.highcharts-legend',
'.highcharts-legend-checkbox',
'.highcharts-navigator-series',
'.highcharts-navigator-xaxis',
'.highcharts-navigator-yaxis',
'.highcharts-navigator',
'.highcharts-reset-zoom',
'.highcharts-scrollbar',
'.highcharts-subtitle',
'.highcharts-title'
], axisClass;
if (this.scrollablePixelsX && !this.inverted) {
axisClass = '.highcharts-yaxis';
}
else if (this.scrollablePixelsX && this.inverted) {
axisClass = '.highcharts-xaxis';
}
else if (this.scrollablePixelsY && !this.inverted) {
axisClass = '.highcharts-xaxis';
}
else if (this.scrollablePixelsY && this.inverted) {
axisClass = '.highcharts-yaxis';
}
fixedSelectors.push(axisClass, axisClass + '-labels');
fixedSelectors.forEach(function (className) {
[].forEach.call(container.querySelectorAll(className), function (elem) {
(elem.namespaceURI === fixedRenderer.SVG_NS ?
fixedRenderer.box :
fixedRenderer.box.parentNode).appendChild(elem);
elem.style.pointerEvents = 'auto';
});
});
};
/**
* @private
* @function Highcharts.Chart#applyFixed
* @return {void}
*/
Chart.prototype.applyFixed = function () {
var fixedRenderer, scrollableWidth, scrollableHeight, firstTime = !this.fixedDiv, scrollableOptions = this.options.chart.scrollablePlotArea;
// First render
if (firstTime) {
this.fixedDiv = createElement('div', {
className: 'highcharts-fixed'
}, {
position: 'absolute',
overflow: 'hidden',
pointerEvents: 'none',
zIndex: 2
}, null, true);
this.renderTo.insertBefore(this.fixedDiv, this.renderTo.firstChild);
this.renderTo.style.overflow = 'visible';
this.fixedRenderer = fixedRenderer = new H.Renderer(this.fixedDiv, this.chartWidth, this.chartHeight);
// Mask
this.scrollableMask = fixedRenderer
.path()
.attr({
fill: this.options.chart.backgroundColor || '#fff',
'fill-opacity': pick(scrollableOptions.opacity, 0.85),
zIndex: -1
})
.addClass('highcharts-scrollable-mask')
.add();
this.moveFixedElements();
addEvent(this, 'afterShowResetZoom', this.moveFixedElements);
addEvent(this, 'afterLayOutTitles', this.moveFixedElements);
}
else {
// Set the size of the fixed renderer to the visible width
this.fixedRenderer.setSize(this.chartWidth, this.chartHeight);
}
// Increase the size of the scrollable renderer and background
scrollableWidth = this.chartWidth + (this.scrollablePixelsX || 0);
scrollableHeight = this.chartHeight + (this.scrollablePixelsY || 0);
stop(this.container);
this.container.style.width = scrollableWidth + 'px';
this.container.style.height = scrollableHeight + 'px';
this.renderer.boxWrapper.attr({
width: scrollableWidth,
height: scrollableHeight,
viewBox: [0, 0, scrollableWidth, scrollableHeight].join(' ')
});
this.chartBackground.attr({
width: scrollableWidth,
height: scrollableHeight
});
if (this.scrollablePixelsY) {
this.scrollingContainer.style.height = this.chartHeight + 'px';
}
// Set scroll position
if (firstTime) {
if (scrollableOptions.scrollPositionX) {
this.scrollingContainer.scrollLeft =
this.scrollablePixelsX *
scrollableOptions.scrollPositionX;
}
if (scrollableOptions.scrollPositionY) {
this.scrollingContainer.scrollTop =
this.scrollablePixelsY *
scrollableOptions.scrollPositionY;
}
}
// Mask behind the left and right side
var axisOffset = this.axisOffset, maskTop = this.plotTop - axisOffset[0] - 1, maskLeft = this.plotLeft - axisOffset[3] - 1, maskBottom = this.plotTop + this.plotHeight + axisOffset[2] + 1, maskRight = this.plotLeft + this.plotWidth + axisOffset[1] + 1, maskPlotRight = this.plotLeft + this.plotWidth -
(this.scrollablePixelsX || 0), maskPlotBottom = this.plotTop + this.plotHeight -
(this.scrollablePixelsY || 0), d;
if (this.scrollablePixelsX) {
d = [
// Left side
'M', 0, maskTop,
'L', this.plotLeft - 1, maskTop,
'L', this.plotLeft - 1, maskBottom,
'L', 0, maskBottom,
'Z',
// Right side
'M', maskPlotRight, maskTop,
'L', this.chartWidth, maskTop,
'L', this.chartWidth, maskBottom,
'L', maskPlotRight, maskBottom,
'Z'
];
}
else if (this.scrollablePixelsY) {
d = [
// Top side
'M', maskLeft, 0,
'L', maskLeft, this.plotTop - 1,
'L', maskRight, this.plotTop - 1,
'L', maskRight, 0,
'Z',
// Bottom side
'M', maskLeft, maskPlotBottom,
'L', maskLeft, this.chartHeight,
'L', maskRight, this.chartHeight,
'L', maskRight, maskPlotBottom,
'Z'
];
}
else {
d = ['M', 0, 0];
}
if (this.redrawTrigger !== 'adjustHeight') {
this.scrollableMask.attr({
d: d
});
}
};

View File

@@ -0,0 +1,914 @@
/* *
*
* (c) 2010-2020 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from './Globals.js';
import U from './Utilities.js';
var addEvent = U.addEvent, correctFloat = U.correctFloat, defined = U.defined, destroyObjectProperties = U.destroyObjectProperties, fireEvent = U.fireEvent, merge = U.merge, pick = U.pick, removeEvent = U.removeEvent;
import './Axis.js';
import './Options.js';
var Axis = H.Axis, defaultOptions = H.defaultOptions, hasTouch = H.hasTouch, isTouchDevice = H.isTouchDevice, swapXY;
/**
*
* The scrollbar is a means of panning over the X axis of a stock chart.
* Scrollbars can also be applied to other types of axes.
*
* Another approach to scrollable charts is the [chart.scrollablePlotArea](
* https://api.highcharts.com/highcharts/chart.scrollablePlotArea) option that
* is especially suitable for simpler cartesian charts on mobile.
*
* In styled mode, all the presentational options for the
* scrollbar are replaced by the classes `.highcharts-scrollbar-thumb`,
* `.highcharts-scrollbar-arrow`, `.highcharts-scrollbar-button`,
* `.highcharts-scrollbar-rifles` and `.highcharts-scrollbar-track`.
*
* @sample stock/yaxis/inverted-bar-scrollbar/
* A scrollbar on a simple bar chart
*
* @product highstock gantt
* @optionparent scrollbar
*/
var defaultScrollbarOptions = {
/**
* The height of the scrollbar. The height also applies to the width
* of the scroll arrows so that they are always squares. Defaults to
* 20 for touch devices and 14 for mouse devices.
*
* @sample stock/scrollbar/height/
* A 30px scrollbar
*
* @type {number}
* @default 20/14
*/
height: isTouchDevice ? 20 : 14,
/**
* The border rounding radius of the bar.
*
* @sample stock/scrollbar/style/
* Scrollbar styling
*/
barBorderRadius: 0,
/**
* The corner radius of the scrollbar buttons.
*
* @sample stock/scrollbar/style/
* Scrollbar styling
*/
buttonBorderRadius: 0,
/**
* Enable or disable the scrollbar.
*
* @sample stock/scrollbar/enabled/
* Disable the scrollbar, only use navigator
*
* @type {boolean}
* @default true
* @apioption scrollbar.enabled
*/
/**
* Whether to redraw the main chart as the scrollbar or the navigator
* zoomed window is moved. Defaults to `true` for modern browsers and
* `false` for legacy IE browsers as well as mobile devices.
*
* @sample stock/scrollbar/liveredraw
* Setting live redraw to false
*
* @type {boolean}
* @since 1.3
*/
liveRedraw: void 0,
/**
* The margin between the scrollbar and its axis when the scrollbar is
* applied directly to an axis.
*/
margin: 10,
/**
* The minimum width of the scrollbar.
*
* @since 1.2.5
*/
minWidth: 6,
/**
* Whether to show or hide the scrollbar when the scrolled content is
* zoomed out to it full extent.
*
* @type {boolean}
* @default true
* @apioption scrollbar.showFull
*/
step: 0.2,
/**
* The z index of the scrollbar group.
*/
zIndex: 3,
/**
* The background color of the scrollbar itself.
*
* @sample stock/scrollbar/style/
* Scrollbar styling
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
*/
barBackgroundColor: '#cccccc',
/**
* The width of the bar's border.
*
* @sample stock/scrollbar/style/
* Scrollbar styling
*/
barBorderWidth: 1,
/**
* The color of the scrollbar's border.
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
*/
barBorderColor: '#cccccc',
/**
* The color of the small arrow inside the scrollbar buttons.
*
* @sample stock/scrollbar/style/
* Scrollbar styling
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
*/
buttonArrowColor: '#333333',
/**
* The color of scrollbar buttons.
*
* @sample stock/scrollbar/style/
* Scrollbar styling
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
*/
buttonBackgroundColor: '#e6e6e6',
/**
* The color of the border of the scrollbar buttons.
*
* @sample stock/scrollbar/style/
* Scrollbar styling
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
*/
buttonBorderColor: '#cccccc',
/**
* The border width of the scrollbar buttons.
*
* @sample stock/scrollbar/style/
* Scrollbar styling
*/
buttonBorderWidth: 1,
/**
* The color of the small rifles in the middle of the scrollbar.
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
*/
rifleColor: '#333333',
/**
* The color of the track background.
*
* @sample stock/scrollbar/style/
* Scrollbar styling
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
*/
trackBackgroundColor: '#f2f2f2',
/**
* The color of the border of the scrollbar track.
*
* @sample stock/scrollbar/style/
* Scrollbar styling
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
*/
trackBorderColor: '#f2f2f2',
/**
* The corner radius of the border of the scrollbar track.
*
* @sample stock/scrollbar/style/
* Scrollbar styling
*
* @type {number}
* @default 0
* @apioption scrollbar.trackBorderRadius
*/
/**
* The width of the border of the scrollbar track.
*
* @sample stock/scrollbar/style/
* Scrollbar styling
*/
trackBorderWidth: 1
};
defaultOptions.scrollbar = merge(true, defaultScrollbarOptions, defaultOptions.scrollbar);
/**
* When we have vertical scrollbar, rifles and arrow in buttons should be
* rotated. The same method is used in Navigator's handles, to rotate them.
*
* @function Highcharts.swapXY
*
* @param {Highcharts.SVGPathArray} path
* Path to be rotated.
*
* @param {boolean} [vertical]
* If vertical scrollbar, swap x-y values.
*
* @return {Highcharts.SVGPathArray}
* Rotated path.
*/
H.swapXY = swapXY = function (path, vertical) {
var i, len = path.length, temp;
if (vertical) {
for (i = 0; i < len; i += 3) {
temp = path[i + 1];
path[i + 1] = path[i + 2];
path[i + 2] = temp;
}
}
return path;
};
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* A reusable scrollbar, internally used in Highstock's navigator and optionally
* on individual axes.
*
* @private
* @class
* @name Highcharts.Scrollbar
* @param {Highcharts.SVGRenderer} renderer
* @param {Highcharts.ScrollbarOptions} options
* @param {Highcharts.Chart} chart
*/
var Scrollbar = /** @class */ (function () {
/* *
*
* Constructors
*
* */
function Scrollbar(renderer, options, chart) {
/* *
*
* Properties
*
* */
this._events = [];
this.chartX = 0;
this.chartY = 0;
this.from = 0;
this.group = void 0;
this.scrollbar = void 0;
this.scrollbarButtons = [];
this.scrollbarGroup = void 0;
this.scrollbarLeft = 0;
this.scrollbarRifles = void 0;
this.scrollbarStrokeWidth = 1;
this.scrollbarTop = 0;
this.size = 0;
this.to = 0;
this.track = void 0;
this.trackBorderWidth = 1;
this.userOptions = {};
this.x = 0;
this.y = 0;
this.chart = chart;
this.options = options;
this.renderer = chart.renderer;
this.init(renderer, options, chart);
}
/* *
*
* Functions
*
* */
/**
* Set up the mouse and touch events for the Scrollbar
*
* @private
* @function Highcharts.Scrollbar#addEvents
* @return {void}
*/
Scrollbar.prototype.addEvents = function () {
var buttonsOrder = this.options.inverted ? [1, 0] : [0, 1], buttons = this.scrollbarButtons, bar = this.scrollbarGroup.element, track = this.track.element, mouseDownHandler = this.mouseDownHandler.bind(this), mouseMoveHandler = this.mouseMoveHandler.bind(this), mouseUpHandler = this.mouseUpHandler.bind(this), _events;
// Mouse events
_events = [
[buttons[buttonsOrder[0]].element, 'click', this.buttonToMinClick.bind(this)],
[buttons[buttonsOrder[1]].element, 'click', this.buttonToMaxClick.bind(this)],
[track, 'click', this.trackClick.bind(this)],
[bar, 'mousedown', mouseDownHandler],
[bar.ownerDocument, 'mousemove', mouseMoveHandler],
[bar.ownerDocument, 'mouseup', mouseUpHandler]
];
// Touch events
if (hasTouch) {
_events.push([bar, 'touchstart', mouseDownHandler], [bar.ownerDocument, 'touchmove', mouseMoveHandler], [bar.ownerDocument, 'touchend', mouseUpHandler]);
}
// Add them all
_events.forEach(function (args) {
addEvent.apply(null, args);
});
this._events = _events;
};
Scrollbar.prototype.buttonToMaxClick = function (e) {
var scroller = this;
var range = (scroller.to - scroller.from) * pick(scroller.options.step, 0.2);
scroller.updatePosition(scroller.from + range, scroller.to + range);
fireEvent(scroller, 'changed', {
from: scroller.from,
to: scroller.to,
trigger: 'scrollbar',
DOMEvent: e
});
};
Scrollbar.prototype.buttonToMinClick = function (e) {
var scroller = this;
var range = correctFloat(scroller.to - scroller.from) *
pick(scroller.options.step, 0.2);
scroller.updatePosition(correctFloat(scroller.from - range), correctFloat(scroller.to - range));
fireEvent(scroller, 'changed', {
from: scroller.from,
to: scroller.to,
trigger: 'scrollbar',
DOMEvent: e
});
};
/**
* Get normalized (0-1) cursor position over the scrollbar
*
* @private
* @function Highcharts.Scrollbar#cursorToScrollbarPosition
*
* @param {*} normalizedEvent
* normalized event, with chartX and chartY values
*
* @return {Highcharts.Dictionary<number>}
* Local position {chartX, chartY}
*/
Scrollbar.prototype.cursorToScrollbarPosition = function (normalizedEvent) {
var scroller = this, options = scroller.options, minWidthDifference = options.minWidth > scroller.calculatedWidth ?
options.minWidth :
0; // minWidth distorts translation
return {
chartX: (normalizedEvent.chartX - scroller.x -
scroller.xOffset) /
(scroller.barWidth - minWidthDifference),
chartY: (normalizedEvent.chartY - scroller.y -
scroller.yOffset) /
(scroller.barWidth - minWidthDifference)
};
};
/**
* Destroys allocated elements.
*
* @private
* @function Highcharts.Scrollbar#destroy
* @return {void}
*/
Scrollbar.prototype.destroy = function () {
var scroller = this.chart.scroller;
// Disconnect events added in addEvents
this.removeEvents();
// Destroy properties
[
'track',
'scrollbarRifles',
'scrollbar',
'scrollbarGroup',
'group'
].forEach(function (prop) {
if (this[prop] && this[prop].destroy) {
this[prop] = this[prop].destroy();
}
}, this);
// #6421, chart may have more scrollbars
if (scroller && this === scroller.scrollbar) {
scroller.scrollbar = null;
// Destroy elements in collection
destroyObjectProperties(scroller.scrollbarButtons);
}
};
/**
* Draw the scrollbar buttons with arrows
*
* @private
* @function Highcharts.Scrollbar#drawScrollbarButton
* @param {number} index
* 0 is left, 1 is right
* @return {void}
*/
Scrollbar.prototype.drawScrollbarButton = function (index) {
var scroller = this, renderer = scroller.renderer, scrollbarButtons = scroller.scrollbarButtons, options = scroller.options, size = scroller.size, group, tempElem;
group = renderer.g().add(scroller.group);
scrollbarButtons.push(group);
// Create a rectangle for the scrollbar button
tempElem = renderer.rect()
.addClass('highcharts-scrollbar-button')
.add(group);
// Presentational attributes
if (!this.chart.styledMode) {
tempElem.attr({
stroke: options.buttonBorderColor,
'stroke-width': options.buttonBorderWidth,
fill: options.buttonBackgroundColor
});
}
// Place the rectangle based on the rendered stroke width
tempElem.attr(tempElem.crisp({
x: -0.5,
y: -0.5,
width: size + 1,
height: size + 1,
r: options.buttonBorderRadius
}, tempElem.strokeWidth()));
// Button arrow
tempElem = renderer
.path(swapXY([
'M',
size / 2 + (index ? -1 : 1),
size / 2 - 3,
'L',
size / 2 + (index ? -1 : 1),
size / 2 + 3,
'L',
size / 2 + (index ? 2 : -2),
size / 2
], options.vertical))
.addClass('highcharts-scrollbar-arrow')
.add(scrollbarButtons[index]);
if (!this.chart.styledMode) {
tempElem.attr({
fill: options.buttonArrowColor
});
}
};
/**
* @private
* @function Highcharts.Scrollbar#init
* @param {Highcharts.SVGRenderer} renderer
* @param {Highcharts.ScrollbarOptions} options
* @param {Highcharts.Chart} chart
*/
Scrollbar.prototype.init = function (renderer, options, chart) {
this.scrollbarButtons = [];
this.renderer = renderer;
this.userOptions = options;
this.options = merge(defaultScrollbarOptions, options);
this.chart = chart;
// backward compatibility
this.size = pick(this.options.size, this.options.height);
// Init
if (options.enabled) {
this.render();
this.addEvents();
}
};
Scrollbar.prototype.mouseDownHandler = function (e) {
var scroller = this;
var normalizedEvent = scroller.chart.pointer.normalize(e), mousePosition = scroller.cursorToScrollbarPosition(normalizedEvent);
scroller.chartX = mousePosition.chartX;
scroller.chartY = mousePosition.chartY;
scroller.initPositions = [scroller.from, scroller.to];
scroller.grabbedCenter = true;
};
/**
* Event handler for the mouse move event.
* @private
*/
Scrollbar.prototype.mouseMoveHandler = function (e) {
var scroller = this;
var normalizedEvent = scroller.chart.pointer.normalize(e), options = scroller.options, direction = options.vertical ? 'chartY' : 'chartX', initPositions = scroller.initPositions || [], scrollPosition, chartPosition, change;
// In iOS, a mousemove event with e.pageX === 0 is fired when
// holding the finger down in the center of the scrollbar. This
// should be ignored.
if (scroller.grabbedCenter &&
// #4696, scrollbar failed on Android
(!e.touches || e.touches[0][direction] !== 0)) {
chartPosition = scroller.cursorToScrollbarPosition(normalizedEvent)[direction];
scrollPosition = scroller[direction];
change = chartPosition - scrollPosition;
scroller.hasDragged = true;
scroller.updatePosition(initPositions[0] + change, initPositions[1] + change);
if (scroller.hasDragged) {
fireEvent(scroller, 'changed', {
from: scroller.from,
to: scroller.to,
trigger: 'scrollbar',
DOMType: e.type,
DOMEvent: e
});
}
}
};
/**
* Event handler for the mouse up event.
* @private
*/
Scrollbar.prototype.mouseUpHandler = function (e) {
var scroller = this;
if (scroller.hasDragged) {
fireEvent(scroller, 'changed', {
from: scroller.from,
to: scroller.to,
trigger: 'scrollbar',
DOMType: e.type,
DOMEvent: e
});
}
scroller.grabbedCenter =
scroller.hasDragged =
scroller.chartX =
scroller.chartY = null;
};
/**
* Position the scrollbar, method called from a parent with defined
* dimensions.
*
* @private
* @function Highcharts.Scrollbar#position
* @param {number} x
* x-position on the chart
* @param {number} y
* y-position on the chart
* @param {number} width
* width of the scrollbar
* @param {number} height
* height of the scorllbar
* @return {void}
*/
Scrollbar.prototype.position = function (x, y, width, height) {
var scroller = this, options = scroller.options, vertical = options.vertical, xOffset = height, yOffset = 0, method = scroller.rendered ? 'animate' : 'attr';
scroller.x = x;
scroller.y = y + this.trackBorderWidth;
scroller.width = width; // width with buttons
scroller.height = height;
scroller.xOffset = xOffset;
scroller.yOffset = yOffset;
// If Scrollbar is a vertical type, swap options:
if (vertical) {
scroller.width = scroller.yOffset = width = yOffset = scroller.size;
scroller.xOffset = xOffset = 0;
scroller.barWidth = height - width * 2; // width without buttons
scroller.x = x = x + scroller.options.margin;
}
else {
scroller.height = scroller.xOffset = height = xOffset =
scroller.size;
scroller.barWidth = width - height * 2; // width without buttons
scroller.y = scroller.y + scroller.options.margin;
}
// Set general position for a group:
scroller.group[method]({
translateX: x,
translateY: scroller.y
});
// Resize background/track:
scroller.track[method]({
width: width,
height: height
});
// Move right/bottom button ot it's place:
scroller.scrollbarButtons[1][method]({
translateX: vertical ? 0 : width - xOffset,
translateY: vertical ? height - yOffset : 0
});
};
/**
* Removes the event handlers attached previously with addEvents.
*
* @private
* @function Highcharts.Scrollbar#removeEvents
* @return {void}
*/
Scrollbar.prototype.removeEvents = function () {
this._events.forEach(function (args) {
removeEvent.apply(null, args);
});
this._events.length = 0;
};
/**
* Render scrollbar with all required items.
*
* @private
* @function Highcharts.Scrollbar#render
*/
Scrollbar.prototype.render = function () {
var scroller = this, renderer = scroller.renderer, options = scroller.options, size = scroller.size, styledMode = this.chart.styledMode, group;
// Draw the scrollbar group
scroller.group = group = renderer.g('scrollbar').attr({
zIndex: options.zIndex,
translateY: -99999
}).add();
// Draw the scrollbar track:
scroller.track = renderer.rect()
.addClass('highcharts-scrollbar-track')
.attr({
x: 0,
r: options.trackBorderRadius || 0,
height: size,
width: size
}).add(group);
if (!styledMode) {
scroller.track.attr({
fill: options.trackBackgroundColor,
stroke: options.trackBorderColor,
'stroke-width': options.trackBorderWidth
});
}
this.trackBorderWidth = scroller.track.strokeWidth();
scroller.track.attr({
y: -this.trackBorderWidth % 2 / 2
});
// Draw the scrollbar itself
scroller.scrollbarGroup = renderer.g().add(group);
scroller.scrollbar = renderer.rect()
.addClass('highcharts-scrollbar-thumb')
.attr({
height: size,
width: size,
r: options.barBorderRadius || 0
}).add(scroller.scrollbarGroup);
scroller.scrollbarRifles = renderer
.path(swapXY([
'M',
-3, size / 4,
'L',
-3, 2 * size / 3,
'M',
0, size / 4,
'L',
0, 2 * size / 3,
'M',
3, size / 4,
'L',
3, 2 * size / 3
], options.vertical))
.addClass('highcharts-scrollbar-rifles')
.add(scroller.scrollbarGroup);
if (!styledMode) {
scroller.scrollbar.attr({
fill: options.barBackgroundColor,
stroke: options.barBorderColor,
'stroke-width': options.barBorderWidth
});
scroller.scrollbarRifles.attr({
stroke: options.rifleColor,
'stroke-width': 1
});
}
scroller.scrollbarStrokeWidth = scroller.scrollbar.strokeWidth();
scroller.scrollbarGroup.translate(-scroller.scrollbarStrokeWidth % 2 / 2, -scroller.scrollbarStrokeWidth % 2 / 2);
// Draw the buttons:
scroller.drawScrollbarButton(0);
scroller.drawScrollbarButton(1);
};
/**
* Set scrollbar size, with a given scale.
*
* @private
* @function Highcharts.Scrollbar#setRange
* @param {number} from
* scale (0-1) where bar should start
* @param {number} to
* scale (0-1) where bar should end
* @return {void}
*/
Scrollbar.prototype.setRange = function (from, to) {
var scroller = this, options = scroller.options, vertical = options.vertical, minWidth = options.minWidth, fullWidth = scroller.barWidth, fromPX, toPX, newPos, newSize, newRiflesPos, method = (this.rendered &&
!this.hasDragged &&
!(this.chart.navigator && this.chart.navigator.hasDragged)) ? 'animate' : 'attr';
if (!defined(fullWidth)) {
return;
}
from = Math.max(from, 0);
fromPX = Math.ceil(fullWidth * from);
toPX = fullWidth * Math.min(to, 1);
scroller.calculatedWidth = newSize = correctFloat(toPX - fromPX);
// We need to recalculate position, if minWidth is used
if (newSize < minWidth) {
fromPX = (fullWidth - minWidth + newSize) * from;
newSize = minWidth;
}
newPos = Math.floor(fromPX + scroller.xOffset + scroller.yOffset);
newRiflesPos = newSize / 2 - 0.5; // -0.5 -> rifle line width / 2
// Store current position:
scroller.from = from;
scroller.to = to;
if (!vertical) {
scroller.scrollbarGroup[method]({
translateX: newPos
});
scroller.scrollbar[method]({
width: newSize
});
scroller.scrollbarRifles[method]({
translateX: newRiflesPos
});
scroller.scrollbarLeft = newPos;
scroller.scrollbarTop = 0;
}
else {
scroller.scrollbarGroup[method]({
translateY: newPos
});
scroller.scrollbar[method]({
height: newSize
});
scroller.scrollbarRifles[method]({
translateY: newRiflesPos
});
scroller.scrollbarTop = newPos;
scroller.scrollbarLeft = 0;
}
if (newSize <= 12) {
scroller.scrollbarRifles.hide();
}
else {
scroller.scrollbarRifles.show(true);
}
// Show or hide the scrollbar based on the showFull setting
if (options.showFull === false) {
if (from <= 0 && to >= 1) {
scroller.group.hide();
}
else {
scroller.group.show();
}
}
scroller.rendered = true;
};
Scrollbar.prototype.trackClick = function (e) {
var scroller = this;
var normalizedEvent = scroller.chart.pointer.normalize(e), range = scroller.to - scroller.from, top = scroller.y + scroller.scrollbarTop, left = scroller.x + scroller.scrollbarLeft;
if ((scroller.options.vertical && normalizedEvent.chartY > top) ||
(!scroller.options.vertical && normalizedEvent.chartX > left)) {
// On the top or on the left side of the track:
scroller.updatePosition(scroller.from + range, scroller.to + range);
}
else {
// On the bottom or the right side of the track:
scroller.updatePosition(scroller.from - range, scroller.to - range);
}
fireEvent(scroller, 'changed', {
from: scroller.from,
to: scroller.to,
trigger: 'scrollbar',
DOMEvent: e
});
};
/**
* Update the scrollbar with new options
*
* @private
* @function Highcharts.Scrollbar#update
* @param {Highcharts.ScrollbarOptions} options
* @return {void}
*/
Scrollbar.prototype.update = function (options) {
this.destroy();
this.init(this.chart.renderer, merge(true, this.options, options), this.chart);
};
/**
* Update position option in the Scrollbar, with normalized 0-1 scale
*
* @private
* @function Highcharts.Scrollbar#updatePosition
* @param {number} from
* @param {number} to
* @return {void}
*/
Scrollbar.prototype.updatePosition = function (from, to) {
if (to > 1) {
from = correctFloat(1 - correctFloat(to - from));
to = 1;
}
if (from < 0) {
to = correctFloat(to - from);
from = 0;
}
this.from = from;
this.to = to;
};
return Scrollbar;
}());
if (!H.Scrollbar) {
/* *
* Wrap axis initialization and create scrollbar if enabled:
*/
addEvent(Axis, 'afterInit', function () {
var axis = this;
if (axis.options &&
axis.options.scrollbar &&
axis.options.scrollbar.enabled) {
// Predefined options:
axis.options.scrollbar.vertical = !axis.horiz;
axis.options.startOnTick = axis.options.endOnTick = false;
axis.scrollbar = new Scrollbar(axis.chart.renderer, axis.options.scrollbar, axis.chart);
addEvent(axis.scrollbar, 'changed', function (e) {
var unitedMin = Math.min(pick(axis.options.min, axis.min), axis.min, axis.dataMin), unitedMax = Math.max(pick(axis.options.max, axis.max), axis.max, axis.dataMax), range = unitedMax - unitedMin, to, from;
if ((axis.horiz && !axis.reversed) ||
(!axis.horiz && axis.reversed)) {
to = unitedMin + range * this.to;
from = unitedMin + range * this.from;
}
else {
// y-values in browser are reversed, but this also applies
// for reversed horizontal axis:
to = unitedMin + range * (1 - this.from);
from = unitedMin + range * (1 - this.to);
}
if (pick(this.options.liveRedraw, H.svg && !H.isTouchDevice && !this.chart.isBoosting) ||
// Mouseup always should change extremes
e.DOMType === 'mouseup' ||
// Internal events
!defined(e.DOMType)) {
axis.setExtremes(from, to, true, e.DOMType !== 'mousemove', e);
}
else {
// When live redraw is disabled, don't change extremes
// Only change the position of the scollbar thumb
this.setRange(this.from, this.to);
}
});
}
});
/* *
* Wrap rendering axis, and update scrollbar if one is created:
*/
addEvent(Axis, 'afterRender', function () {
var axis = this, scrollMin = Math.min(pick(axis.options.min, axis.min), axis.min, pick(axis.dataMin, axis.min) // #6930
), scrollMax = Math.max(pick(axis.options.max, axis.max), axis.max, pick(axis.dataMax, axis.max) // #6930
), scrollbar = axis.scrollbar, offset = axis.axisTitleMargin + (axis.titleOffset || 0), scrollbarsOffsets = axis.chart.scrollbarsOffsets, axisMargin = axis.options.margin || 0, offsetsIndex, from, to;
if (scrollbar) {
if (axis.horiz) {
// Reserve space for labels/title
if (!axis.opposite) {
scrollbarsOffsets[1] += offset;
}
scrollbar.position(axis.left, axis.top + axis.height + 2 + scrollbarsOffsets[1] -
(axis.opposite ? axisMargin : 0), axis.width, axis.height);
// Next scrollbar should reserve space for margin (if set)
if (!axis.opposite) {
scrollbarsOffsets[1] += axisMargin;
}
offsetsIndex = 1;
}
else {
// Reserve space for labels/title
if (axis.opposite) {
scrollbarsOffsets[0] += offset;
}
scrollbar.position(axis.left + axis.width + 2 + scrollbarsOffsets[0] -
(axis.opposite ? 0 : axisMargin), axis.top, axis.width, axis.height);
// Next scrollbar should reserve space for margin (if set)
if (axis.opposite) {
scrollbarsOffsets[0] += axisMargin;
}
offsetsIndex = 0;
}
scrollbarsOffsets[offsetsIndex] += scrollbar.size +
scrollbar.options.margin;
if (isNaN(scrollMin) ||
isNaN(scrollMax) ||
!defined(axis.min) ||
!defined(axis.max) ||
axis.min === axis.max // #10733
) {
// default action: when extremes are the same or there is not
// extremes on the axis, but scrollbar exists, make it full size
scrollbar.setRange(0, 1);
}
else {
from =
(axis.min - scrollMin) / (scrollMax - scrollMin);
to =
(axis.max - scrollMin) / (scrollMax - scrollMin);
if ((axis.horiz && !axis.reversed) ||
(!axis.horiz && axis.reversed)) {
scrollbar.setRange(from, to);
}
else {
// inverse vertical axis
scrollbar.setRange(1 - to, 1 - from);
}
}
}
});
/* *
* Make space for a scrollbar
* @private
*/
addEvent(Axis, 'afterGetOffset', function () {
var axis = this, index = axis.horiz ? 2 : 1, scrollbar = axis.scrollbar;
if (scrollbar) {
axis.chart.scrollbarsOffsets = [0, 0]; // reset scrollbars offsets
axis.chart.axisOffset[index] +=
scrollbar.size + scrollbar.options.margin;
}
});
H.Scrollbar = Scrollbar;
}
export default H.Scrollbar;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,253 @@
/* *
*
* (c) 2010-2020 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import U from './Utilities.js';
var pick = U.pick, seriesType = U.seriesType;
import './Options.js';
import './Series.js';
/**
* Spline series type.
*
* @private
* @class
* @name Highcharts.seriesTypes.spline
*
* @augments Highcarts.Series
*/
seriesType('spline', 'line',
/**
* A spline series is a special type of line series, where the segments
* between the data points are smoothed.
*
* @sample {highcharts} highcharts/demo/spline-irregular-time/
* Spline chart
* @sample {highstock} stock/demo/spline/
* Spline chart
*
* @extends plotOptions.series
* @excluding step
* @product highcharts highstock
* @optionparent plotOptions.spline
*/
{},
/**
* @lends seriesTypes.spline.prototype
*/
{
/* eslint-disable valid-jsdoc */
/**
* Get the spline segment from a given point's previous neighbour to the
* given point.
*
* @private
* @function Highcharts.seriesTypes.spline#getPointSpline
*
* @param {Array<Highcharts.Point>}
*
* @param {Highcharts.Point} point
*
* @param {number} i
*
* @return {Highcharts.SVGPathArray}
*/
getPointSpline: function (points, point, i) {
var
// 1 means control points midway between points, 2 means 1/3
// from the point, 3 is 1/4 etc
smoothing = 1.5, denom = smoothing + 1, plotX = point.plotX, plotY = point.plotY, lastPoint = points[i - 1], nextPoint = points[i + 1], leftContX, leftContY, rightContX, rightContY, ret;
/**
* @private
*/
function doCurve(otherPoint) {
return otherPoint &&
!otherPoint.isNull &&
otherPoint.doCurve !== false &&
// #6387, area splines next to null:
!point.isCliff;
}
// Find control points
if (doCurve(lastPoint) && doCurve(nextPoint)) {
var lastX = lastPoint.plotX, lastY = lastPoint.plotY, nextX = nextPoint.plotX, nextY = nextPoint.plotY, correction = 0;
leftContX =
(smoothing * plotX + lastX) / denom;
leftContY =
(smoothing * plotY + lastY) / denom;
rightContX =
(smoothing * plotX + nextX) / denom;
rightContY =
(smoothing * plotY + nextY) / denom;
// Have the two control points make a straight line through main
// point
if (rightContX !== leftContX) { // #5016, division by zero
correction = (((rightContY - leftContY) *
(rightContX - plotX)) /
(rightContX - leftContX) + plotY - rightContY);
}
leftContY += correction;
rightContY += correction;
// to prevent false extremes, check that control points are
// between neighbouring points' y values
if (leftContY > lastY && leftContY > plotY) {
leftContY = Math.max(lastY, plotY);
// mirror of left control point
rightContY = 2 * plotY - leftContY;
}
else if (leftContY < lastY &&
leftContY < plotY) {
leftContY = Math.min(lastY, plotY);
rightContY = 2 * plotY - leftContY;
}
if (rightContY > nextY &&
rightContY > plotY) {
rightContY = Math.max(nextY, plotY);
leftContY = 2 * plotY - rightContY;
}
else if (rightContY < nextY &&
rightContY < plotY) {
rightContY = Math.min(nextY, plotY);
leftContY = 2 * plotY - rightContY;
}
// record for drawing in next point
point.rightContX = rightContX;
point.rightContY = rightContY;
}
// Visualize control points for debugging
/*
if (leftContX) {
this.chart.renderer.circle(
leftContX + this.chart.plotLeft,
leftContY + this.chart.plotTop,
2
)
.attr({
stroke: 'red',
'stroke-width': 2,
fill: 'none',
zIndex: 9
})
.add();
this.chart.renderer.path(['M', leftContX + this.chart.plotLeft,
leftContY + this.chart.plotTop,
'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop])
.attr({
stroke: 'red',
'stroke-width': 2,
zIndex: 9
})
.add();
}
if (rightContX) {
this.chart.renderer.circle(
rightContX + this.chart.plotLeft,
rightContY + this.chart.plotTop,
2
)
.attr({
stroke: 'green',
'stroke-width': 2,
fill: 'none',
zIndex: 9
})
.add();
this.chart.renderer.path(['M', rightContX + this.chart.plotLeft,
rightContY + this.chart.plotTop,
'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop])
.attr({
stroke: 'green',
'stroke-width': 2,
zIndex: 9
})
.add();
}
// */
ret = [
'C',
pick(lastPoint.rightContX, lastPoint.plotX),
pick(lastPoint.rightContY, lastPoint.plotY),
pick(leftContX, plotX),
pick(leftContY, plotY),
plotX,
plotY
];
// reset for updating series later
lastPoint.rightContX = lastPoint.rightContY = null;
return ret;
}
/* eslint-enable valid-jsdoc */
});
/**
* A `spline` series. If the [type](#series.spline.type) option is
* not specified, it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.spline
* @excluding dataParser, dataURL, step
* @product highcharts highstock
* @apioption series.spline
*/
/**
* An array of data points for the series. For the `spline` series type,
* points can be given in the following ways:
*
* 1. An array of numerical values. In this case, the numerical values will be
* interpreted as `y` options. The `x` values will be automatically
* calculated, either starting at 0 and incremented by 1, or from
* `pointStart` and `pointInterval` given in the series options. If the axis
* has categories, these will be used. Example:
* ```js
* data: [0, 5, 3, 5]
* ```
*
* 2. An array of arrays with 2 values. In this case, the values correspond to
* `x,y`. If the first value is a string, it is applied as the name of the
* point, and the `x` value is inferred.
* ```js
* data: [
* [0, 9],
* [1, 2],
* [2, 8]
* ]
* ```
*
* 3. An array of objects with named values. The following snippet shows only a
* few settings, see the complete options set below. If the total number of
* data points exceeds the series'
* [turboThreshold](#series.spline.turboThreshold),
* this option is not available.
* ```js
* data: [{
* x: 1,
* y: 9,
* name: "Point2",
* color: "#00FF00"
* }, {
* x: 1,
* y: 0,
* name: "Point1",
* color: "#FF00FF"
* }]
* ```
*
* @sample {highcharts} highcharts/chart/reflow-true/
* Numerical values
* @sample {highcharts} highcharts/series/data-array-of-arrays/
* Arrays of numeric x and y
* @sample {highcharts} highcharts/series/data-array-of-arrays-datetime/
* Arrays of datetime x and y
* @sample {highcharts} highcharts/series/data-array-of-name-value/
* Arrays of point.name and y
* @sample {highcharts} highcharts/series/data-array-of-objects/
* Config objects
*
* @type {Array<number|Array<(number|string),(number|null)>|null|*>}
* @extends series.line.data
* @product highcharts highstock
* @apioption series.spline.data
*/
''; // adds doclets above intro transpilat

View File

@@ -0,0 +1,566 @@
/* *
*
* (c) 2010-2020 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from './Globals.js';
/**
* Stack of data points
*
* @product highcharts
*
* @interface Highcharts.StackItemObject
*/ /**
* Alignment settings
* @name Highcharts.StackItemObject#alignOptions
* @type {Highcharts.AlignObject}
*/ /**
* Related axis
* @name Highcharts.StackItemObject#axis
* @type {Highcharts.Axis}
*/ /**
* Cumulative value of the stacked data points
* @name Highcharts.StackItemObject#cumulative
* @type {number}
*/ /**
* True if on the negative side
* @name Highcharts.StackItemObject#isNegative
* @type {boolean}
*/ /**
* Related SVG element
* @name Highcharts.StackItemObject#label
* @type {Highcharts.SVGElement}
*/ /**
* Related stack options
* @name Highcharts.StackItemObject#options
* @type {Highcharts.YAxisStackLabelsOptions}
*/ /**
* Total value of the stacked data points
* @name Highcharts.StackItemObject#total
* @type {number}
*/ /**
* Shared x value of the stack
* @name Highcharts.StackItemObject#x
* @type {number}
*/
import U from './Utilities.js';
var correctFloat = U.correctFloat, defined = U.defined, destroyObjectProperties = U.destroyObjectProperties, format = U.format, objectEach = U.objectEach, pick = U.pick;
import './Axis.js';
import './Chart.js';
import './Series.js';
var Axis = H.Axis, Chart = H.Chart, Series = H.Series;
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* The class for stacks. Each stack, on a specific X value and either negative
* or positive, has its own stack item.
*
* @private
* @class
* @name Highcharts.StackItem
* @param {Highcharts.Axis} axis
* @param {Highcharts.YAxisStackLabelsOptions} options
* @param {boolean} isNegative
* @param {number} x
* @param {Highcharts.OptionsStackingValue} [stackOption]
*/
H.StackItem = function (axis, options, isNegative, x, stackOption) {
var inverted = axis.chart.inverted;
this.axis = axis;
// Tells if the stack is negative
this.isNegative = isNegative;
// Save the options to be able to style the label
this.options = options = options || {};
// Save the x value to be able to position the label later
this.x = x;
// Initialize total value
this.total = null;
// This will keep each points' extremes stored by series.index and point
// index
this.points = {};
// Save the stack option on the series configuration object, and whether to
// treat it as percent
this.stack = stackOption;
this.leftCliff = 0;
this.rightCliff = 0;
// The align options and text align varies on whether the stack is negative
// and if the chart is inverted or not.
// First test the user supplied value, then use the dynamic.
this.alignOptions = {
align: options.align ||
(inverted ? (isNegative ? 'left' : 'right') : 'center'),
verticalAlign: options.verticalAlign ||
(inverted ? 'middle' : (isNegative ? 'bottom' : 'top')),
y: options.y,
x: options.x
};
this.textAlign = options.textAlign ||
(inverted ? (isNegative ? 'right' : 'left') : 'center');
};
H.StackItem.prototype = {
/**
* @private
* @function Highcharts.StackItem#destroy
* @return {void}
*/
destroy: function () {
destroyObjectProperties(this, this.axis);
},
/**
* Renders the stack total label and adds it to the stack label group.
*
* @private
* @function Highcharts.StackItem#render
* @param {Highcharts.SVGElement} group
* @return {void}
*/
render: function (group) {
var chart = this.axis.chart, options = this.options, formatOption = options.format, attr = {}, str = formatOption ? // format the text in the label
format(formatOption, this, chart) :
options.formatter.call(this);
// Change the text to reflect the new total and set visibility to hidden
// in case the serie is hidden
if (this.label) {
this.label.attr({ text: str, visibility: 'hidden' });
}
else {
// Create new label
this.label = chart.renderer
.label(str, null, null, options.shape, null, null, options.useHTML, false, 'stack-labels');
attr = {
text: str,
rotation: options.rotation,
padding: pick(options.padding, 5),
visibility: 'hidden' // hidden until setOffset is called
};
this.label.attr(attr);
if (!chart.styledMode) {
this.label.css(options.style);
}
if (!this.label.added) {
this.label.add(group); // add to the labels-group
}
}
// Rank it higher than data labels (#8742)
this.label.labelrank = chart.plotHeight;
},
/**
* Sets the offset that the stack has from the x value and repositions the
* label.
*
* @private
* @function Highcarts.StackItem#setOffset
* @param {number} xOffset
* @param {number} xWidth
* @param {number} [boxBottom]
* @param {number} [boxTop]
* @param {number} [defaultX]
* @return {void}
*/
setOffset: function (xOffset, xWidth, boxBottom, boxTop, defaultX) {
var stackItem = this, axis = stackItem.axis, chart = axis.chart,
// stack value translated mapped to chart coordinates
y = axis.translate(axis.usePercentage ?
100 :
(boxTop ?
boxTop :
stackItem.total), 0, 0, 0, 1), yZero = axis.translate(boxBottom ? boxBottom : 0), // stack origin
// stack height:
h = defined(y) && Math.abs(y - yZero),
// x position:
x = pick(defaultX, chart.xAxis[0].translate(stackItem.x)) +
xOffset, stackBox = defined(y) && stackItem.getStackBox(chart, stackItem, x, y, xWidth, h, axis), label = stackItem.label, isNegative = stackItem.isNegative, isJustify = pick(stackItem.options.overflow, 'justify') === 'justify', textAlign = stackItem.textAlign, visible;
if (label && stackBox) {
var bBox = label.getBBox(), padding = label.padding, boxOffsetX, boxOffsetY;
if (textAlign === 'left') {
boxOffsetX = chart.inverted ? -padding : padding;
}
else if (textAlign === 'right') {
boxOffsetX = bBox.width;
}
else {
if (chart.inverted && textAlign === 'center') {
boxOffsetX = bBox.width / 2;
}
else {
boxOffsetX = chart.inverted ?
(isNegative ? bBox.width + padding : -padding) : bBox.width / 2;
}
}
boxOffsetY = chart.inverted ?
bBox.height / 2 : (isNegative ? -padding : bBox.height);
// Reset alignOptions property after justify #12337
stackItem.alignOptions.x = pick(stackItem.options.x, 0);
stackItem.alignOptions.y = pick(stackItem.options.y, 0);
// Set the stackBox position
stackBox.x -= boxOffsetX;
stackBox.y -= boxOffsetY;
// Align the label to the box
label.align(stackItem.alignOptions, null, stackBox);
// Check if label is inside the plotArea #12294
if (chart.isInsidePlot(label.alignAttr.x + boxOffsetX - stackItem.alignOptions.x, label.alignAttr.y + boxOffsetY - stackItem.alignOptions.y)) {
label.show();
}
else {
// Move label away to avoid the overlapping issues
label.alignAttr.y = -9999;
isJustify = false;
}
if (isJustify) {
// Justify stackLabel into the stackBox
Series.prototype.justifyDataLabel.call(this.axis, label, stackItem.alignOptions, label.alignAttr, bBox, stackBox);
}
label.attr({
x: label.alignAttr.x,
y: label.alignAttr.y
});
if (pick(!isJustify && stackItem.options.crop, true)) {
visible = chart.isInsidePlot(label.x - padding + label.width, label.y) &&
chart.isInsidePlot(label.x + padding, label.y);
if (!visible) {
label.hide();
}
}
}
},
/**
* @private
* @function Highcharts.StackItem#getStackBox
*
* @param {Highcharts.Chart} chart
*
* @param {Highcharts.StackItem} stackItem
*
* @param {number} x
*
* @param {number} y
*
* @param {number} xWidth
*
* @param {number} h
*
* @param {Highcharts.Axis} axis
*
* @return {Highcharts.BBoxObject}
*/
getStackBox: function (chart, stackItem, x, y, xWidth, h, axis) {
var reversed = stackItem.axis.reversed, inverted = chart.inverted, axisPos = axis.height + axis.pos -
(inverted ? chart.plotLeft : chart.plotTop), neg = (stackItem.isNegative && !reversed) ||
(!stackItem.isNegative && reversed); // #4056
return {
x: inverted ? (neg ? y : y - h) : x,
y: inverted ?
axisPos - x - xWidth :
(neg ?
(axisPos - y - h) :
axisPos - y),
width: inverted ? h : xWidth,
height: inverted ? xWidth : h
};
}
};
/**
* Generate stacks for each series and calculate stacks total values
*
* @private
* @function Highcharts.Chart#getStacks
* @return {void}
*/
Chart.prototype.getStacks = function () {
var chart = this, inverted = chart.inverted;
// reset stacks for each yAxis
chart.yAxis.forEach(function (axis) {
if (axis.stacks && axis.hasVisibleSeries) {
axis.oldStacks = axis.stacks;
}
});
chart.series.forEach(function (series) {
var xAxisOptions = series.xAxis && series.xAxis.options || {};
if (series.options.stacking &&
(series.visible === true ||
chart.options.chart.ignoreHiddenSeries === false)) {
series.stackKey = [
series.type,
pick(series.options.stack, ''),
inverted ? xAxisOptions.top : xAxisOptions.left,
inverted ? xAxisOptions.height : xAxisOptions.width
].join(',');
}
});
};
// Stacking methods defined on the Axis prototype
/**
* Build the stacks from top down
*
* @private
* @function Highcharts.Axis#buildStacks
* @return {void}
*/
Axis.prototype.buildStacks = function () {
var axisSeries = this.series, reversedStacks = pick(this.options.reversedStacks, true), len = axisSeries.length, actualSeries, i;
if (!this.isXAxis) {
this.usePercentage = false;
i = len;
while (i--) {
actualSeries = axisSeries[reversedStacks ? i : len - i - 1];
actualSeries.setStackedPoints();
}
// Loop up again to compute percent and stream stack
for (i = 0; i < len; i++) {
axisSeries[i].modifyStacks();
}
H.fireEvent(this, 'afterBuildStacks');
}
};
/**
* @private
* @function Highcharts.Axis#renderStackTotals
* @return {vopid}
*/
Axis.prototype.renderStackTotals = function () {
var axis = this, chart = axis.chart, renderer = chart.renderer, stacks = axis.stacks, stackTotalGroup = axis.stackTotalGroup;
// Create a separate group for the stack total labels
if (!stackTotalGroup) {
axis.stackTotalGroup = stackTotalGroup =
renderer
.g('stack-labels')
.attr({
visibility: 'visible',
zIndex: 6
})
.add();
}
// plotLeft/Top will change when y axis gets wider so we need to translate
// the stackTotalGroup at every render call. See bug #506 and #516
stackTotalGroup.translate(chart.plotLeft, chart.plotTop);
// Render each stack total
objectEach(stacks, function (type) {
objectEach(type, function (stack) {
stack.render(stackTotalGroup);
});
});
};
/**
* Set all the stacks to initial states and destroy unused ones.
*
* @private
* @function Highcharts.Axis#resetStacks
* @return {void}
*/
Axis.prototype.resetStacks = function () {
var axis = this, stacks = axis.stacks;
if (!axis.isXAxis) {
objectEach(stacks, function (type) {
objectEach(type, function (stack, key) {
// Clean up memory after point deletion (#1044, #4320)
if (stack.touched < axis.stacksTouched) {
stack.destroy();
delete type[key];
// Reset stacks
}
else {
stack.total = null;
stack.cumulative = null;
}
});
});
}
};
/**
* @private
* @function Highcharts.Axis#cleanStacks
* @return {void}
*/
Axis.prototype.cleanStacks = function () {
var stacks;
if (!this.isXAxis) {
if (this.oldStacks) {
stacks = this.stacks = this.oldStacks;
}
// reset stacks
objectEach(stacks, function (type) {
objectEach(type, function (stack) {
stack.cumulative = stack.total;
});
});
}
};
// Stacking methods defnied for Series prototype
/**
* Adds series' points value to corresponding stack
*
* @private
* @function Highcharts.Series#setStackedPoints
* @return {void}
*/
Series.prototype.setStackedPoints = function () {
if (!this.options.stacking ||
(this.visible !== true &&
this.chart.options.chart.ignoreHiddenSeries !== false)) {
return;
}
var series = this, xData = series.processedXData, yData = series.processedYData, stackedYData = [], yDataLength = yData.length, seriesOptions = series.options, threshold = seriesOptions.threshold, stackThreshold = pick(seriesOptions.startFromThreshold && threshold, 0), stackOption = seriesOptions.stack, stacking = seriesOptions.stacking, stackKey = series.stackKey, negKey = '-' + stackKey, negStacks = series.negStacks, yAxis = series.yAxis, stacks = yAxis.stacks, oldStacks = yAxis.oldStacks, stackIndicator, isNegative, stack, other, key, pointKey, i, x, y;
yAxis.stacksTouched += 1;
// loop over the non-null y values and read them into a local array
for (i = 0; i < yDataLength; i++) {
x = xData[i];
y = yData[i];
stackIndicator = series.getStackIndicator(stackIndicator, x, series.index);
pointKey = stackIndicator.key;
// Read stacked values into a stack based on the x value,
// the sign of y and the stack key. Stacking is also handled for null
// values (#739)
isNegative = negStacks && y < (stackThreshold ? 0 : threshold);
key = isNegative ? negKey : stackKey;
// Create empty object for this stack if it doesn't exist yet
if (!stacks[key]) {
stacks[key] =
{};
}
// Initialize StackItem for this x
if (!stacks[key][x]) {
if (oldStacks[key] &&
oldStacks[key][x]) {
stacks[key][x] = oldStacks[key][x];
stacks[key][x].total = null;
}
else {
stacks[key][x] = new H.StackItem(yAxis, yAxis.options.stackLabels, isNegative, x, stackOption);
}
}
// If the StackItem doesn't exist, create it first
stack = stacks[key][x];
if (y !== null) {
stack.points[pointKey] = stack.points[series.index] =
[pick(stack.cumulative, stackThreshold)];
// Record the base of the stack
if (!defined(stack.cumulative)) {
stack.base = pointKey;
}
stack.touched = yAxis.stacksTouched;
// In area charts, if there are multiple points on the same X value,
// let the area fill the full span of those points
if (stackIndicator.index > 0 && series.singleStacks === false) {
stack.points[pointKey][0] =
stack.points[series.index + ',' + x + ',0'][0];
}
// When updating to null, reset the point stack (#7493)
}
else {
stack.points[pointKey] = stack.points[series.index] =
null;
}
// Add value to the stack total
if (stacking === 'percent') {
// Percent stacked column, totals are the same for the positive and
// negative stacks
other = isNegative ? stackKey : negKey;
if (negStacks && stacks[other] && stacks[other][x]) {
other = stacks[other][x];
stack.total = other.total =
Math.max(other.total, stack.total) +
Math.abs(y) ||
0;
// Percent stacked areas
}
else {
stack.total =
correctFloat(stack.total + (Math.abs(y) || 0));
}
}
else {
stack.total = correctFloat(stack.total + (y || 0));
}
stack.cumulative =
pick(stack.cumulative, stackThreshold) + (y || 0);
if (y !== null) {
stack.points[pointKey].push(stack.cumulative);
stackedYData[i] = stack.cumulative;
}
}
if (stacking === 'percent') {
yAxis.usePercentage = true;
}
this.stackedYData = stackedYData; // To be used in getExtremes
// Reset old stacks
yAxis.oldStacks = {};
};
/**
* Iterate over all stacks and compute the absolute values to percent
*
* @private
* @function Highcharts.Series#modifyStacks
* @return {void}
*/
Series.prototype.modifyStacks = function () {
var series = this, stackKey = series.stackKey, stacks = series.yAxis.stacks, processedXData = series.processedXData, stackIndicator, stacking = series.options.stacking;
if (series[stacking + 'Stacker']) { // Modifier function exists
[stackKey, '-' + stackKey].forEach(function (key) {
var i = processedXData.length, x, stack, pointExtremes;
while (i--) {
x = processedXData[i];
stackIndicator = series.getStackIndicator(stackIndicator, x, series.index, key);
stack = stacks[key] && stacks[key][x];
pointExtremes =
stack && stack.points[stackIndicator.key];
if (pointExtremes) {
series[stacking + 'Stacker'](pointExtremes, stack, i);
}
}
});
}
};
/**
* Modifier function for percent stacks. Blows up the stack to 100%.
*
* @private
* @function Highcharts.Series#percentStacker
* @param {Array<number>} pointExtremes
* @param {Highcharts.StackItem} stack
* @param {number} i
* @return {void}
*/
Series.prototype.percentStacker = function (pointExtremes, stack, i) {
var totalFactor = stack.total ? 100 / stack.total : 0;
// Y bottom value
pointExtremes[0] = correctFloat(pointExtremes[0] * totalFactor);
// Y value
pointExtremes[1] = correctFloat(pointExtremes[1] * totalFactor);
this.stackedYData[i] = pointExtremes[1];
};
/**
* Get stack indicator, according to it's x-value, to determine points with the
* same x-value
*
* @private
* @function Highcharts.Series#getStackIndicator
* @param {Highcharts.StackItemIndicatorObject|undefined} stackIndicator
* @param {number} x
* @param {number} index
* @param {string} [key]
* @return {Highcharts.StackItemIndicatorObject}
*/
Series.prototype.getStackIndicator = function (stackIndicator, x, index, key) {
// Update stack indicator, when:
// first point in a stack || x changed || stack type (negative vs positive)
// changed:
if (!defined(stackIndicator) ||
stackIndicator.x !== x ||
(key && stackIndicator.key !== key)) {
stackIndicator = {
x: x,
index: 0,
key: key
};
}
else {
stackIndicator.index++;
}
stackIndicator.key =
[index, x, stackIndicator.index].join(',');
return stackIndicator;
};

View File

@@ -0,0 +1,788 @@
/* *
*
* (c) 2010-2020 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from './Globals.js';
import Point from './Point.js';
import U from './Utilities.js';
var addEvent = U.addEvent, arrayMax = U.arrayMax, arrayMin = U.arrayMin, clamp = U.clamp, defined = U.defined, extend = U.extend, find = U.find, format = U.format, isNumber = U.isNumber, isString = U.isString, merge = U.merge, pick = U.pick, splat = U.splat;
import './Chart.js';
import './Axis.js';
import './Pointer.js';
import './Series.js';
import './SvgRenderer.js';
// Has a dependency on Navigator due to the use of
// defaultOptions.navigator
import './Navigator.js';
// Has a dependency on Scrollbar due to the use of
// defaultOptions.scrollbar
import './Scrollbar.js';
// Has a dependency on RangeSelector due to the use of
// defaultOptions.rangeSelector
import './RangeSelector.js';
var Axis = H.Axis, Chart = H.Chart, Renderer = H.Renderer, Series = H.Series, SVGRenderer = H.SVGRenderer, VMLRenderer = H.VMLRenderer, seriesProto = Series.prototype, seriesInit = seriesProto.init, seriesProcessData = seriesProto.processData, pointTooltipFormatter = Point.prototype.tooltipFormatter;
/**
* Compare the values of the series against the first non-null, non-
* zero value in the visible range. The y axis will show percentage
* or absolute change depending on whether `compare` is set to `"percent"`
* or `"value"`. When this is applied to multiple series, it allows
* comparing the development of the series against each other. Adds
* a `change` field to every point object.
*
* @see [compareBase](#plotOptions.series.compareBase)
* @see [Axis.setCompare()](/class-reference/Highcharts.Axis#setCompare)
*
* @sample {highstock} stock/plotoptions/series-compare-percent/
* Percent
* @sample {highstock} stock/plotoptions/series-compare-value/
* Value
*
* @type {string}
* @since 1.0.1
* @product highstock
* @apioption plotOptions.series.compare
*/
/**
* Defines if comparison should start from the first point within the visible
* range or should start from the first point **before** the range.
*
* In other words, this flag determines if first point within the visible range
* will have 0% (`compareStart=true`) or should have been already calculated
* according to the previous point (`compareStart=false`).
*
* @sample {highstock} stock/plotoptions/series-comparestart/
* Calculate compare within visible range
*
* @type {boolean}
* @default false
* @since 6.0.0
* @product highstock
* @apioption plotOptions.series.compareStart
*/
/**
* When [compare](#plotOptions.series.compare) is `percent`, this option
* dictates whether to use 0 or 100 as the base of comparison.
*
* @sample {highstock} stock/plotoptions/series-comparebase/
* Compare base is 100
*
* @type {number}
* @default 0
* @since 5.0.6
* @product highstock
* @validvalue [0, 100]
* @apioption plotOptions.series.compareBase
*/
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* Factory function for creating new stock charts. Creates a new
* {@link Highcharts.Chart|Chart} object with different default options than the
* basic Chart.
*
* @example
* var chart = Highcharts.stockChart('container', {
* series: [{
* data: [1, 2, 3, 4, 5, 6, 7, 8, 9],
* pointInterval: 24 * 60 * 60 * 1000
* }]
* });
*
* @function Highcharts.stockChart
*
* @param {string|Highcharts.HTMLDOMElement} [renderTo]
* The DOM element to render to, or its id.
*
* @param {Highcharts.Options} options
* The chart options structure as described in the
* [options reference](https://api.highcharts.com/highstock).
*
* @param {Highcharts.ChartCallbackFunction} [callback]
* A function to execute when the chart object is finished loading and
* rendering. In most cases the chart is built in one thread, but in
* Internet Explorer version 8 or less the chart is sometimes
* initialized before the document is ready, and in these cases the
* chart object will not be finished synchronously. As a consequence,
* code that relies on the newly built Chart object should always run in
* the callback. Defining a
* [chart.events.load](https://api.highcharts.com/highstock/chart.events.load)
* handler is equivalent.
*
* @return {Highcharts.Chart}
* The chart object.
*/
H.StockChart = H.stockChart = function (a, b, c) {
var hasRenderToArg = isString(a) || a.nodeName, options = arguments[hasRenderToArg ? 1 : 0], userOptions = options,
// to increase performance, don't merge the data
seriesOptions = options.series, defaultOptions = H.getOptions(), opposite, panning = options.chart && options.chart.panning,
// Always disable startOnTick:true on the main axis when the navigator
// is enabled (#1090)
navigatorEnabled = pick(options.navigator && options.navigator.enabled, defaultOptions.navigator.enabled, true), verticalPanningEnabled = panning && /y/.test(panning.type), disableStartOnTick = {
startOnTick: false,
endOnTick: false
};
// apply X axis options to both single and multi y axes
options.xAxis = splat(options.xAxis || {}).map(function (xAxisOptions, i) {
return merge({
minPadding: 0,
maxPadding: 0,
overscroll: 0,
ordinal: true,
title: {
text: null
},
labels: {
overflow: 'justify'
},
showLastLabel: true
}, defaultOptions.xAxis, // #3802
defaultOptions.xAxis && defaultOptions.xAxis[i], // #7690
xAxisOptions, // user options
{
type: 'datetime',
categories: null
}, (navigatorEnabled ? disableStartOnTick : null));
});
// apply Y axis options to both single and multi y axes
options.yAxis = splat(options.yAxis || {}).map(function (yAxisOptions, i) {
opposite = pick(yAxisOptions.opposite, true);
return merge({
labels: {
y: -2
},
opposite: opposite,
/**
* @default {highcharts} true
* @default {highstock} false
* @apioption yAxis.showLastLabel
*
* @private
*/
showLastLabel: !!(
// #6104, show last label by default for category axes
yAxisOptions.categories ||
yAxisOptions.type === 'category'),
title: {
text: null
}
}, defaultOptions.yAxis, // #3802
defaultOptions.yAxis && defaultOptions.yAxis[i], // #7690
yAxisOptions, // user options
(verticalPanningEnabled ? disableStartOnTick : null));
});
options.series = null;
options = merge({
chart: {
panning: {
enabled: true,
type: 'x'
},
pinchType: 'x'
},
navigator: {
enabled: navigatorEnabled
},
scrollbar: {
// #4988 - check if setOptions was called
enabled: pick(defaultOptions.scrollbar.enabled, true)
},
rangeSelector: {
// #4988 - check if setOptions was called
enabled: pick(defaultOptions.rangeSelector.enabled, true)
},
title: {
text: null
},
tooltip: {
split: pick(defaultOptions.tooltip.split, true),
crosshairs: true
},
legend: {
enabled: false
}
}, options, // user's options
{
isStock: true // internal flag
});
options.series = userOptions.series = seriesOptions;
return hasRenderToArg ?
new Chart(a, options, c) :
new Chart(options, b);
};
// Handle som Stock-specific series defaults, override the plotOptions before
// series options are handled.
addEvent(Series, 'setOptions', function (e) {
var overrides;
if (this.chart.options.isStock) {
if (this.is('column') || this.is('columnrange')) {
overrides = {
borderWidth: 0,
shadow: false
};
}
else if (!this.is('scatter') && !this.is('sma')) {
overrides = {
marker: {
enabled: false,
radius: 2
}
};
}
if (overrides) {
e.plotOptions[this.type] = merge(e.plotOptions[this.type], overrides);
}
}
});
// Override the automatic label alignment so that the first Y axis' labels
// are drawn on top of the grid line, and subsequent axes are drawn outside
addEvent(Axis, 'autoLabelAlign', function (e) {
var chart = this.chart, options = this.options, panes = chart._labelPanes = chart._labelPanes || {}, key, labelOptions = this.options.labels;
if (this.chart.options.isStock && this.coll === 'yAxis') {
key = options.top + ',' + options.height;
// do it only for the first Y axis of each pane
if (!panes[key] && labelOptions.enabled) {
if (labelOptions.x === 15) { // default
labelOptions.x = 0;
}
if (typeof labelOptions.align === 'undefined') {
labelOptions.align = 'right';
}
panes[key] = this;
e.align = 'right';
e.preventDefault();
}
}
});
// Clear axis from label panes (#6071)
addEvent(Axis, 'destroy', function () {
var chart = this.chart, key = this.options && (this.options.top + ',' + this.options.height);
if (key && chart._labelPanes && chart._labelPanes[key] === this) {
delete chart._labelPanes[key];
}
});
// Override getPlotLinePath to allow for multipane charts
addEvent(Axis, 'getPlotLinePath', function (e) {
var axis = this, series = (this.isLinked && !this.series ?
this.linkedParent.series :
this.series), chart = axis.chart, renderer = chart.renderer, axisLeft = axis.left, axisTop = axis.top, x1, y1, x2, y2, result = [], axes = [], // #3416 need a default array
axes2, uniqueAxes, translatedValue = e.translatedValue, value = e.value, force = e.force, transVal;
/**
* Return the other axis based on either the axis option or on related
* series.
* @private
*/
function getAxis(coll) {
var otherColl = coll === 'xAxis' ? 'yAxis' : 'xAxis', opt = axis.options[otherColl];
// Other axis indexed by number
if (isNumber(opt)) {
return [chart[otherColl][opt]];
}
// Other axis indexed by id (like navigator)
if (isString(opt)) {
return [chart.get(opt)];
}
// Auto detect based on existing series
return series.map(function (s) {
return s[otherColl];
});
}
if ( // For stock chart, by default render paths across the panes
// except the case when `acrossPanes` is disabled by user (#6644)
(chart.options.isStock && e.acrossPanes !== false) &&
// Ignore in case of colorAxis or zAxis. #3360, #3524, #6720
axis.coll === 'xAxis' || axis.coll === 'yAxis') {
e.preventDefault();
// Get the related axes based on series
axes = getAxis(axis.coll);
// Get the related axes based options.*Axis setting #2810
axes2 = (axis.isXAxis ? chart.yAxis : chart.xAxis);
axes2.forEach(function (A) {
if (defined(A.options.id) ?
A.options.id.indexOf('navigator') === -1 :
true) {
var a = (A.isXAxis ? 'yAxis' : 'xAxis'), rax = (defined(A.options[a]) ?
chart[a][A.options[a]] :
chart[a][0]);
if (axis === rax) {
axes.push(A);
}
}
});
// Remove duplicates in the axes array. If there are no axes in the axes
// array, we are adding an axis without data, so we need to populate
// this with grid lines (#2796).
uniqueAxes = axes.length ?
[] :
[axis.isXAxis ? chart.yAxis[0] : chart.xAxis[0]]; // #3742
axes.forEach(function (axis2) {
if (uniqueAxes.indexOf(axis2) === -1 &&
// Do not draw on axis which overlap completely. #5424
!find(uniqueAxes, function (unique) {
return unique.pos === axis2.pos && unique.len === axis2.len;
})) {
uniqueAxes.push(axis2);
}
});
transVal = pick(translatedValue, axis.translate(value, null, null, e.old));
if (isNumber(transVal)) {
if (axis.horiz) {
uniqueAxes.forEach(function (axis2) {
var skip;
y1 = axis2.pos;
y2 = y1 + axis2.len;
x1 = x2 = Math.round(transVal + axis.transB);
// outside plot area
if (force !== 'pass' &&
(x1 < axisLeft || x1 > axisLeft + axis.width)) {
if (force) {
x1 = x2 = clamp(x1, axisLeft, axisLeft + axis.width);
}
else {
skip = true;
}
}
if (!skip) {
result.push('M', x1, y1, 'L', x2, y2);
}
});
}
else {
uniqueAxes.forEach(function (axis2) {
var skip;
x1 = axis2.pos;
x2 = x1 + axis2.len;
y1 = y2 = Math.round(axisTop + axis.height - transVal);
// outside plot area
if (force !== 'pass' &&
(y1 < axisTop || y1 > axisTop + axis.height)) {
if (force) {
y1 = y2 = clamp(y1, axisTop, axisTop + axis.height);
}
else {
skip = true;
}
}
if (!skip) {
result.push('M', x1, y1, 'L', x2, y2);
}
});
}
}
e.path = result.length > 0 ?
renderer.crispPolyLine(result, e.lineWidth || 1) :
// #3557 getPlotLinePath in regular Highcharts also returns null
null;
}
});
/**
* Function to crisp a line with multiple segments
*
* @private
* @function Highcharts.SVGRenderer#crispPolyLine
* @param {Highcharts.SVGPathArray} points
* @param {number} width
* @return {Highcharts.SVGPathArray}
*/
SVGRenderer.prototype.crispPolyLine = function (points, width) {
// points format: ['M', 0, 0, 'L', 100, 0]
// normalize to a crisp line
var i;
for (i = 0; i < points.length; i = i + 6) {
if (points[i + 1] === points[i + 4]) {
// Substract due to #1129. Now bottom and left axis gridlines behave
// the same.
points[i + 1] = points[i + 4] =
Math.round(points[i + 1]) - (width % 2 / 2);
}
if (points[i + 2] === points[i + 5]) {
points[i + 2] = points[i + 5] =
Math.round(points[i + 2]) + (width % 2 / 2);
}
}
return points;
};
if (Renderer === VMLRenderer) {
VMLRenderer.prototype.crispPolyLine = SVGRenderer.prototype.crispPolyLine;
}
// Wrapper to hide the label
addEvent(Axis, 'afterHideCrosshair', function () {
if (this.crossLabel) {
this.crossLabel = this.crossLabel.hide();
}
});
// Extend crosshairs to also draw the label
addEvent(Axis, 'afterDrawCrosshair', function (event) {
// Check if the label has to be drawn
if (!defined(this.crosshair.label) ||
!this.crosshair.label.enabled ||
!this.cross) {
return;
}
var chart = this.chart, options = this.options.crosshair.label, // the label's options
horiz = this.horiz, // axis orientation
opposite = this.opposite, // axis position
left = this.left, // left position
top = this.top, // top position
crossLabel = this.crossLabel, // the svgElement
posx, posy, crossBox, formatOption = options.format, formatFormat = '', limit, align, tickInside = this.options.tickPosition === 'inside', snap = this.crosshair.snap !== false, value, offset = 0,
// Use last available event (#5287)
e = event.e || (this.cross && this.cross.e), point = event.point, lin2log = this.lin2log, min, max;
if (this.isLog) {
min = lin2log(this.min);
max = lin2log(this.max);
}
else {
min = this.min;
max = this.max;
}
align = (horiz ? 'center' : opposite ?
(this.labelAlign === 'right' ? 'right' : 'left') :
(this.labelAlign === 'left' ? 'left' : 'center'));
// If the label does not exist yet, create it.
if (!crossLabel) {
crossLabel = this.crossLabel = chart.renderer
.label(null, null, null, options.shape || 'callout')
.addClass('highcharts-crosshair-label' + (this.series[0] &&
' highcharts-color-' + this.series[0].colorIndex))
.attr({
align: options.align || align,
padding: pick(options.padding, 8),
r: pick(options.borderRadius, 3),
zIndex: 2
})
.add(this.labelGroup);
// Presentational
if (!chart.styledMode) {
crossLabel
.attr({
fill: options.backgroundColor ||
(this.series[0] && this.series[0].color) ||
'#666666',
stroke: options.borderColor || '',
'stroke-width': options.borderWidth || 0
})
.css(extend({
color: '#ffffff',
fontWeight: 'normal',
fontSize: '11px',
textAlign: 'center'
}, options.style));
}
}
if (horiz) {
posx = snap ? point.plotX + left : e.chartX;
posy = top + (opposite ? 0 : this.height);
}
else {
posx = opposite ? this.width + left : 0;
posy = snap ? point.plotY + top : e.chartY;
}
if (!formatOption && !options.formatter) {
if (this.isDatetimeAxis) {
formatFormat = '%b %d, %Y';
}
formatOption =
'{value' + (formatFormat ? ':' + formatFormat : '') + '}';
}
// Show the label
value = snap ?
point[this.isXAxis ? 'x' : 'y'] :
this.toValue(horiz ? e.chartX : e.chartY);
crossLabel.attr({
text: formatOption ?
format(formatOption, { value: value }, chart) :
options.formatter.call(this, value),
x: posx,
y: posy,
// Crosshair should be rendered within Axis range (#7219)
visibility: value < min || value > max ?
'hidden' :
'visible'
});
crossBox = crossLabel.getBBox();
// now it is placed we can correct its position
if (horiz) {
if ((tickInside && !opposite) || (!tickInside && opposite)) {
posy = crossLabel.y - crossBox.height;
}
}
else {
posy = crossLabel.y - (crossBox.height / 2);
}
// check the edges
if (horiz) {
limit = {
left: left - crossBox.x,
right: left + this.width - crossBox.x
};
}
else {
limit = {
left: this.labelAlign === 'left' ? left : 0,
right: this.labelAlign === 'right' ?
left + this.width :
chart.chartWidth
};
}
// left edge
if (crossLabel.translateX < limit.left) {
offset = limit.left - crossLabel.translateX;
}
// right edge
if (crossLabel.translateX + crossBox.width >= limit.right) {
offset = -(crossLabel.translateX + crossBox.width - limit.right);
}
// show the crosslabel
crossLabel.attr({
x: posx + offset,
y: posy,
// First set x and y, then anchorX and anchorY, when box is actually
// calculated, #5702
anchorX: horiz ?
posx :
(this.opposite ? 0 : chart.chartWidth),
anchorY: horiz ?
(this.opposite ? chart.chartHeight : 0) :
posy + crossBox.height / 2
});
});
/* ************************************************************************** *
* Start value compare logic *
* ************************************************************************** */
/**
* Extend series.init by adding a method to modify the y value used for plotting
* on the y axis. This method is called both from the axis when finding dataMin
* and dataMax, and from the series.translate method.
*
* @ignore
* @function Highcharts.Series#init
*/
seriesProto.init = function () {
// Call base method
seriesInit.apply(this, arguments);
// Set comparison mode
this.setCompare(this.options.compare);
};
/**
* Highstock only. Set the
* [compare](https://api.highcharts.com/highstock/plotOptions.series.compare)
* mode of the series after render time. In most cases it is more useful running
* {@link Axis#setCompare} on the X axis to update all its series.
*
* @function Highcharts.Series#setCompare
*
* @param {string} [compare]
* Can be one of `null` (default), `"percent"` or `"value"`.
*/
seriesProto.setCompare = function (compare) {
// Set or unset the modifyValue method
this.modifyValue = (compare === 'value' || compare === 'percent') ?
function (value, point) {
var compareValue = this.compareValue;
if (typeof value !== 'undefined' &&
typeof compareValue !== 'undefined') { // #2601, #5814
// Get the modified value
if (compare === 'value') {
value -= compareValue;
// Compare percent
}
else {
value = 100 * (value / compareValue) -
(this.options.compareBase === 100 ? 0 : 100);
}
// record for tooltip etc.
if (point) {
point.change = value;
}
return value;
}
return 0;
} :
null;
// Survive to export, #5485
this.userOptions.compare = compare;
// Mark dirty
if (this.chart.hasRendered) {
this.isDirty = true;
}
};
/**
* Extend series.processData by finding the first y value in the plot area,
* used for comparing the following values
*
* @ignore
* @function Highcharts.Series#processData
*/
seriesProto.processData = function (force) {
var series = this, i, keyIndex = -1, processedXData, processedYData, compareStart = series.options.compareStart === true ? 0 : 1, length, compareValue;
// call base method
seriesProcessData.apply(this, arguments);
if (series.xAxis && series.processedYData) { // not pies
// local variables
processedXData = series.processedXData;
processedYData = series.processedYData;
length = processedYData.length;
// For series with more than one value (range, OHLC etc), compare
// against close or the pointValKey (#4922, #3112, #9854)
if (series.pointArrayMap) {
keyIndex = series.pointArrayMap.indexOf(series.options.pointValKey || series.pointValKey || 'y');
}
// find the first value for comparison
for (i = 0; i < length - compareStart; i++) {
compareValue = processedYData[i] && keyIndex > -1 ?
processedYData[i][keyIndex] :
processedYData[i];
if (isNumber(compareValue) &&
processedXData[i + compareStart] >=
series.xAxis.min &&
compareValue !== 0) {
series.compareValue = compareValue;
break;
}
}
}
return;
};
// Modify series extremes
addEvent(Series, 'afterGetExtremes', function () {
if (this.modifyValue) {
var extremes = [
this.modifyValue(this.dataMin),
this.modifyValue(this.dataMax)
];
this.dataMin = arrayMin(extremes);
this.dataMax = arrayMax(extremes);
}
});
/**
* Highstock only. Set the compare mode on all series belonging to an Y axis
* after render time.
*
* @see [series.plotOptions.compare](https://api.highcharts.com/highstock/series.plotOptions.compare)
*
* @sample stock/members/axis-setcompare/
* Set compoare
*
* @function Highcharts.Axis#setCompare
*
* @param {string} [compare]
* The compare mode. Can be one of `null` (default), `"value"` or
* `"percent"`.
*
* @param {boolean} [redraw=true]
* Whether to redraw the chart or to wait for a later call to
* {@link Chart#redraw}.
*/
Axis.prototype.setCompare = function (compare, redraw) {
if (!this.isXAxis) {
this.series.forEach(function (series) {
series.setCompare(compare);
});
if (pick(redraw, true)) {
this.chart.redraw();
}
}
};
/**
* Extend the tooltip formatter by adding support for the point.change variable
* as well as the changeDecimals option.
*
* @ignore
* @function Highcharts.Point#tooltipFormatter
*
* @param {string} pointFormat
*/
Point.prototype.tooltipFormatter = function (pointFormat) {
var point = this;
var numberFormatter = point.series.chart.numberFormatter;
pointFormat = pointFormat.replace('{point.change}', (point.change > 0 ? '+' : '') + numberFormatter(point.change, pick(point.series.tooltipOptions.changeDecimals, 2)));
return pointTooltipFormatter.apply(this, [pointFormat]);
};
/* ************************************************************************** *
* End value compare logic *
* ************************************************************************** */
// Extend the Series prototype to create a separate series clip box. This is
// related to using multiple panes, and a future pane logic should incorporate
// this feature (#2754).
addEvent(Series, 'render', function () {
var chart = this.chart, clipHeight;
// Only do this on not 3d (#2939, #5904) nor polar (#6057) charts, and only
// if the series type handles clipping in the animate method (#2975).
if (!(chart.is3d && chart.is3d()) &&
!chart.polar &&
this.xAxis &&
!this.xAxis.isRadial // Gauge, #6192
) {
clipHeight = this.yAxis.len;
// Include xAxis line width (#8031) but only if the Y axis ends on the
// edge of the X axis (#11005).
if (this.xAxis.axisLine) {
var dist = chart.plotTop + chart.plotHeight -
this.yAxis.pos - this.yAxis.len, lineHeightCorrection = Math.floor(this.xAxis.axisLine.strokeWidth() / 2);
if (dist >= 0) {
clipHeight -= Math.max(lineHeightCorrection - dist, 0);
}
}
// First render, initial clip box
if (!this.clipBox && this.animate) {
this.clipBox = merge(chart.clipBox);
this.clipBox.width = this.xAxis.len;
this.clipBox.height = clipHeight;
// On redrawing, resizing etc, update the clip rectangle
}
else if (chart[this.sharedClipKey]) {
// animate in case resize is done during initial animation
chart[this.sharedClipKey].animate({
width: this.xAxis.len,
height: clipHeight
});
// also change markers clip animation for consistency
// (marker clip rects should exist only on chart init)
if (chart[this.sharedClipKey + 'm']) {
chart[this.sharedClipKey + 'm'].animate({
width: this.xAxis.len
});
}
}
}
});
addEvent(Chart, 'update', function (e) {
var options = e.options;
// Use case: enabling scrollbar from a disabled state.
// Scrollbar needs to be initialized from a controller, Navigator in this
// case (#6615)
if ('scrollbar' in options && this.navigator) {
merge(true, this.options.scrollbar, options.scrollbar);
this.navigator.update({}, false);
delete options.scrollbar;
}
});
// Extend the Axis prototype to calculate start min/max values
// (including min/maxPadding). This is related to using vertical panning
// (#11315).
addEvent(Axis, 'afterSetScale', function () {
var axis = this, panning = axis.chart.options.chart &&
axis.chart.options.chart.panning;
if (panning &&
(panning.type === 'y' ||
panning.type === 'xy') &&
!axis.isXAxis &&
!defined(axis.panningState)) {
var min = Number.MAX_VALUE, max = Number.MIN_VALUE;
axis.series.forEach(function (series) {
min = Math.min(H.arrayMin(series.yData), min) -
(axis.min && axis.dataMin ? axis.dataMin - axis.min : 0);
max = Math.max(H.arrayMax(series.yData), max) +
(axis.max && axis.dataMax ? axis.max - axis.dataMax : 0);
});
axis.panningState = {
startMin: min,
startMax: max
};
}
});

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,660 @@
/* *
*
* (c) 2010-2020 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from './Globals.js';
/**
* Optional parameters for the tick.
* @private
* @interface Highcharts.TickParametersObject
*/ /**
* Set category for the tick.
* @name Highcharts.TickParametersObject#category
* @type {string|undefined}
*/ /**
* @name Highcharts.TickParametersObject#options
* @type {Highcharts.Dictionary<any>|undefined}
*/ /**
* Set tickmarkOffset for the tick.
* @name Highcharts.TickParametersObject#tickmarkOffset
* @type {number|undefined}
*/
import U from './Utilities.js';
var clamp = U.clamp, correctFloat = U.correctFloat, defined = U.defined, destroyObjectProperties = U.destroyObjectProperties, extend = U.extend, isNumber = U.isNumber, merge = U.merge, objectEach = U.objectEach, pick = U.pick;
var fireEvent = H.fireEvent, deg2rad = H.deg2rad;
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* The Tick class.
*
* @class
* @name Highcharts.Tick
*
* @param {Highcharts.Axis} axis
* The axis of the tick.
*
* @param {number} pos
* The position of the tick on the axis in terms of axis values.
*
* @param {string} [type]
* The type of tick, either 'minor' or an empty string
*
* @param {boolean} [noLabel=false]
* Whether to disable the label or not. Defaults to false.
*
* @param {object} [parameters]
* Optional parameters for the tick.
*/
var Tick = /** @class */ (function () {
/* *
*
* Constructors
*
* */
function Tick(axis, pos, type, noLabel, parameters) {
this.isNew = true;
this.isNewLabel = true;
/**
* The related axis of the tick.
* @name Highcharts.Tick#axis
* @type {Highcharts.Axis}
*/
this.axis = axis;
/**
* The logical position of the tick on the axis in terms of axis values.
* @name Highcharts.Tick#pos
* @type {number}
*/
this.pos = pos;
/**
* The tick type, which can be `"minor"`, or an empty string.
* @name Highcharts.Tick#type
* @type {string}
*/
this.type = type || '';
this.parameters = parameters || {};
/**
* The mark offset of the tick on the axis. Usually `undefined`, numeric
* for grid axes.
* @name Highcharts.Tick#tickmarkOffset
* @type {number|undefined}
*/
this.tickmarkOffset = this.parameters.tickmarkOffset;
this.options = this.parameters.options;
if (!type && !noLabel) {
this.addLabel();
}
}
/* *
*
* Functions
*
* */
/**
* Write the tick label.
*
* @private
* @function Highcharts.Tick#addLabel
* @return {void}
*/
Tick.prototype.addLabel = function () {
var tick = this, axis = tick.axis, options = axis.options, chart = axis.chart, categories = axis.categories, names = axis.names, pos = tick.pos, labelOptions = pick(tick.options && tick.options.labels, options.labels), str, tickPositions = axis.tickPositions, isFirst = pos === tickPositions[0], isLast = pos === tickPositions[tickPositions.length - 1], value = this.parameters.category || (categories ?
pick(categories[pos], names[pos], pos) :
pos), label = tick.label, animateLabels = (!labelOptions.step || labelOptions.step === 1) &&
axis.tickInterval === 1, tickPositionInfo = tickPositions.info, dateTimeLabelFormat, dateTimeLabelFormats, i, list;
// Set the datetime label format. If a higher rank is set for this
// position, use that. If not, use the general format.
if (axis.isDatetimeAxis && tickPositionInfo) {
dateTimeLabelFormats = chart.time.resolveDTLFormat(options.dateTimeLabelFormats[(!options.grid &&
tickPositionInfo.higherRanks[pos]) ||
tickPositionInfo.unitName]);
dateTimeLabelFormat = dateTimeLabelFormats.main;
}
// set properties for access in render method
/**
* True if the tick is the first one on the axis.
* @name Highcharts.Tick#isFirst
* @readonly
* @type {boolean|undefined}
*/
tick.isFirst = isFirst;
/**
* True if the tick is the last one on the axis.
* @name Highcharts.Tick#isLast
* @readonly
* @type {boolean|undefined}
*/
tick.isLast = isLast;
// Get the string
tick.formatCtx = {
axis: axis,
chart: chart,
isFirst: isFirst,
isLast: isLast,
dateTimeLabelFormat: dateTimeLabelFormat,
tickPositionInfo: tickPositionInfo,
value: axis.isLog ? correctFloat(axis.lin2log(value)) : value,
pos: pos
};
str = axis.labelFormatter.call(tick.formatCtx, this.formatCtx);
// Set up conditional formatting based on the format list if existing.
list = dateTimeLabelFormats && dateTimeLabelFormats.list;
if (list) {
tick.shortenLabel = function () {
for (i = 0; i < list.length; i++) {
label.attr({
text: axis.labelFormatter.call(extend(tick.formatCtx, { dateTimeLabelFormat: list[i] }))
});
if (label.getBBox().width <
axis.getSlotWidth(tick) - 2 *
pick(labelOptions.padding, 5)) {
return;
}
}
label.attr({
text: ''
});
};
}
// Call only after first render
if (animateLabels && axis._addedPlotLB && axis.isXAxis) {
tick.moveLabel(str, labelOptions);
}
// First call
if (!defined(label) && !tick.movedLabel) {
tick.label = label = tick.createLabel({ x: 0, y: 0 }, str, labelOptions);
// Base value to detect change for new calls to getBBox
tick.rotation = 0;
// update
}
else if (label && label.textStr !== str && !animateLabels) {
// When resetting text, also reset the width if dynamically set
// (#8809)
if (label.textWidth &&
!(labelOptions.style && labelOptions.style.width) &&
!label.styles.width) {
label.css({ width: null });
}
label.attr({ text: str });
label.textPxLength = label.getBBox().width;
}
};
/**
* Render and return the label of the tick.
*
* @private
* @function Highcharts.Tick#createLabel
* @param {Highcharts.PositionObject} xy
* @param {string} str
* @param {Highcharts.XAxisLabelsOptions} labelOptions
* @return {Highcharts.SVGElement|undefined}
*/
Tick.prototype.createLabel = function (xy, str, labelOptions) {
var axis = this.axis, chart = axis.chart, label = defined(str) && labelOptions.enabled ?
chart.renderer
.text(str, xy.x, xy.y, labelOptions.useHTML)
.add(axis.labelGroup) :
null;
// Un-rotated length
if (label) {
// Without position absolute, IE export sometimes is wrong
if (!chart.styledMode) {
label.css(merge(labelOptions.style));
}
label.textPxLength = label.getBBox().width;
}
return label;
};
/**
* Destructor for the tick prototype
*
* @private
* @function Highcharts.Tick#destroy
* @return {void}
*/
Tick.prototype.destroy = function () {
destroyObjectProperties(this, this.axis);
};
/**
* Gets the x and y positions for ticks in terms of pixels.
*
* @private
* @function Highcharts.Tick#getPosition
*
* @param {boolean} horiz
* Whether the tick is on an horizontal axis or not.
*
* @param {number} tickPos
* Position of the tick.
*
* @param {number} tickmarkOffset
* Tickmark offset for all ticks.
*
* @param {boolean} [old]
* Whether the axis has changed or not.
*
* @return {Highcharts.PositionObject}
* The tick position.
*
* @fires Highcharts.Tick#event:afterGetPosition
*/
Tick.prototype.getPosition = function (horiz, tickPos, tickmarkOffset, old) {
var axis = this.axis, chart = axis.chart, cHeight = (old && chart.oldChartHeight) || chart.chartHeight, pos;
pos = {
x: horiz ?
correctFloat(axis.translate(tickPos + tickmarkOffset, null, null, old) +
axis.transB) :
(axis.left +
axis.offset +
(axis.opposite ?
(((old && chart.oldChartWidth) ||
chart.chartWidth) -
axis.right -
axis.left) :
0)),
y: horiz ?
(cHeight -
axis.bottom +
axis.offset -
(axis.opposite ? axis.height : 0)) :
correctFloat(cHeight -
axis.translate(tickPos + tickmarkOffset, null, null, old) -
axis.transB)
};
// Chrome workaround for #10516
pos.y = clamp(pos.y, -1e5, 1e5);
fireEvent(this, 'afterGetPosition', { pos: pos });
return pos;
};
/**
* Get the x, y position of the tick label
*
* @private
* @return {Highcharts.PositionObject}
*/
Tick.prototype.getLabelPosition = function (x, y, label, horiz, labelOptions, tickmarkOffset, index, step) {
var axis = this.axis, transA = axis.transA, reversed = ( // #7911
axis.isLinked && axis.linkedParent ?
axis.linkedParent.reversed :
axis.reversed), staggerLines = axis.staggerLines, rotCorr = axis.tickRotCorr || { x: 0, y: 0 }, yOffset = labelOptions.y,
// Adjust for label alignment if we use reserveSpace: true (#5286)
labelOffsetCorrection = (!horiz && !axis.reserveSpaceDefault ?
-axis.labelOffset * (axis.labelAlign === 'center' ? 0.5 : 1) :
0), line, pos = {};
if (!defined(yOffset)) {
if (axis.side === 0) {
yOffset = label.rotation ? -8 : -label.getBBox().height;
}
else if (axis.side === 2) {
yOffset = rotCorr.y + 8;
}
else {
// #3140, #3140
yOffset = Math.cos(label.rotation * deg2rad) *
(rotCorr.y - label.getBBox(false, 0).height / 2);
}
}
x = x +
labelOptions.x +
labelOffsetCorrection +
rotCorr.x -
(tickmarkOffset && horiz ?
tickmarkOffset * transA * (reversed ? -1 : 1) :
0);
y = y + yOffset - (tickmarkOffset && !horiz ?
tickmarkOffset * transA * (reversed ? 1 : -1) : 0);
// Correct for staggered labels
if (staggerLines) {
line = (index / (step || 1) % staggerLines);
if (axis.opposite) {
line = staggerLines - line - 1;
}
y += line * (axis.labelOffset / staggerLines);
}
pos.x = x;
pos.y = Math.round(y);
fireEvent(this, 'afterGetLabelPosition', { pos: pos, tickmarkOffset: tickmarkOffset, index: index });
return pos;
};
/**
* Get the offset height or width of the label
*
* @private
* @function Highcharts.Tick#getLabelSize
* @return {number}
*/
Tick.prototype.getLabelSize = function () {
return this.label ?
this.label.getBBox()[this.axis.horiz ? 'height' : 'width'] :
0;
};
/**
* Extendible method to return the path of the marker
*
* @private
*
*/
Tick.prototype.getMarkPath = function (x, y, tickLength, tickWidth, horiz, renderer) {
return renderer.crispLine([
'M',
x,
y,
'L',
x + (horiz ? 0 : -tickLength),
y + (horiz ? tickLength : 0)
], tickWidth);
};
/**
* Handle the label overflow by adjusting the labels to the left and right
* edge, or hide them if they collide into the neighbour label.
*
* @private
* @function Highcharts.Tick#handleOverflow
* @param {Highcharts.PositionObject} xy
* @return {void}
*/
Tick.prototype.handleOverflow = function (xy) {
var tick = this, axis = this.axis, labelOptions = axis.options.labels, pxPos = xy.x, chartWidth = axis.chart.chartWidth, spacing = axis.chart.spacing, leftBound = pick(axis.labelLeft, Math.min(axis.pos, spacing[3])), rightBound = pick(axis.labelRight, Math.max(!axis.isRadial ? axis.pos + axis.len : 0, chartWidth - spacing[1])), label = this.label, rotation = this.rotation, factor = {
left: 0,
center: 0.5,
right: 1
}[axis.labelAlign || label.attr('align')], labelWidth = label.getBBox().width, slotWidth = axis.getSlotWidth(tick), modifiedSlotWidth = slotWidth, xCorrection = factor, goRight = 1, leftPos, rightPos, textWidth, css = {};
// Check if the label overshoots the chart spacing box. If it does, move
// it. If it now overshoots the slotWidth, add ellipsis.
if (!rotation &&
pick(labelOptions.overflow, 'justify') === 'justify') {
leftPos = pxPos - factor * labelWidth;
rightPos = pxPos + (1 - factor) * labelWidth;
if (leftPos < leftBound) {
modifiedSlotWidth =
xy.x + modifiedSlotWidth * (1 - factor) - leftBound;
}
else if (rightPos > rightBound) {
modifiedSlotWidth =
rightBound - xy.x + modifiedSlotWidth * factor;
goRight = -1;
}
modifiedSlotWidth = Math.min(slotWidth, modifiedSlotWidth); // #4177
if (modifiedSlotWidth < slotWidth && axis.labelAlign === 'center') {
xy.x += (goRight *
(slotWidth -
modifiedSlotWidth -
xCorrection * (slotWidth - Math.min(labelWidth, modifiedSlotWidth))));
}
// If the label width exceeds the available space, set a text width
// to be picked up below. Also, if a width has been set before, we
// need to set a new one because the reported labelWidth will be
// limited by the box (#3938).
if (labelWidth > modifiedSlotWidth ||
(axis.autoRotation && (label.styles || {}).width)) {
textWidth = modifiedSlotWidth;
}
// Add ellipsis to prevent rotated labels to be clipped against the edge
// of the chart
}
else if (rotation < 0 &&
pxPos - factor * labelWidth < leftBound) {
textWidth = Math.round(pxPos / Math.cos(rotation * deg2rad) - leftBound);
}
else if (rotation > 0 &&
pxPos + factor * labelWidth > rightBound) {
textWidth = Math.round((chartWidth - pxPos) /
Math.cos(rotation * deg2rad));
}
if (textWidth) {
if (tick.shortenLabel) {
tick.shortenLabel();
}
else {
css.width = Math.floor(textWidth);
if (!(labelOptions.style || {}).textOverflow) {
css.textOverflow = 'ellipsis';
}
label.css(css);
}
}
};
/**
* Try to replace the label if the same one already exists.
*
* @private
* @function Highcharts.Tick#moveLabel
* @param {string} str
* @param {Highcharts.XAxisLabelsOptions} labelOptions
*
* @return {void}
*/
Tick.prototype.moveLabel = function (str, labelOptions) {
var tick = this, label = tick.label, moved = false, xAxis = tick.axis, chart = xAxis.chart, labelPos, reversed = xAxis.reversed, inverted = chart.inverted, xPos, yPos;
if (label && label.textStr === str) {
tick.movedLabel = label;
moved = true;
delete tick.label;
}
else { // Find a label with the same string
objectEach(xAxis.ticks, function (currentTick) {
if (!moved &&
!currentTick.isNew &&
currentTick !== tick &&
currentTick.label &&
currentTick.label.textStr === str) {
tick.movedLabel = currentTick.label;
moved = true;
currentTick.labelPos = tick.movedLabel.xy;
delete currentTick.label;
}
});
}
// Create new label if the actual one is moved
if (!moved && (tick.labelPos || label)) {
labelPos = tick.labelPos || label.xy;
xPos = inverted ?
labelPos.x : (reversed ? 0 : xAxis.width + xAxis.left);
yPos = inverted ?
(reversed ? (xAxis.width + xAxis.left) : 0) : labelPos.y;
tick.movedLabel = tick.createLabel({ x: xPos, y: yPos }, str, labelOptions);
if (tick.movedLabel) {
tick.movedLabel.attr({ opacity: 0 });
}
}
};
/**
* Put everything in place
*
* @private
* @param {number} index
* @param {boolean} [old]
* Use old coordinates to prepare an animation into new position
* @param {number} [opacity]
* @return {voids}
*/
Tick.prototype.render = function (index, old, opacity) {
var tick = this, axis = tick.axis, horiz = axis.horiz, pos = tick.pos, tickmarkOffset = pick(tick.tickmarkOffset, axis.tickmarkOffset), xy = tick.getPosition(horiz, pos, tickmarkOffset, old), x = xy.x, y = xy.y, reverseCrisp = ((horiz && x === axis.pos + axis.len) ||
(!horiz && y === axis.pos)) ? -1 : 1; // #1480, #1687
opacity = pick(opacity, 1);
this.isActive = true;
// Create the grid line
this.renderGridLine(old, opacity, reverseCrisp);
// create the tick mark
this.renderMark(xy, opacity, reverseCrisp);
// the label is created on init - now move it into place
this.renderLabel(xy, old, opacity, index);
tick.isNew = false;
H.fireEvent(this, 'afterRender');
};
/**
* Renders the gridLine.
*
* @private
* @param {boolean} old Whether or not the tick is old
* @param {number} opacity The opacity of the grid line
* @param {number} reverseCrisp Modifier for avoiding overlapping 1 or -1
* @return {void}
*/
Tick.prototype.renderGridLine = function (old, opacity, reverseCrisp) {
var tick = this, axis = tick.axis, options = axis.options, gridLine = tick.gridLine, gridLinePath, attribs = {}, pos = tick.pos, type = tick.type, tickmarkOffset = pick(tick.tickmarkOffset, axis.tickmarkOffset), renderer = axis.chart.renderer, gridPrefix = type ? type + 'Grid' : 'grid', gridLineWidth = options[gridPrefix + 'LineWidth'], gridLineColor = options[gridPrefix + 'LineColor'], dashStyle = options[gridPrefix + 'LineDashStyle'];
if (!gridLine) {
if (!axis.chart.styledMode) {
attribs.stroke = gridLineColor;
attribs['stroke-width'] = gridLineWidth;
if (dashStyle) {
attribs.dashstyle = dashStyle;
}
}
if (!type) {
attribs.zIndex = 1;
}
if (old) {
opacity = 0;
}
/**
* The rendered grid line of the tick.
* @name Highcharts.Tick#gridLine
* @type {Highcharts.SVGElement|undefined}
*/
tick.gridLine = gridLine = renderer.path()
.attr(attribs)
.addClass('highcharts-' + (type ? type + '-' : '') + 'grid-line')
.add(axis.gridGroup);
}
if (gridLine) {
gridLinePath = axis.getPlotLinePath({
value: pos + tickmarkOffset,
lineWidth: gridLine.strokeWidth() * reverseCrisp,
force: 'pass',
old: old
});
// If the parameter 'old' is set, the current call will be followed
// by another call, therefore do not do any animations this time
if (gridLinePath) {
gridLine[old || tick.isNew ? 'attr' : 'animate']({
d: gridLinePath,
opacity: opacity
});
}
}
};
/**
* Renders the tick mark.
*
* @private
* @param {Highcharts.PositionObject} xy The position vector of the mark
* @param {number} opacity The opacity of the mark
* @param {number} reverseCrisp Modifier for avoiding overlapping 1 or -1
* @return {void}
*/
Tick.prototype.renderMark = function (xy, opacity, reverseCrisp) {
var tick = this, axis = tick.axis, options = axis.options, renderer = axis.chart.renderer, type = tick.type, tickPrefix = type ? type + 'Tick' : 'tick', tickSize = axis.tickSize(tickPrefix), mark = tick.mark, isNewMark = !mark, x = xy.x, y = xy.y, tickWidth = pick(options[tickPrefix + 'Width'], !type && axis.isXAxis ? 1 : 0), // X axis defaults to 1
tickColor = options[tickPrefix + 'Color'];
if (tickSize) {
// negate the length
if (axis.opposite) {
tickSize[0] = -tickSize[0];
}
// First time, create it
if (isNewMark) {
/**
* The rendered mark of the tick.
* @name Highcharts.Tick#mark
* @type {Highcharts.SVGElement|undefined}
*/
tick.mark = mark = renderer.path()
.addClass('highcharts-' + (type ? type + '-' : '') + 'tick')
.add(axis.axisGroup);
if (!axis.chart.styledMode) {
mark.attr({
stroke: tickColor,
'stroke-width': tickWidth
});
}
}
mark[isNewMark ? 'attr' : 'animate']({
d: tick.getMarkPath(x, y, tickSize[0], mark.strokeWidth() * reverseCrisp, axis.horiz, renderer),
opacity: opacity
});
}
};
/**
* Renders the tick label.
* Note: The label should already be created in init(), so it should only
* have to be moved into place.
*
* @private
* @param {Highcharts.PositionObject} xy The position vector of the label
* @param {boolean} old Whether or not the tick is old
* @param {number} opacity The opacity of the label
* @param {number} index The index of the tick
* @return {void}
*/
Tick.prototype.renderLabel = function (xy, old, opacity, index) {
var tick = this, axis = tick.axis, horiz = axis.horiz, options = axis.options, label = tick.label, labelOptions = options.labels, step = labelOptions.step, tickmarkOffset = pick(tick.tickmarkOffset, axis.tickmarkOffset), show = true, x = xy.x, y = xy.y;
if (label && isNumber(x)) {
label.xy = xy = tick.getLabelPosition(x, y, label, horiz, labelOptions, tickmarkOffset, index, step);
// Apply show first and show last. If the tick is both first and
// last, it is a single centered tick, in which case we show the
// label anyway (#2100).
if ((tick.isFirst &&
!tick.isLast &&
!pick(options.showFirstLabel, 1)) ||
(tick.isLast &&
!tick.isFirst &&
!pick(options.showLastLabel, 1))) {
show = false;
// Handle label overflow and show or hide accordingly
}
else if (horiz &&
!labelOptions.step &&
!labelOptions.rotation &&
!old &&
opacity !== 0) {
tick.handleOverflow(xy);
}
// apply step
if (step && index % step) {
// show those indices dividable by step
show = false;
}
// Set the new position, and show or hide
if (show && isNumber(xy.y)) {
xy.opacity = opacity;
label[tick.isNewLabel ? 'attr' : 'animate'](xy);
tick.isNewLabel = false;
}
else {
label.attr('y', -9999); // #1338
tick.isNewLabel = true;
}
}
};
/**
* Replace labels with the moved ones to perform animation. Additionally
* destroy unused labels.
*
* @private
* @function Highcharts.Tick#replaceMovedLabel
* @return {void}
*/
Tick.prototype.replaceMovedLabel = function () {
var tick = this, label = tick.label, axis = tick.axis, reversed = axis.reversed, chart = tick.axis.chart, inverted = chart.inverted, x, y;
// Animate and destroy
if (label && !tick.isNew) {
x = inverted ? label.xy.x : (reversed ? axis.left : axis.width + axis.left);
y = inverted ?
(reversed ? axis.width + axis.top : axis.top) :
label.xy.y;
label.animate({ x: x, y: y, opacity: 0 }, void 0, label.destroy);
delete tick.label;
}
axis.isDirty = true;
tick.label = tick.movedLabel;
delete tick.movedLabel;
};
return Tick;
}());
H.Tick = Tick;
export default H.Tick;

View File

@@ -0,0 +1,778 @@
/* *
*
* (c) 2010-2020 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import Highcharts from './Globals.js';
/**
* Normalized interval.
*
* @interface Highcharts.TimeNormalizedObject
*/ /**
* The count.
*
* @name Highcharts.TimeNormalizedObject#count
* @type {number}
*/ /**
* The interval in axis values (ms).
*
* @name Highcharts.TimeNormalizedObject#unitRange
* @type {number}
*/
/**
* Function of an additional date format specifier.
*
* @callback Highcharts.TimeFormatCallbackFunction
*
* @param {number} timestamp
* The time to format.
*
* @return {string}
* The formatted portion of the date.
*/
/**
* Additonal time tick information.
*
* @interface Highcharts.TimeTicksInfoObject
* @extends Highcharts.TimeNormalizedObject
*/ /**
* @name Highcharts.TimeTicksInfoObject#higherRanks
* @type {Array<string>}
*/ /**
* @name Highcharts.TimeTicksInfoObject#totalRange
* @type {number}
*/
/**
* Time ticks.
*
* @interface Highcharts.AxisTickPositionsArray
* @extends global.Array<number>
*/ /**
* @name Highcharts.AxisTickPositionsArray#info
* @type {Highcharts.TimeTicksInfoObject|undefined}
*/
/**
* A callback to return the time zone offset for a given datetime. It
* takes the timestamp in terms of milliseconds since January 1 1970,
* and returns the timezone offset in minutes. This provides a hook
* for drawing time based charts in specific time zones using their
* local DST crossover dates, with the help of external libraries.
*
* @callback Highcharts.TimezoneOffsetCallbackFunction
*
* @param {number} timestamp
* Timestamp in terms of milliseconds since January 1 1970.
*
* @return {number}
* Timezone offset in minutes.
*/
import U from './Utilities.js';
var defined = U.defined, error = U.error, extend = U.extend, isObject = U.isObject, merge = U.merge, objectEach = U.objectEach, pad = U.pad, pick = U.pick, splat = U.splat, timeUnits = U.timeUnits;
var H = Highcharts, win = H.win;
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* The Time class. Time settings are applied in general for each page using
* `Highcharts.setOptions`, or individually for each Chart item through the
* [time](https://api.highcharts.com/highcharts/time) options set.
*
* The Time object is available from {@link Highcharts.Chart#time},
* which refers to `Highcharts.time` if no individual time settings are
* applied.
*
* @example
* // Apply time settings globally
* Highcharts.setOptions({
* time: {
* timezone: 'Europe/London'
* }
* });
*
* // Apply time settings by instance
* var chart = Highcharts.chart('container', {
* time: {
* timezone: 'America/New_York'
* },
* series: [{
* data: [1, 4, 3, 5]
* }]
* });
*
* // Use the Time object
* console.log(
* 'Current time in New York',
* chart.time.dateFormat('%Y-%m-%d %H:%M:%S', Date.now())
* );
*
* @since 6.0.5
*
* @class
* @name Highcharts.Time
*
* @param {Highcharts.TimeOptions} options
* Time options as defined in [chart.options.time](/highcharts/time).
*/
var Time = /** @class */ (function () {
/* *
*
* Constructors
*
* */
function Time(options) {
/* *
*
* Properties
*
* */
this.options = {};
this.useUTC = false;
this.variableTimezone = false;
this.Date = win.Date;
/**
* Get the time zone offset based on the current timezone information as
* set in the global options.
*
* @function Highcharts.Time#getTimezoneOffset
*
* @param {number} timestamp
* The JavaScript timestamp to inspect.
*
* @return {number}
* The timezone offset in minutes compared to UTC.
*/
this.getTimezoneOffset = this.timezoneOffsetFunction();
this.update(options);
}
/* *
*
* Functions
*
* */
/**
* Time units used in `Time.get` and `Time.set`
*
* @typedef {"Date"|"Day"|"FullYear"|"Hours"|"Milliseconds"|"Minutes"|"Month"|"Seconds"} Highcharts.TimeUnitValue
*/
/**
* Get the value of a date object in given units, and subject to the Time
* object's current timezone settings. This function corresponds directly to
* JavaScripts `Date.getXXX / Date.getUTCXXX`, so instead of calling
* `date.getHours()` or `date.getUTCHours()` we will call
* `time.get('Hours')`.
*
* @function Highcharts.Time#get
*
* @param {Highcharts.TimeUnitValue} unit
* @param {Date} date
*
* @return {number}
* The given time unit
*/
Time.prototype.get = function (unit, date) {
if (this.variableTimezone || this.timezoneOffset) {
var realMs = date.getTime();
var ms = realMs - this.getTimezoneOffset(date);
date.setTime(ms); // Temporary adjust to timezone
var ret = date['getUTC' + unit]();
date.setTime(realMs); // Reset
return ret;
}
// UTC time with no timezone handling
if (this.useUTC) {
return date['getUTC' + unit]();
}
// Else, local time
return date['get' + unit]();
};
/**
* Set the value of a date object in given units, and subject to the Time
* object's current timezone settings. This function corresponds directly to
* JavaScripts `Date.setXXX / Date.setUTCXXX`, so instead of calling
* `date.setHours(0)` or `date.setUTCHours(0)` we will call
* `time.set('Hours', 0)`.
*
* @function Highcharts.Time#set
*
* @param {Highcharts.TimeUnitValue} unit
* @param {Date} date
* @param {number} value
*
* @return {number}
* The epoch milliseconds of the updated date
*/
Time.prototype.set = function (unit, date, value) {
// UTC time with timezone handling
if (this.variableTimezone || this.timezoneOffset) {
// For lower order time units, just set it directly using UTC
// time
if (unit === 'Milliseconds' ||
unit === 'Seconds' ||
unit === 'Minutes') {
return date['setUTC' + unit](value);
}
// Higher order time units need to take the time zone into
// account
// Adjust by timezone
var offset = this.getTimezoneOffset(date);
var ms = date.getTime() - offset;
date.setTime(ms);
date['setUTC' + unit](value);
var newOffset = this.getTimezoneOffset(date);
ms = date.getTime() + newOffset;
return date.setTime(ms);
}
// UTC time with no timezone handling
if (this.useUTC) {
return date['setUTC' + unit](value);
}
// Else, local time
return date['set' + unit](value);
};
/**
* Update the Time object with current options. It is called internally on
* initializing Highcharts, after running `Highcharts.setOptions` and on
* `Chart.update`.
*
* @private
* @function Highcharts.Time#update
*
* @param {Highcharts.TimeOptions} options
*
* @return {void}
*/
Time.prototype.update = function (options) {
var useUTC = pick(options && options.useUTC, true), time = this;
this.options = options = merge(true, this.options || {}, options);
// Allow using a different Date class
this.Date = options.Date || win.Date || Date;
this.useUTC = useUTC;
this.timezoneOffset = (useUTC && options.timezoneOffset);
this.getTimezoneOffset = this.timezoneOffsetFunction();
/*
* The time object has options allowing for variable time zones, meaning
* the axis ticks or series data needs to consider this.
*/
this.variableTimezone = !!(!useUTC ||
options.getTimezoneOffset ||
options.timezone);
};
/**
* Make a time and returns milliseconds. Interprets the inputs as UTC time,
* local time or a specific timezone time depending on the current time
* settings.
*
* @function Highcharts.Time#makeTime
*
* @param {number} year
* The year
*
* @param {number} month
* The month. Zero-based, so January is 0.
*
* @param {number} [date=1]
* The day of the month
*
* @param {number} [hours=0]
* The hour of the day, 0-23.
*
* @param {number} [minutes=0]
* The minutes
*
* @param {number} [seconds=0]
* The seconds
*
* @return {number}
* The time in milliseconds since January 1st 1970.
*/
Time.prototype.makeTime = function (year, month, date, hours, minutes, seconds) {
var d, offset, newOffset;
if (this.useUTC) {
d = this.Date.UTC.apply(0, arguments);
offset = this.getTimezoneOffset(d);
d += offset;
newOffset = this.getTimezoneOffset(d);
if (offset !== newOffset) {
d += newOffset - offset;
// A special case for transitioning from summer time to winter time.
// When the clock is set back, the same time is repeated twice, i.e.
// 02:30 am is repeated since the clock is set back from 3 am to
// 2 am. We need to make the same time as local Date does.
}
else if (offset - 36e5 === this.getTimezoneOffset(d - 36e5) &&
!H.isSafari) {
d -= 36e5;
}
}
else {
d = new this.Date(year, month, pick(date, 1), pick(hours, 0), pick(minutes, 0), pick(seconds, 0)).getTime();
}
return d;
};
/**
* Sets the getTimezoneOffset function. If the `timezone` option is set, a
* default getTimezoneOffset function with that timezone is returned. If
* a `getTimezoneOffset` option is defined, it is returned. If neither are
* specified, the function using the `timezoneOffset` option or 0 offset is
* returned.
*
* @private
* @function Highcharts.Time#timezoneOffsetFunction
*
* @return {Function}
* A getTimezoneOffset function
*/
Time.prototype.timezoneOffsetFunction = function () {
var time = this, options = this.options, moment = win.moment;
if (!this.useUTC) {
return function (timestamp) {
return new Date(timestamp.toString()).getTimezoneOffset() * 60000;
};
}
if (options.timezone) {
if (!moment) {
// getTimezoneOffset-function stays undefined because it depends
// on Moment.js
error(25);
}
else {
return function (timestamp) {
return -moment.tz(timestamp, options.timezone).utcOffset() * 60000;
};
}
}
// If not timezone is set, look for the getTimezoneOffset callback
if (this.useUTC && options.getTimezoneOffset) {
return function (timestamp) {
return options.getTimezoneOffset(timestamp.valueOf()) * 60000;
};
}
// Last, use the `timezoneOffset` option if set
return function () {
return (time.timezoneOffset || 0) * 60000;
};
};
/**
* Formats a JavaScript date timestamp (milliseconds since Jan 1st 1970)
* into a human readable date string. The available format keys are listed
* below. Additional formats can be given in the
* {@link Highcharts.dateFormats} hook.
*
* Supported format keys:
* - `%a`: Short weekday, like 'Mon'
* - `%A`: Long weekday, like 'Monday'
* - `%d`: Two digit day of the month, 01 to 31
* - `%e`: Day of the month, 1 through 31
* - `%w`: Day of the week, 0 through 6
* - `%b`: Short month, like 'Jan'
* - `%B`: Long month, like 'January'
* - `%m`: Two digit month number, 01 through 12
* - `%y`: Two digits year, like 09 for 2009
* - `%Y`: Four digits year, like 2009
* - `%H`: Two digits hours in 24h format, 00 through 23
* - `%k`: Hours in 24h format, 0 through 23
* - `%I`: Two digits hours in 12h format, 00 through 11
* - `%l`: Hours in 12h format, 1 through 12
* - `%M`: Two digits minutes, 00 through 59
* - `%p`: Upper case AM or PM
* - `%P`: Lower case AM or PM
* - `%S`: Two digits seconds, 00 through 59
* - `%L`: Milliseconds (naming from Ruby)
*
* @example
* const time = new Highcharts.Time();
* const s = time.dateFormat('%Y-%m-%d %H:%M:%S', Date.UTC(2020, 0, 1));
* console.log(s); // => 2020-01-01 00:00:00
*
* @function Highcharts.Time#dateFormat
*
* @param {string} format
* The desired format where various time representations are
* prefixed with %.
*
* @param {number} timestamp
* The JavaScript timestamp.
*
* @param {boolean} [capitalize=false]
* Upper case first letter in the return.
*
* @return {string}
* The formatted date.
*/
Time.prototype.dateFormat = function (format, timestamp, capitalize) {
var _a;
if (!defined(timestamp) || isNaN(timestamp)) {
return ((_a = H.defaultOptions.lang) === null || _a === void 0 ? void 0 : _a.invalidDate) || '';
}
format = pick(format, '%Y-%m-%d %H:%M:%S');
var time = this, date = new this.Date(timestamp),
// get the basic time values
hours = this.get('Hours', date), day = this.get('Day', date), dayOfMonth = this.get('Date', date), month = this.get('Month', date), fullYear = this.get('FullYear', date), lang = H.defaultOptions.lang, langWeekdays = lang === null || lang === void 0 ? void 0 : lang.weekdays, shortWeekdays = lang === null || lang === void 0 ? void 0 : lang.shortWeekdays,
// List all format keys. Custom formats can be added from the
// outside.
replacements = extend({
// Day
// Short weekday, like 'Mon'
a: shortWeekdays ?
shortWeekdays[day] :
langWeekdays[day].substr(0, 3),
// Long weekday, like 'Monday'
A: langWeekdays[day],
// Two digit day of the month, 01 to 31
d: pad(dayOfMonth),
// Day of the month, 1 through 31
e: pad(dayOfMonth, 2, ' '),
// Day of the week, 0 through 6
w: day,
// Week (none implemented)
// 'W': weekNumber(),
// Month
// Short month, like 'Jan'
b: lang.shortMonths[month],
// Long month, like 'January'
B: lang.months[month],
// Two digit month number, 01 through 12
m: pad(month + 1),
// Month number, 1 through 12 (#8150)
o: month + 1,
// Year
// Two digits year, like 09 for 2009
y: fullYear.toString().substr(2, 2),
// Four digits year, like 2009
Y: fullYear,
// Time
// Two digits hours in 24h format, 00 through 23
H: pad(hours),
// Hours in 24h format, 0 through 23
k: hours,
// Two digits hours in 12h format, 00 through 11
I: pad((hours % 12) || 12),
// Hours in 12h format, 1 through 12
l: (hours % 12) || 12,
// Two digits minutes, 00 through 59
M: pad(this.get('Minutes', date)),
// Upper case AM or PM
p: hours < 12 ? 'AM' : 'PM',
// Lower case AM or PM
P: hours < 12 ? 'am' : 'pm',
// Two digits seconds, 00 through 59
S: pad(date.getSeconds()),
// Milliseconds (naming from Ruby)
L: pad(Math.floor(timestamp % 1000), 3)
}, H.dateFormats);
// Do the replaces
objectEach(replacements, function (val, key) {
// Regex would do it in one line, but this is faster
while (format.indexOf('%' + key) !== -1) {
format = format.replace('%' + key, typeof val === 'function' ? val.call(time, timestamp) : val);
}
});
// Optionally capitalize the string and return
return capitalize ?
(format.substr(0, 1).toUpperCase() +
format.substr(1)) :
format;
};
/**
* Resolve legacy formats of dateTimeLabelFormats (strings and arrays) into
* an object.
* @private
* @param {string|Array<T>|Highcharts.Dictionary<T>} f - General format description
* @return {Highcharts.Dictionary<T>} - The object definition
*/
Time.prototype.resolveDTLFormat = function (f) {
if (!isObject(f, true)) { // check for string or array
f = splat(f);
return {
main: f[0],
from: f[1],
to: f[2]
};
}
return f;
};
/**
* Return an array with time positions distributed on round time values
* right and right after min and max. Used in datetime axes as well as for
* grouping data on a datetime axis.
*
* @function Highcharts.Time#getTimeTicks
*
* @param {Highcharts.TimeNormalizedObject} normalizedInterval
* The interval in axis values (ms) and the count
*
* @param {number} [min]
* The minimum in axis values
*
* @param {number} [max]
* The maximum in axis values
*
* @param {number} [startOfWeek=1]
*
* @return {Highcharts.AxisTickPositionsArray}
*/
Time.prototype.getTimeTicks = function (normalizedInterval, min, max, startOfWeek) {
var time = this, Date = time.Date, tickPositions = [], i, higherRanks = {}, minYear, // used in months and years as a basis for Date.UTC()
// When crossing DST, use the max. Resolves #6278.
minDate = new Date(min), interval = normalizedInterval.unitRange, count = normalizedInterval.count || 1, variableDayLength, minDay;
startOfWeek = pick(startOfWeek, 1);
if (defined(min)) { // #1300
time.set('Milliseconds', minDate, interval >= timeUnits.second ?
0 : // #3935
count * Math.floor(time.get('Milliseconds', minDate) / count)); // #3652, #3654
if (interval >= timeUnits.second) { // second
time.set('Seconds', minDate, interval >= timeUnits.minute ?
0 : // #3935
count * Math.floor(time.get('Seconds', minDate) / count));
}
if (interval >= timeUnits.minute) { // minute
time.set('Minutes', minDate, interval >= timeUnits.hour ?
0 :
count * Math.floor(time.get('Minutes', minDate) / count));
}
if (interval >= timeUnits.hour) { // hour
time.set('Hours', minDate, interval >= timeUnits.day ?
0 :
count * Math.floor(time.get('Hours', minDate) / count));
}
if (interval >= timeUnits.day) { // day
time.set('Date', minDate, interval >= timeUnits.month ?
1 :
Math.max(1, count * Math.floor(time.get('Date', minDate) / count)));
}
if (interval >= timeUnits.month) { // month
time.set('Month', minDate, interval >= timeUnits.year ? 0 :
count * Math.floor(time.get('Month', minDate) / count));
minYear = time.get('FullYear', minDate);
}
if (interval >= timeUnits.year) { // year
minYear -= minYear % count;
time.set('FullYear', minDate, minYear);
}
// week is a special case that runs outside the hierarchy
if (interval === timeUnits.week) {
// get start of current week, independent of count
minDay = time.get('Day', minDate);
time.set('Date', minDate, (time.get('Date', minDate) -
minDay + startOfWeek +
// We don't want to skip days that are before
// startOfWeek (#7051)
(minDay < startOfWeek ? -7 : 0)));
}
// Get basics for variable time spans
minYear = time.get('FullYear', minDate);
var minMonth = time.get('Month', minDate), minDateDate = time.get('Date', minDate), minHours = time.get('Hours', minDate);
// Redefine min to the floored/rounded minimum time (#7432)
min = minDate.getTime();
// Handle local timezone offset
if (time.variableTimezone) {
// Detect whether we need to take the DST crossover into
// consideration. If we're crossing over DST, the day length may
// be 23h or 25h and we need to compute the exact clock time for
// each tick instead of just adding hours. This comes at a cost,
// so first we find out if it is needed (#4951).
variableDayLength = (
// Long range, assume we're crossing over.
max - min > 4 * timeUnits.month ||
// Short range, check if min and max are in different time
// zones.
time.getTimezoneOffset(min) !==
time.getTimezoneOffset(max));
}
// Iterate and add tick positions at appropriate values
var t = minDate.getTime();
i = 1;
while (t < max) {
tickPositions.push(t);
// if the interval is years, use Date.UTC to increase years
if (interval === timeUnits.year) {
t = time.makeTime(minYear + i * count, 0);
// if the interval is months, use Date.UTC to increase months
}
else if (interval === timeUnits.month) {
t = time.makeTime(minYear, minMonth + i * count);
// if we're using global time, the interval is not fixed as it
// jumps one hour at the DST crossover
}
else if (variableDayLength &&
(interval === timeUnits.day || interval === timeUnits.week)) {
t = time.makeTime(minYear, minMonth, minDateDate +
i * count * (interval === timeUnits.day ? 1 : 7));
}
else if (variableDayLength &&
interval === timeUnits.hour &&
count > 1) {
// make sure higher ranks are preserved across DST (#6797,
// #7621)
t = time.makeTime(minYear, minMonth, minDateDate, minHours + i * count);
// else, the interval is fixed and we use simple addition
}
else {
t += interval * count;
}
i++;
}
// push the last time
tickPositions.push(t);
// Handle higher ranks. Mark new days if the time is on midnight
// (#950, #1649, #1760, #3349). Use a reasonable dropout threshold
// to prevent looping over dense data grouping (#6156).
if (interval <= timeUnits.hour && tickPositions.length < 10000) {
tickPositions.forEach(function (t) {
if (
// Speed optimization, no need to run dateFormat unless
// we're on a full or half hour
t % 1800000 === 0 &&
// Check for local or global midnight
time.dateFormat('%H%M%S%L', t) === '000000000') {
higherRanks[t] = 'day';
}
});
}
}
// record information on the chosen unit - for dynamic label formatter
tickPositions.info = extend(normalizedInterval, {
higherRanks: higherRanks,
totalRange: interval * count
});
return tickPositions;
};
/* *
*
* Static Properties
*
* */
/**
* Time options that can apply globally or to individual charts. These
* settings affect how `datetime` axes are laid out, how tooltips are
* formatted, how series
* [pointIntervalUnit](#plotOptions.series.pointIntervalUnit) works and how
* the Highstock range selector handles time.
*
* The common use case is that all charts in the same Highcharts object
* share the same time settings, in which case the global settings are set
* using `setOptions`.
*
* ```js
* // Apply time settings globally
* Highcharts.setOptions({
* time: {
* timezone: 'Europe/London'
* }
* });
* // Apply time settings by instance
* var chart = Highcharts.chart('container', {
* time: {
* timezone: 'America/New_York'
* },
* series: [{
* data: [1, 4, 3, 5]
* }]
* });
*
* // Use the Time object
* console.log(
* 'Current time in New York',
* chart.time.dateFormat('%Y-%m-%d %H:%M:%S', Date.now())
* );
* ```
*
* Since v6.0.5, the time options were moved from the `global` obect to the
* `time` object, and time options can be set on each individual chart.
*
* @sample {highcharts|highstock}
* highcharts/time/timezone/
* Set the timezone globally
* @sample {highcharts}
* highcharts/time/individual/
* Set the timezone per chart instance
* @sample {highstock}
* stock/time/individual/
* Set the timezone per chart instance
*
* @since 6.0.5
* @optionparent time
*/
Time.defaultOptions = {
/**
* A custom `Date` class for advanced date handling. For example,
* [JDate](https://github.com/tahajahangir/jdate) can be hooked in to
* handle Jalali dates.
*
* @type {*}
* @since 4.0.4
* @product highcharts highstock gantt
*/
Date: void 0,
/**
* A callback to return the time zone offset for a given datetime. It
* takes the timestamp in terms of milliseconds since January 1 1970,
* and returns the timezone offset in minutes. This provides a hook
* for drawing time based charts in specific time zones using their
* local DST crossover dates, with the help of external libraries.
*
* @see [global.timezoneOffset](#global.timezoneOffset)
*
* @sample {highcharts|highstock} highcharts/time/gettimezoneoffset/
* Use moment.js to draw Oslo time regardless of browser locale
*
* @type {Highcharts.TimezoneOffsetCallbackFunction}
* @since 4.1.0
* @product highcharts highstock gantt
*/
getTimezoneOffset: void 0,
/**
* Requires [moment.js](https://momentjs.com/). If the timezone option
* is specified, it creates a default
* [getTimezoneOffset](#time.getTimezoneOffset) function that looks
* up the specified timezone in moment.js. If moment.js is not included,
* this throws a Highcharts error in the console, but does not crash the
* chart.
*
* @see [getTimezoneOffset](#time.getTimezoneOffset)
*
* @sample {highcharts|highstock} highcharts/time/timezone/
* Europe/Oslo
*
* @type {string}
* @since 5.0.7
* @product highcharts highstock gantt
*/
timezone: void 0,
/**
* The timezone offset in minutes. Positive values are west, negative
* values are east of UTC, as in the ECMAScript
* [getTimezoneOffset](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset)
* method. Use this to display UTC based data in a predefined time zone.
*
* @see [time.getTimezoneOffset](#time.getTimezoneOffset)
*
* @sample {highcharts|highstock} highcharts/time/timezoneoffset/
* Timezone offset
*
* @since 3.0.8
* @product highcharts highstock gantt
*/
timezoneOffset: 0,
/**
* Whether to use UTC time for axis scaling, tickmark placement and
* time display in `Highcharts.dateFormat`. Advantages of using UTC
* is that the time displays equally regardless of the user agent's
* time zone settings. Local time can be used when the data is loaded
* in real time or when correct Daylight Saving Time transitions are
* required.
*
* @sample {highcharts} highcharts/time/useutc-true/
* True by default
* @sample {highcharts} highcharts/time/useutc-false/
* False
*/
useUTC: true
};
return Time;
}());
H.Time = Time;
export default H.Time;

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff