devextreme
Version:
JavaScript/TypeScript Component Suite for Responsive Web Development
2,493 lines • 110 kB
JavaScript
/**
* DevExtreme (cjs/__internal/viz/axes/base_axis.js)
* Version: 26.1.6
* Build date: Fri Oct 16 2026
*
* Copyright (c) 2012 - 2026 Developer Express Inc. ALL RIGHTS RESERVED
* Read about DevExtreme licensing here: https://js.devexpress.com/Licensing/
*/
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Axis = void 0;
var _format_helper = _interopRequireDefault(require("../../core/format_helper"));
var _deferred = require("../../core/utils/deferred");
var _m_common = require("../../core/utils/m_common");
var _m_date = require("../../core/utils/m_date");
var _m_extend = require("../../core/utils/m_extend");
var _m_math = require("../../core/utils/m_math");
var _m_type = require("../../core/utils/m_type");
var _axes_constants = _interopRequireDefault(require("../../viz/axes/axes_constants"));
var _axes_utils = require("../../viz/axes/axes_utils");
var _constant_line = _interopRequireDefault(require("../../viz/axes/constant_line"));
var polarMethods = _interopRequireWildcard(require("../../viz/axes/polar_axes"));
var _smart_formatter = require("../../viz/axes/smart_formatter");
var _strip = _interopRequireDefault(require("../../viz/axes/strip"));
var _tick = require("../../viz/axes/tick");
var _tick_generator = require("../../viz/axes/tick_generator");
var _xy_axes = _interopRequireDefault(require("../../viz/axes/xy_axes"));
var _parse_utils = require("../../viz/components/parse_utils");
var _utils = require("../core/utils");
var _range = require("../translators/range");
var _translator2d = require("../translators/translator2d");
function _interopRequireWildcard(e, t) {
if ("function" == typeof WeakMap) {
var r = new WeakMap,
n = new WeakMap
}
return (_interopRequireWildcard = function(e, t) {
if (!t && e && e.__esModule) {
return e
}
var o, i, f = {
__proto__: null,
default: e
};
if (null === e || "object" != typeof e && "function" != typeof e) {
return f
}
if (o = t ? n : r) {
if (o.has(e)) {
return o.get(e)
}
o.set(e, f)
}
for (const t in e) {
"default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t])
}
return f
})(e, t)
}
function _interopRequireDefault(e) {
return e && e.__esModule ? e : {
default: e
}
}
const convertTicksToValues = _axes_constants.default.convertTicksToValues;
const _math = Math;
const _abs = _math.abs;
const _max = _math.max;
const _min = _math.min;
const _isArray = Array.isArray;
const DEFAULT_AXIS_LABEL_SPACING = 5;
const MAX_GRID_BORDER_ADHENSION = 4;
const PANNING_CORRECTION_ITERATION_COUNT = 5;
const PANNING_CORRECTION_PRECISION = 1e-4;
const ZOOM_FACTOR_PRECISION = 2;
const ZOOM_FACTOR_MULTIPLIER = 100;
const TOP = _axes_constants.default.top;
const BOTTOM = _axes_constants.default.bottom;
const LEFT = _axes_constants.default.left;
const RIGHT = _axes_constants.default.right;
const CENTER = _axes_constants.default.center;
const KEEP = "keep";
const SHIFT = "shift";
const RESET = "reset";
const ROTATE = "rotate";
const DEFAULT_AXIS_DIVISION_FACTOR = 50;
const DEFAULT_MINOR_AXIS_DIVISION_FACTOR = 15;
const SCROLL_THRESHOLD = 5;
const MIN_BAR_MARGIN = 5;
const MAX_MARGIN_VALUE = .8;
const dateIntervals = {
day: 864e5,
week: 6048e5
};
function getTickGenerator(options, incidentOccurred, skipTickGeneration, rangeIsEmpty, adjustDivisionFactor, _ref) {
var _options$workWeek;
let {
allowNegatives: allowNegatives,
linearThreshold: linearThreshold
} = _ref;
return (0, _tick_generator.tickGenerator)({
axisType: options.type,
dataType: options.dataType,
logBase: options.logarithmBase,
allowNegatives: allowNegatives,
linearThreshold: linearThreshold,
axisDivisionFactor: adjustDivisionFactor(options.axisDivisionFactor || 50),
minorAxisDivisionFactor: adjustDivisionFactor(options.minorAxisDivisionFactor || 15),
numberMultipliers: options.numberMultipliers,
calculateMinors: options.minorTick.visible || options.minorGrid.visible || options.calculateMinors,
allowDecimals: options.allowDecimals,
endOnTick: options.endOnTick,
incidentOccurred: incidentOccurred,
firstDayOfWeek: null === (_options$workWeek = options.workWeek) || void 0 === _options$workWeek ? void 0 : _options$workWeek[0],
skipTickGeneration: skipTickGeneration,
skipCalculationLimits: options.skipCalculationLimits,
generateExtraTick: options.generateExtraTick,
minTickInterval: options.minTickInterval,
rangeIsEmpty: rangeIsEmpty
})
}
function createMajorTick(axis, renderer, skippedCategory) {
const options = axis.getOptions();
return (0, _tick.tick)(axis, renderer, options.tick, options.grid, skippedCategory, false)
}
function createMinorTick(axis, renderer) {
const options = axis.getOptions();
return (0, _tick.tick)(axis, renderer, options.minorTick, options.minorGrid)
}
function createBoundaryTick(axis, renderer, isFirst) {
const options = axis.getOptions();
return (0, _tick.tick)(axis, renderer, (0, _m_extend.extend)({}, options.tick, {
visible: options.showCustomBoundaryTicks
}), options.grid, void 0, false, isFirst ? -1 : 1)
}
function callAction(elements, action, actionArgument1, actionArgument2) {
(elements || []).forEach(e => e[action](actionArgument1, actionArgument2))
}
function initTickCoords(ticks) {
callAction(ticks, "initCoords")
}
function drawTickMarks(ticks, options) {
callAction(ticks, "drawMark", options)
}
function drawGrids(ticks, drawLine) {
callAction(ticks, "drawGrid", drawLine)
}
function updateTicksPosition(ticks, options, animate) {
callAction(ticks, "updateTickPosition", options, animate)
}
function updateGridsPosition(ticks, animate) {
callAction(ticks, "updateGridPosition", animate)
}
function cleanUpInvalidTicks(ticks) {
let i = ticks.length - 1;
for (i; i >= 0; i--) {
if (!removeInvalidTick(ticks, i)) {
break
}
}
for (i = 0; i < ticks.length; i++) {
if (removeInvalidTick(ticks, i)) {
i--
} else {
break
}
}
}
function removeInvalidTick(ticks, i) {
if (null === ticks[i].coords.x || null === ticks[i].coords.y) {
ticks.splice(i, 1);
return true
}
return false
}
function validateAxisOptions(options) {
const labelOptions = options.label;
let position = options.position;
const defaultPosition = options.isHorizontal ? BOTTOM : LEFT;
const secondaryPosition = options.isHorizontal ? TOP : RIGHT;
let labelPosition = labelOptions.position;
if (position !== defaultPosition && position !== secondaryPosition) {
position = defaultPosition
}
if (!labelPosition || "outside" === labelPosition) {
labelPosition = position
} else if ("inside" === labelPosition) {
labelPosition = {
[TOP]: BOTTOM,
[BOTTOM]: TOP,
[LEFT]: RIGHT,
[RIGHT]: LEFT
} [position]
}
if (labelPosition !== defaultPosition && labelPosition !== secondaryPosition) {
labelPosition = position
}
if (labelOptions.alignment !== CENTER && !labelOptions.userAlignment) {
labelOptions.alignment = {
[TOP]: CENTER,
[BOTTOM]: CENTER,
[LEFT]: RIGHT,
[RIGHT]: LEFT
} [labelPosition]
}
options.position = position;
labelOptions.position = labelPosition;
options.hoverMode = options.hoverMode ? options.hoverMode.toLowerCase() : "none";
labelOptions.minSpacing = labelOptions.minSpacing ?? 5;
options.type && (options.type = options.type.toLowerCase());
options.argumentType && (options.argumentType = options.argumentType.toLowerCase());
options.valueType && (options.valueType = options.valueType.toLowerCase())
}
function getOptimalAngle(boxes, labelOpt) {
const angle = 180 * _math.asin((boxes[0].height + labelOpt.minSpacing) / (boxes[1].x - boxes[0].x)) / _math.PI;
return angle < 45 ? -45 : -90
}
function updateLabels(ticks, step, func) {
ticks.forEach((tick, index) => {
if (tick.getContentContainer()) {
if (index % step !== 0) {
tick.removeLabel()
} else if (func) {
func(tick, index)
}
}
})
}
function getZoomBoundValue(optionValue, dataValue) {
if (void 0 === optionValue) {
return dataValue
} else if (null === optionValue) {
return
} else {
return optionValue
}
}
function configureGenerator(options, axisDivisionFactor, viewPort, screenDelta, minTickInterval) {
const tickGeneratorOptions = (0, _m_extend.extend)({}, options, {
endOnTick: true,
axisDivisionFactor: axisDivisionFactor,
skipCalculationLimits: true,
generateExtraTick: true,
minTickInterval: minTickInterval
});
return function(tickInterval, skipTickGeneration, min, max, breaks) {
return getTickGenerator(tickGeneratorOptions, _m_common.noop, skipTickGeneration, viewPort.isEmpty(), v => v, viewPort)({
min: min,
max: max,
categories: viewPort.categories,
isSpacedMargin: viewPort.isSpacedMargin
}, screenDelta, tickInterval, (0, _m_type.isDefined)(tickInterval), void 0, void 0, void 0, breaks)
}
}
function getConstantLineSharpDirection(coord, axisCanvas) {
return Math.max(axisCanvas.start, axisCanvas.end) !== coord ? 1 : -1
}
let Axis = exports.Axis = class {
constructor(renderSettings) {
this._renderer = renderSettings.renderer;
this._incidentOccurred = renderSettings.incidentOccurred;
this._eventTrigger = renderSettings.eventTrigger;
this._stripsGroup = renderSettings.stripsGroup;
this._stripLabelAxesGroup = renderSettings.stripLabelAxesGroup;
this._labelsAxesGroup = renderSettings.labelsAxesGroup;
this._constantLinesGroup = renderSettings.constantLinesGroup;
this._scaleBreaksGroup = renderSettings.scaleBreaksGroup;
this._axesContainerGroup = renderSettings.axesContainerGroup;
this._gridContainerGroup = renderSettings.gridGroup;
this._axisCssPrefix = `${renderSettings.widgetClass}-${renderSettings.axisClass?`${renderSettings.axisClass}-`:""}`;
this._setType(renderSettings.axisType, renderSettings.drawingType);
this._createAxisGroups();
this._translator = this._createTranslator();
this.isArgumentAxis = renderSettings.isArgumentAxis;
this._viewport = {};
this._prevDataInfo = {};
this._firstDrawing = true;
this._initRange = {};
this._getTemplate = renderSettings.getTemplate
}
_drawAxis() {
const options = this._options;
if (!options.visible) {
return
}
this._axisElement = this._createAxisElement();
this._updateAxisElementPosition();
this._axisElement.attr({
"stroke-width": options.width,
stroke: options.color,
"stroke-opacity": options.opacity
}).sharp(this._getSharpParam(true), this.getAxisSharpDirection()).append(this._axisLineGroup)
}
_createPathElement(points, attr, sharpDirection) {
return this.sharp(this._renderer.path(points, "line").attr(attr), sharpDirection)
}
sharp(svgElement) {
let sharpDirection = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 1;
return svgElement.sharp(this._getSharpParam(), sharpDirection)
}
customPositionIsAvailable() {
return false
}
hasNonBoundaryPosition() {
return false
}
customPositionIsBoundaryOrthogonalAxis() {
return false
}
getResolvedBoundaryPosition() {
return this.getOptions().position
}
getAxisSharpDirection() {
const position = this.getResolvedBoundaryPosition();
return this.hasNonBoundaryPosition() || position !== BOTTOM && position !== RIGHT ? 1 : -1
}
getSharpDirectionByCoords(coords) {
const canvas = this._getCanvasStartEnd();
const maxCoord = Math.max(canvas.start, canvas.end);
return this.getRadius ? 0 : maxCoord !== coords[this._isHorizontal ? "x" : "y"] ? 1 : -1
}
_getGridLineDrawer() {
const that = this;
return function(tick, gridStyle) {
const grid = that._getGridPoints(tick.coords);
if (grid.points) {
return that._createPathElement(grid.points, gridStyle, that.getSharpDirectionByCoords(tick.coords))
}
return null
}
}
_getGridPoints(coords) {
const isHorizontal = this._isHorizontal;
const tickPositionField = isHorizontal ? "x" : "y";
const orthogonalPositions = this._orthogonalPositions;
const positionFrom = orthogonalPositions.start;
const positionTo = orthogonalPositions.end;
const borderOptions = this.borderOptions;
const canvasStart = isHorizontal ? LEFT : TOP;
const canvasEnd = isHorizontal ? RIGHT : BOTTOM;
const axisCanvas = this.getCanvas();
const canvas = {
left: axisCanvas.left,
right: axisCanvas.width - axisCanvas.right,
top: axisCanvas.top,
bottom: axisCanvas.height - axisCanvas.bottom
};
const firstBorderLinePosition = borderOptions.visible && borderOptions[canvasStart] ? canvas[canvasStart] : void 0;
const lastBorderLinePosition = borderOptions.visible && borderOptions[canvasEnd] ? canvas[canvasEnd] : void 0;
const minDelta = 4 + firstBorderLinePosition;
const maxDelta = lastBorderLinePosition - 4;
if (this.areCoordsOutsideAxis(coords) || void 0 === coords[tickPositionField] || coords[tickPositionField] < minDelta || coords[tickPositionField] > maxDelta) {
return {
points: null
}
}
return {
points: isHorizontal ? null !== coords[tickPositionField] ? [coords[tickPositionField], positionFrom, coords[tickPositionField], positionTo] : null : null !== coords[tickPositionField] ? [positionFrom, coords[tickPositionField], positionTo, coords[tickPositionField]] : null
}
}
_getConstantLinePos(parsedValue, canvasStart, canvasEnd) {
const value = this._getTranslatedCoord(parsedValue);
if (!(0, _m_type.isDefined)(value) || value < _min(canvasStart, canvasEnd) || value > _max(canvasStart, canvasEnd)) {
return
}
return value
}
_getConstantLineGraphicAttributes(value) {
const positionFrom = this._orthogonalPositions.start;
const positionTo = this._orthogonalPositions.end;
return {
points: this._isHorizontal ? [value, positionFrom, value, positionTo] : [positionFrom, value, positionTo, value]
}
}
_createConstantLine(value, attr) {
return this._createPathElement(this._getConstantLineGraphicAttributes(value).points, attr, getConstantLineSharpDirection(value, this._getCanvasStartEnd()))
}
_drawConstantLineLabelText(text, x, y, _ref2, group) {
let {
font: font,
cssClass: cssClass
} = _ref2;
return this._renderer.text(text, x, y).css((0, _utils.patchFontOptions)((0, _m_extend.extend)({}, this._options.label.font, font))).attr({
align: "center",
class: cssClass
}).append(group)
}
_drawConstantLineLabels(parsedValue, lineLabelOptions, value, group) {
let text = lineLabelOptions.text;
const options = this._options;
const labelOptions = options.label;
this._checkAlignmentConstantLineLabels(lineLabelOptions);
text = text ?? this.formatLabel(parsedValue, labelOptions);
const coords = this._getConstantLineLabelsCoords(value, lineLabelOptions);
return this._drawConstantLineLabelText(text, coords.x, coords.y, lineLabelOptions, group)
}
_getStripPos(startValue, endValue, canvasStart, canvasEnd, range) {
const isContinuous = !!(range.minVisible || range.maxVisible);
const categories = (range.categories || []).reduce((result, cat) => {
result.push(cat.valueOf());
return result
}, []);
let start;
let end;
let swap;
let startCategoryIndex;
let endCategoryIndex;
if (!isContinuous) {
if ((0, _m_type.isDefined)(startValue) && (0, _m_type.isDefined)(endValue)) {
const parsedStartValue = this.parser(startValue);
const parsedEndValue = this.parser(endValue);
startCategoryIndex = categories.indexOf((null === parsedStartValue || void 0 === parsedStartValue ? void 0 : parsedStartValue.valueOf()) ?? void 0);
endCategoryIndex = categories.indexOf((null === parsedEndValue || void 0 === parsedEndValue ? void 0 : parsedEndValue.valueOf()) ?? void 0);
if (-1 === startCategoryIndex || -1 === endCategoryIndex) {
return {
from: 0,
to: 0,
outOfCanvas: true
}
}
if (startCategoryIndex > endCategoryIndex) {
swap = endValue;
endValue = startValue;
startValue = swap
}
}
}
if ((0, _m_type.isDefined)(startValue)) {
startValue = this.validateUnit(startValue, "E2105", "strip");
start = this._getTranslatedCoord(startValue, -1)
} else {
start = canvasStart
}
if ((0, _m_type.isDefined)(endValue)) {
endValue = this.validateUnit(endValue, "E2105", "strip");
end = this._getTranslatedCoord(endValue, 1)
} else {
end = canvasEnd
}
const stripPosition = start < end ? {
from: start,
to: end
} : {
from: end,
to: start
};
const visibleArea = this.getVisibleArea();
if (stripPosition.from <= visibleArea[0] && stripPosition.to <= visibleArea[0] || stripPosition.from >= visibleArea[1] && stripPosition.to >= visibleArea[1]) {
stripPosition.outOfCanvas = true
}
return stripPosition
}
_getStripGraphicAttributes(fromPoint, toPoint) {
let x;
let y;
let width;
let height;
const orthogonalPositions = this._orthogonalPositions;
const positionFrom = orthogonalPositions.start;
const positionTo = orthogonalPositions.end;
if (this._isHorizontal) {
x = fromPoint;
y = _min(positionFrom, positionTo);
width = toPoint - fromPoint;
height = _abs(positionFrom - positionTo)
} else {
x = _min(positionFrom, positionTo);
y = fromPoint;
width = _abs(positionFrom - positionTo);
height = _abs(fromPoint - toPoint)
}
return {
x: x,
y: y,
width: width,
height: height
}
}
_createStrip(attrs) {
return this._renderer.rect(attrs.x, attrs.y, attrs.width, attrs.height)
}
_adjustStripLabels() {
this._strips.forEach(strip => {
if (strip.label) {
strip.label.attr(this._getAdjustedStripLabelCoords(strip))
}
})
}
_adjustLabelsCoord(offset, maxWidth, checkCanvas) {
const getContainerAttrs = tick => this._getLabelAdjustedCoord(tick, offset + (tick.labelOffset || 0), maxWidth, checkCanvas);
this._majorTicks.forEach(tick => {
if (tick.label) {
tick.updateMultilineTextAlignment();
tick.label.attr(getContainerAttrs(tick))
} else {
tick.templateContainer && tick.templateContainer.attr(getContainerAttrs(tick))
}
})
}
_adjustLabels(offset) {
const options = this.getOptions();
const positionsAreConsistent = options.position === options.label.position;
const maxSize = this._majorTicks.reduce((size, tick) => {
if (!tick.getContentContainer()) {
return size
}
const bBox = tick.labelRotationAngle ? (0, _utils.rotateBBox)(tick.labelBBox, [tick.labelCoords.x, tick.labelCoords.y], -tick.labelRotationAngle) : tick.labelBBox;
return {
width: _max(size.width || 0, bBox.width),
height: _max(size.height || 0, bBox.height),
offset: _max(size.offset || 0, tick.labelOffset || 0)
}
}, {});
const additionalOffset = positionsAreConsistent ? this._isHorizontal ? maxSize.height : maxSize.width : 0;
this._adjustLabelsCoord(offset, maxSize.width);
return offset + additionalOffset + (additionalOffset && this._options.label.indentFromAxis) + (positionsAreConsistent ? maxSize.offset : 0)
}
_getLabelAdjustedCoord(tick, offset, maxWidth) {
offset = offset || 0;
const options = this._options;
const templateBox = tick.templateContainer && tick.templateContainer.getBBox();
const box = templateBox || (0, _utils.rotateBBox)(tick.labelBBox, [tick.labelCoords.x, tick.labelCoords.y], -tick.labelRotationAngle || 0);
const textAlign = tick.labelAlignment || options.label.alignment;
const isDiscrete = "discrete" === this._options.type;
const isFlatLabel = tick.labelRotationAngle % 90 === 0;
const indentFromAxis = options.label.indentFromAxis;
const labelPosition = options.label.position;
const axisPosition = this._axisPosition;
const labelCoords = tick.labelCoords;
const labelX = labelCoords.x;
let translateX;
let translateY;
if (this._isHorizontal) {
if (labelPosition === BOTTOM) {
translateY = axisPosition + indentFromAxis - box.y + offset
} else {
translateY = axisPosition - indentFromAxis - (box.y + box.height) - offset
}
if (textAlign === RIGHT) {
translateX = isDiscrete && isFlatLabel ? tick.coords.x - (box.x + box.width) : labelX - box.x - box.width
} else if (textAlign === LEFT) {
translateX = isDiscrete && isFlatLabel ? labelX - box.x - (tick.coords.x - labelX) : labelX - box.x
} else {
translateX = labelX - box.x - box.width / 2
}
} else {
translateY = labelCoords.y - box.y - box.height / 2;
if (labelPosition === LEFT) {
if (textAlign === LEFT) {
translateX = axisPosition - indentFromAxis - maxWidth - box.x
} else if (textAlign === CENTER) {
translateX = axisPosition - indentFromAxis - maxWidth / 2 - box.x - box.width / 2
} else {
translateX = axisPosition - indentFromAxis - box.x - box.width
}
translateX -= offset
} else {
if (textAlign === RIGHT) {
translateX = axisPosition + indentFromAxis + maxWidth - box.x - box.width
} else if (textAlign === CENTER) {
translateX = axisPosition + indentFromAxis + maxWidth / 2 - box.x - box.width / 2
} else {
translateX = axisPosition + indentFromAxis - box.x
}
translateX += offset
}
}
return {
translateX: translateX,
translateY: translateY
}
}
_createAxisConstantLineGroups() {
const renderer = this._renderer;
const classSelector = this._axisCssPrefix;
const constantLinesClass = `${classSelector}constant-lines`;
const insideGroup = renderer.g().attr({
class: constantLinesClass
});
const outsideGroup1 = renderer.g().attr({
class: constantLinesClass
});
const outsideGroup2 = renderer.g().attr({
class: constantLinesClass
});
return {
inside: insideGroup,
outside1: outsideGroup1,
left: outsideGroup1,
top: outsideGroup1,
outside2: outsideGroup2,
right: outsideGroup2,
bottom: outsideGroup2,
remove() {
this.inside.remove();
this.outside1.remove();
this.outside2.remove()
},
clear() {
this.inside.clear();
this.outside1.clear();
this.outside2.clear()
}
}
}
_createAxisGroups() {
const renderer = this._renderer;
const classSelector = this._axisCssPrefix;
this._axisGroup = renderer.g().attr({
class: `${classSelector}axis`
}).enableLinks();
this._axisStripGroup = renderer.g().attr({
class: `${classSelector}strips`
});
this._axisGridGroup = renderer.g().attr({
class: `${classSelector}grid`
});
this._axisElementsGroup = renderer.g().attr({
class: `${classSelector}elements`
});
this._axisLineGroup = renderer.g().attr({
class: `${classSelector}line`
}).linkOn(this._axisGroup, "axisLine").linkAppend();
this._axisTitleGroup = renderer.g().attr({
class: `${classSelector}title`
}).append(this._axisGroup);
this._axisConstantLineGroups = {
above: this._createAxisConstantLineGroups(),
under: this._createAxisConstantLineGroups()
};
this._axisStripLabelGroup = renderer.g().attr({
class: `${classSelector}axis-labels`
})
}
_clearAxisGroups() {
this._axisGroup.remove();
this._axisStripGroup.remove();
this._axisStripLabelGroup.remove();
this._axisConstantLineGroups.above.remove();
this._axisConstantLineGroups.under.remove();
this._axisGridGroup.remove();
this._axisTitleGroup.clear();
if (!this._options.label.template || !this.isRendered()) {
this._axisElementsGroup.remove();
this._axisElementsGroup.clear()
}
this._axisLineGroup && this._axisLineGroup.clear();
this._axisStripGroup && this._axisStripGroup.clear();
this._axisGridGroup && this._axisGridGroup.clear();
this._axisConstantLineGroups.above.clear();
this._axisConstantLineGroups.under.clear();
this._axisStripLabelGroup && this._axisStripLabelGroup.clear()
}
_getLabelFormatObject(value, labelOptions, range, point, tickInterval, ticks) {
range = range || this._getViewportRange();
const formatObject = {
value: value,
valueText: (0, _smart_formatter.smartFormatter)(value, {
labelOptions: labelOptions,
ticks: ticks || convertTicksToValues(this._majorTicks),
tickInterval: tickInterval ?? this._tickInterval,
dataType: this._options.dataType,
logarithmBase: this._options.logarithmBase,
type: this._options.type,
showTransition: !this._options.marker.visible,
point: point
}) || "",
min: range.minVisible,
max: range.maxVisible
};
if (point) {
formatObject.point = point
}
return formatObject
}
formatLabel(value, labelOptions, range, point, tickInterval, ticks) {
const formatObject = this._getLabelFormatObject(value, labelOptions, range, point, tickInterval, ticks);
return (0, _m_type.isFunction)(labelOptions.customizeText) ? labelOptions.customizeText.call(formatObject, formatObject) : formatObject.valueText
}
formatHint(value, labelOptions, range) {
const formatObject = this._getLabelFormatObject(value, labelOptions, range);
return (0, _m_type.isFunction)(labelOptions.customizeHint) ? labelOptions.customizeHint.call(formatObject, formatObject) : void 0
}
formatRange(startValue, endValue, interval, argumentFormat) {
return (0, _smart_formatter.formatRange)({
startValue: startValue,
endValue: endValue,
tickInterval: interval,
argumentFormat: argumentFormat,
axisOptions: this.getOptions()
})
}
_setTickOffset() {
const options = this._options;
const discreteAxisDivisionMode = options.discreteAxisDivisionMode;
this._tickOffset = +("crossLabels" !== discreteAxisDivisionMode || !discreteAxisDivisionMode)
}
aggregatedPointBetweenTicks() {
return "crossTicks" === this._options.aggregatedPointsPosition
}
resetApplyingAnimation(isFirstDrawing) {
this._resetApplyingAnimation = true;
if (isFirstDrawing) {
this._firstDrawing = true
}
}
isFirstDrawing() {
return this._firstDrawing
}
getMargins() {
const that = this;
const {
position: position,
offset: offset,
customPosition: customPosition,
placeholderSize: placeholderSize,
grid: grid,
tick: tick,
crosshairMargin: crosshairMargin
} = that._options;
const isDefinedCustomPositionOption = (0, _m_type.isDefined)(customPosition);
const boundaryPosition = that.getResolvedBoundaryPosition();
const canvas = that.getCanvas();
const cLeft = canvas.left;
const cTop = canvas.top;
const cRight = canvas.width - canvas.right;
const cBottom = canvas.height - canvas.bottom;
const edgeMarginCorrection = _max(grid.visible && grid.width || 0, tick.visible && tick.width || 0);
const constantLineAboveSeries = that._axisConstantLineGroups.above;
const constantLineUnderSeries = that._axisConstantLineGroups.under;
const boxes = [that._axisElementsGroup, constantLineAboveSeries.outside1, constantLineAboveSeries.outside2, constantLineUnderSeries.outside1, constantLineUnderSeries.outside2, that._axisLineGroup].map(group => group && group.getBBox()).concat(function(group) {
const box = group && group.getBBox();
if (!box || box.isEmpty) {
return box
}
if (that._isHorizontal) {
box.x = cLeft;
box.width = cRight - cLeft
} else {
box.y = cTop;
box.height = cBottom - cTop
}
return box
}(that._axisTitleGroup));
const margins = (0, _axes_utils.calculateCanvasMargins)(boxes, canvas);
margins[position] += crosshairMargin;
if (that.hasNonBoundaryPosition() && isDefinedCustomPositionOption) {
margins[boundaryPosition] = 0
}
if (placeholderSize) {
margins[position] = placeholderSize
}
if (edgeMarginCorrection) {
if (that._isHorizontal && canvas.right < edgeMarginCorrection && margins.right < edgeMarginCorrection) {
margins.right = edgeMarginCorrection
}
if (!that._isHorizontal && canvas.bottom < edgeMarginCorrection && margins.bottom < edgeMarginCorrection) {
margins.bottom = edgeMarginCorrection
}
}
if (!isDefinedCustomPositionOption && (0, _m_type.isDefined)(offset)) {
const moveByOffset = that.customPositionIsBoundary() && (offset > 0 && (boundaryPosition === LEFT || boundaryPosition === TOP) || offset < 0 && (boundaryPosition === RIGHT || boundaryPosition === BOTTOM));
margins[boundaryPosition] -= moveByOffset ? offset : 0
}
return margins
}
validateUnit(unit, idError, parameters) {
unit = this.parser(unit);
if (void 0 === unit && idError) {
this._incidentOccurred(idError, [parameters])
}
return unit
}
_setType(axisType, drawingType) {
let axisTypeMethods;
switch (axisType) {
case "xyAxes":
axisTypeMethods = _xy_axes.default;
break;
case "polarAxes":
axisTypeMethods = polarMethods
}(0, _m_extend.extend)(this, axisTypeMethods[drawingType])
}
_getSharpParam() {
return true
}
dispose() {
[this._axisElementsGroup, this._axisStripGroup, this._axisGroup].forEach(g => {
g.dispose()
});
this._strips = this._title = null;
this._axisStripGroup = this._axisConstantLineGroups = this._axisStripLabelGroup = this._axisBreaksGroup = null;
this._axisLineGroup = this._axisElementsGroup = this._axisGridGroup = null;
this._axisGroup = this._axisTitleGroup = null;
this._axesContainerGroup = this._stripsGroup = this._constantLinesGroup = this._labelsAxesGroup = null;
this._renderer = this._options = this._textOptions = this._textFontStyles = null;
this._translator = null;
this._majorTicks = this._minorTicks = null;
this._disposeBreaksGroup();
this._templatesRendered && this._templatesRendered.reject()
}
getOptions() {
return this._options
}
setPane(pane) {
this.pane = pane;
this._options.pane = pane
}
setTypes(type, axisType, typeSelector) {
this._options.type = type || this._options.type;
this._options[typeSelector] = axisType || this._options[typeSelector];
this._updateTranslator()
}
resetTypes(typeSelector) {
this._options.type = this._initTypes.type;
this._options[typeSelector] = this._initTypes[typeSelector]
}
getTranslator() {
return this._translator
}
updateOptions(options) {
const labelOpt = options.label;
validateAxisOptions(options);
this._options = options;
options.tick = options.tick || {};
options.minorTick = options.minorTick || {};
options.grid = options.grid || {};
options.minorGrid = options.minorGrid || {};
options.title = options.title || {};
options.marker = options.marker || {};
this._initTypes = {
type: options.type,
argumentType: options.argumentType,
valueType: options.valueType
};
this._setTickOffset();
this._isHorizontal = options.isHorizontal;
this.pane = options.pane ?? this.pane;
this.name = options.name;
this.priority = options.priority;
this._hasLabelFormat = "" !== labelOpt.format && (0, _m_type.isDefined)(labelOpt.format);
this._textOptions = {
opacity: labelOpt.opacity,
align: "center",
class: labelOpt.cssClass
};
this._textFontStyles = (0, _utils.patchFontOptions)(labelOpt.font);
if (options.type === _axes_constants.default.logarithmic) {
if (options.logarithmBaseError) {
this._incidentOccurred("E2104");
delete options.logarithmBaseError
}
}
this._updateTranslator();
this._createConstantLines();
this._strips = (options.strips || []).map(o => (0, _strip.default)(this, o));
this._majorTicks = this._minorTicks = null;
this._firstDrawing = true
}
calculateInterval(value, prevValue) {
const options = this._options;
if (!options || options.type !== _axes_constants.default.logarithmic) {
return _abs(value - prevValue)
}
const {
allowNegatives: allowNegatives,
linearThreshold: linearThreshold
} = new _range.Range(this.getTranslator().getBusinessRange());
return _abs((0, _utils.getLogExt)(value, options.logarithmBase, allowNegatives, linearThreshold) - (0, _utils.getLogExt)(prevValue, options.logarithmBase, allowNegatives, linearThreshold))
}
getCanvasRange() {
const translator = this._translator;
return {
startValue: translator.from(translator.translate("canvas_position_start")),
endValue: translator.from(translator.translate("canvas_position_end"))
}
}
_processCanvas(canvas) {
return canvas
}
updateCanvas(canvas, canvasRedesign) {
if (!canvasRedesign) {
const positions = this._orthogonalPositions = {
start: !this._isHorizontal ? canvas.left : canvas.top,
end: !this._isHorizontal ? canvas.width - canvas.right : canvas.height - canvas.bottom
};
positions.center = positions.start + (positions.end - positions.start) / 2
} else {
this._orthogonalPositions = null
}
this._canvas = canvas;
this._translator.updateCanvas(this._processCanvas(canvas));
this._initAxisPositions()
}
getCanvas() {
return this._canvas
}
getAxisShift() {
return this._axisShift || 0
}
hideTitle() {
if (this._options.title.text) {
this._incidentOccurred("W2105", [this._isHorizontal ? "horizontal" : "vertical"]);
this._axisTitleGroup.clear()
}
}
getTitle() {
return this._title
}
hideOuterElements() {
const options = this._options;
if ((options.label.visible || this._outsideConstantLines.length) && !this._translator.getBusinessRange().isEmpty()) {
this._incidentOccurred("W2106", [this._isHorizontal ? "horizontal" : "vertical"]);
this._axisElementsGroup.clear();
callAction(this._outsideConstantLines, "removeLabel")
}
}
_resolveLogarithmicOptionsForRange(range) {
const options = this._options;
if (options.type === _axes_constants.default.logarithmic) {
range.addRange({
allowNegatives: void 0 !== options.allowNegatives ? options.allowNegatives : range.min <= 0
});
if (!isNaN(options.linearThreshold)) {
range.linearThreshold = options.linearThreshold
}
}
}
adjustViewport(businessRange) {
const options = this._options;
const isDiscrete = options.type === _axes_constants.default.discrete;
let categories = this._seriesData && this._seriesData.categories || [];
const wholeRange = this.adjustRange((0, _utils.getVizRangeObject)(options.wholeRange));
const visualRange = this.getViewport() || {};
const result = new _range.Range(businessRange);
this._addConstantLinesToRange(result);
let minDefined = (0, _m_type.isDefined)(visualRange.startValue);
let maxDefined = (0, _m_type.isDefined)(visualRange.endValue);
if (!isDiscrete) {
minDefined = minDefined && (!(0, _m_type.isDefined)(wholeRange.endValue) || visualRange.startValue < wholeRange.endValue);
maxDefined = maxDefined && (!(0, _m_type.isDefined)(wholeRange.startValue) || visualRange.endValue > wholeRange.startValue)
}
const minVisible = minDefined ? visualRange.startValue : result.minVisible;
const maxVisible = maxDefined ? visualRange.endValue : result.maxVisible;
if (!isDiscrete) {
result.min = wholeRange.startValue ?? result.min;
result.max = wholeRange.endValue ?? result.max
} else {
const categoriesInfo = (0, _utils.getCategoriesInfo)(categories, wholeRange.startValue, wholeRange.endValue);
categories = categoriesInfo.categories;
result.categories = categories
}
const adjustedVisualRange = (0, _utils.adjustVisualRange)({
axisType: options.type,
dataType: options.dataType,
base: options.logarithmBase
}, {
startValue: minDefined ? visualRange.startValue : void 0,
endValue: maxDefined ? visualRange.endValue : void 0,
length: visualRange.length
}, {
categories: categories,
min: wholeRange.startValue,
max: wholeRange.endValue
}, {
categories: categories,
min: minVisible,
max: maxVisible
});
result.minVisible = adjustedVisualRange.startValue;
result.maxVisible = adjustedVisualRange.endValue;
!(0, _m_type.isDefined)(result.min) && (result.min = result.minVisible);
!(0, _m_type.isDefined)(result.max) && (result.max = result.maxVisible);
result.addRange({});
this._resolveLogarithmicOptionsForRange(result);
return result
}
adjustRange(range) {
range = range || {};
const isDiscrete = this._options.type === _axes_constants.default.discrete;
const isLogarithmic = this._options.type === _axes_constants.default.logarithmic;
const disabledNegatives = false === this._options.allowNegatives;
if (isLogarithmic) {
range.startValue = disabledNegatives && range.startValue <= 0 ? null : range.startValue;
range.endValue = disabledNegatives && range.endValue <= 0 ? null : range.endValue
}
if (!isDiscrete && (0, _m_type.isDefined)(range.startValue) && (0, _m_type.isDefined)(range.endValue) && range.startValue > range.endValue) {
const tmp = range.endValue;
range.endValue = range.startValue;
range.startValue = tmp
}
return range
}
_getVisualRangeUpdateMode(viewport, newRange, oppositeValue) {
let value = this._options.visualRangeUpdateMode;
const translator = this._translator;
const range = this._seriesData;
const prevDataInfo = this._prevDataInfo;
if (prevDataInfo.isEmpty && !prevDataInfo.containsConstantLine) {
return KEEP
}
if (!this.isArgumentAxis) {
const viewport = this.getViewport();
const isViewportNotDefined = !(0, _m_type.isDefined)(viewport.startValue) && !(0, _m_type.isDefined)(viewport.endValue) && !(0, _m_type.isDefined)(viewport.length);
if (isViewportNotDefined) {
const visualRange = this.visualRange();
const isVisualRangeNotDefined = !(0, _m_type.isDefined)(visualRange.startValue) && !(0, _m_type.isDefined)(visualRange.endValue);
if (isVisualRangeNotDefined) {
return RESET
}
}
}
if (this.isArgumentAxis) {
if (![SHIFT, KEEP, RESET].includes(value)) {
if (range.axisType === _axes_constants.default.discrete) {
const categories = range.categories;
const newCategories = newRange.categories;
const visualRange = this.visualRange();
if (categories && newCategories && categories.length && -1 !== newCategories.map(c => c.valueOf()).join(",").indexOf(categories.map(c => c.valueOf()).join(",")) && (visualRange.startValue.valueOf() !== categories[0].valueOf() || visualRange.endValue.valueOf() !== categories[categories.length - 1].valueOf())) {
value = KEEP
} else {
value = RESET
}
} else {
const minPoint = translator.translate(range.min);
const minVisiblePoint = translator.translate(viewport.startValue);
const maxPoint = translator.translate(range.max);
const maxVisiblePoint = translator.translate(viewport.endValue);
if (minPoint === minVisiblePoint && maxPoint === maxVisiblePoint) {
value = RESET
} else if (minPoint !== minVisiblePoint && maxPoint === maxVisiblePoint) {
value = SHIFT
} else {
value = KEEP
}
}
if (value === KEEP && prevDataInfo.isEmpty && prevDataInfo.containsConstantLine) {
value = RESET
}
}
} else if (![KEEP, RESET].includes(value)) {
if (oppositeValue === KEEP) {
value = KEEP
} else {
value = RESET
}
}
return value
}
_handleBusinessRangeChanged(oppositeVisualRangeUpdateMode, axisReinitialized, newRange) {
const visualRange = this.visualRange();
if (axisReinitialized || this._translator.getBusinessRange().isEmpty()) {
return
}
const visualRangeUpdateMode = this._lastVisualRangeUpdateMode = this._getVisualRangeUpdateMode(visualRange, newRange, oppositeVisualRangeUpdateMode);
if (visualRangeUpdateMode === KEEP) {
this._setVisualRange([visualRange.startValue, visualRange.endValue])
} else if (visualRangeUpdateMode === RESET) {
this._setVisualRange([null, null])
} else if (visualRangeUpdateMode === SHIFT) {
this._setVisualRange({
length: this.getVisualRangeLength()
})
}
}
getVisualRangeLength(range) {
const currentBusinessRange = range || this._translator.getBusinessRange();
const {
type: type
} = this._options;
let length;
if (type === _axes_constants.default.logarithmic) {
length = (0, _m_math.adjust)(this.calculateInterval(currentBusinessRange.maxVisible, currentBusinessRange.minVisible))
} else if (type === _axes_constants.default.discrete) {
const categoriesInfo = (0, _utils.getCategoriesInfo)(currentBusinessRange.categories, currentBusinessRange.minVisible, currentBusinessRange.maxVisible);
length = categoriesInfo.categories.length
} else {
length = currentBusinessRange.maxVisible - currentBusinessRange.minVisible
}
return length
}
_getTickIntervalValue() {
const tickInterval = this.getTickInterval();
if (!(0, _m_type.isDefined)(tickInterval)) {
return 0
}
return "datetime" === this._options.dataType ? _m_date.dateUtils.dateToMilliseconds(tickInterval) : tickInterval
}
getWholeRangeBreaks() {
const businessRange = this._translator.getBusinessRange();
const {
type: type
} = this._options;
if (type === _axes_constants.default.discrete || !(0, _m_type.isDefined)(businessRange.min) || !(0, _m_type.isDefined)(businessRange.max)) {
return []
}
const interval = this._getTickIntervalValue();
return this._getBreaksForRange(businessRange.min, businessRange.max).reduce((result, scaleBreak) => {
const hidden = this._getHiddenDuration(scaleBreak, interval);
const shift = (this.calculateInterval(scaleBreak.to, scaleBreak.from) - hidden) / 2;
return hidden ? result.concat((0, _m_extend.extend)({}, scaleBreak, {
from: this._addToValue(scaleBreak.from, shift),
to: this._addToValue(scaleBreak.to, -shift),
cumulativeWidth: 0
})) : result
}, [])
}
_getBreaksForRange(minVisible, maxVisible) {
const viewport = minVisible > maxVisible ? {
minVisible: maxVisible,
maxVisible: minVisible
} : {
minVisible: minVisible,
maxVisible: maxVisible
};
const breaks = this._getScaleBreaks(this._options, viewport, this._series, this.isArgumentAxis);
return this._filterBreaks(breaks, viewport, this._options.breakStyle)
}
_getHiddenDuration(scaleBreak, tickInterval) {
const duration = this.calculateInterval(scaleBreak.to, scaleBreak.from);
return scaleBreak.gapSize ? duration : Math.max(duration - tickInterval, 0)
}
getVisualRangeLengthWithoutBreaks(range) {
const businessRange = range || this._translator.getBusinessRange();
const length = this.getVisualRangeLength(businessRange);
const options = this._options;
if (options.type === _axes_constants.default.discrete || !(0, _m_type.isDefined)(businessRange.minVisible) || !(0, _m_type.isDefined)(businessRange.maxVisible)) {
return length
}
const interval = this._getTickIntervalValue();
return this._getBreaksForRange(businessRange.minVisible, businessRange.maxVisible).reduce((result, scaleBreak) => result - this._getHiddenDuration(scaleBreak, interval), length)
}
_addToValue(value, diff) {
if (this._options.type === _axes_constants.default.logarithmic) {
const translator = this.getTranslator();
return translator.toValue(translator.fromValue(value) + diff)
}
return (0, _m_type.isDate)(value) ? new Date(value.getTime() + diff) : value + diff
}
adjustPannedRange(range, anchor) {
const storedParams = this._storedZoomEndParams;
const {
type: type
} = this._options;
if (!storedParams || type === _axes_constants.default.discrete) {
return range
}
const {
startRange: startRange
} = storedParams;
if (!this._getBreaksForRange(range.startValue, range.endValue).length && !this._getBreaksForRange(startRange.startValue, startRange.endValue).length) {
return range
}
const isReversed = range.startValue > range.endValue;
if (isReversed) {
const reordered = this.adjustPannedRange({
startValue: range.endValue,
endValue: range.startValue
}, anchor);
return {
startValue: reordered.endValue,
endValue: reordered.startValue
}
}
const targetLength = this.getVisualRangeLengthWithoutBreaks({
minVisible: startRange.startValue,
maxVisible: startRange.endValue
});
if (!targetLength) {
return range
}
const tolerance = 1e-4 * targetLength;
const bounds = this.getZoomBounds();
const keepsEndValue = anchor ? "end" === anchor : range.startValue > startRange.startValue || range.endValue > startRange.endValue;
let result = range;
let current = range;
let bestDeviation = 1 / 0;
for (let i = 0; i < 5; i += 1) {
const delta = this.getVisualRangeLengthWithoutBreaks({
minVisible: current.startValue,
maxVisible: current.endValue
}) - targetLength;
const deviation = Math.abs(delta);
if (deviation < bestDeviation) {
bestDeviation = deviation;
result = current
}
if (deviation <= tolerance) {
break
}
const shifted = keepsEndValue ? {
startValue: this._addToValue(current.startValue, delta),
endValue: current.endValue
} : {
startValue: current.startValue,
endValue: this._addToValue(current.endValue, -delta)
};
current = {
startValue: shifted.startValue < bounds.startValue ? bounds.startValue : shifted.startValue,
endValue: shifted.endValue > bounds.endValue ? bounds.endValue : shifted.endValue
};
if (current.startValue >= current.endValue) {
break
}
}
return result
}
getVisualRangeCenter(range, useMerge) {
const translator = this.getTranslator();
const businessRange = translator.getBusinessRange();
const currentBusinessRange = useMerge ? (0, _m_extend.extend)(true, {}, businessRange, range || {}) : range || businessRange;
const {
type: type,
logarithmBase: logarithmBase
} = this._options;
let center;
if (!(0, _m_type.isDefined)(currentBusinessRange.minVisible) || !(0, _m_type.isDefined)(currentBusinessRange.maxVisible)) {
return
}
if (type === _axes_constants.default.logarithmic) {
const {
allowNegatives: allowNegatives,
linearThreshold: linearThreshold,
minVisible: minVisible,
maxVisible: maxVisible
} = currentBusinessRange;
center = (0, _utils.raiseToExt)((0, _m_math.adjust)((0, _utils.getLogExt)(maxVisible, logarithmBase, allowNegatives, linearThreshold) + (0, _utils.getLogExt)(minVisible, logarithmBase, allowNegatives, linearThreshold)) / 2, logarithmBase, allowNegatives, linearThreshold)
} else if (type === _axes_constants.default.discrete) {
const categoriesInfo = (0, _utils.getCategoriesInfo)(currentBusinessRange.categories, currentBusinessRange.minVisible, currentBusinessRange.maxVisible);
const index = Math.ceil(categoriesInfo.categories.length / 2) - 1;
center = businessRange.categories.indexOf(categoriesInfo.categories[index])
} else {
center = translator.toValue((currentBusinessRange.maxVisible.valueOf() + currentBusinessRange.minVisible.valueOf()) / 2)
}
return center
}
setBusinessRange(range, axisReinitialized, oppositeVisualRangeUpdateMode, argCategories) {
const options = this._options;
const isDiscrete = options.type === _axes_constants.default.discrete;
this._handleBusinessRangeChanged(oppositeVisualRangeUpdateMode, axisReinitialized, range);
this._seriesData = new _range.Range(range);
const dataIsEmpty = this._seriesData.isEmpty();
const rangeWithConstantLines = new _range.Range(this._seriesData);
this._addConstantLinesToRange(rangeWithConstantLines);
this._prevDataInfo = {
isEmpty: dataIsEmpty,
containsConstantLine: rangeWithConstantLines.containsConstantLine
};
this._seriesData.addRange({
categories: options.categories,
dataType: options.dataType,
axisType: options.type,
base: options.logarithmBase,
invert: options.inverted
});
this._resolveLogarithmicOptionsForRange(this._seriesData);
if (!isDiscrete) {
if (!(0, _m_type.isDefined)(this._seriesData.min) && !(0, _m_type.isDefined)(this._seriesData.max)) {
const visualRange = this.getViewport();
visualRange && this._seriesData.addRange({
min: visualRange.startValue,
max: visualRange.endValue
})
}
const synchronizedValue = options.synchronizedValue;
if ((0, _m_type.isDefined)(synchronizedValue)) {
this._seriesData.addRange({
min: synchronizedValue,
max: synchronizedValue
})
}
}
this._seriesData.minVisible = this._seriesData.minVisible ?? this._seriesData.min;
this._seriesData.maxVisible = this._seriesData.maxVisible ?? this._seriesData.max;
if (!this.isArgumentAxis && options.showZero) {
this._seriesData.correctValueZeroLevel()
}
this._seriesData.sortCategories(this.getCategoriesSorter(argCategories));
this._seriesData.userBreaks = this._seriesData.isEmpty() ? [] : this._getScaleBreaks(options, this._seriesData, this._series, this.isArgumentAxis);
this._translator.updateBusinessRange(this._getViewportRange())
}
_addConstantLinesToRange(dataRange) {
this._outsideConstantLines.concat(this._insideConstantLines || []).forEach(cl => {
if (cl.options.extendAxis) {
const value = cl.getParsedValue();
dataRange.addRange({
containsConstantLine: true,
minVisible: value,
maxVisible: value,
min: !(0, _m_type.isDefined)(dataRange.min) ? value : dataRange.min,
max: !(0, _m_type.isDefined)(dataRange.max) ? value : dataRange.max
})
}
})
}
setGroupSeries(series) {
this._series = series
}
getLabelsPosition() {
const options = this._options;
const position = options.position;
const labelShift = options.label.indentFromAxis + (this._axisShift || 0) + this._constantLabelOffset;
const axisPosition = this._axisPosition;
return position === TOP || position === LEFT ? axisPosition - labelShift : axisPosition + labelShift
}
getFormattedValue(value, options, point) {
const labelOptions = this._options.label;
return (0, _m_type.isDefined)(value) ? this.formatLabel(value, (0, _m_extend.extend)(true, {}, labelOptions, options), void 0, point) : null
}
_getBoundaryTicks(majors, viewPort) {
const length = majors.length;
const options = this._options;
const customBounds = options.customBoundTicks;
const min = viewPort.minVisible;
const max = viewPort.maxVisible;
const addMinMax = options.showCustomBoundaryTicks ? this._boundaryTicksVisibility : {};
let boundaryTicks = [];
if (options.type === _axes_constants.default.discrete) {
if (this._tickOffset && 0 !== majors.length) {
boundaryTicks = [majors[0], majors[majors.length - 1]]
}
} else if (customBounds) {
if (addMinMax.min && (0, _m_type.isDefined)(customBounds[0])) {
boundaryTicks.push(customBounds[0])
}
if (addMinMax.max && (0, _m_type.isDefined)(customBounds[1])) {
boundaryTicks.push(customBounds[1])
}
} else {
if (addMinMax.min && (0 === length || majors[0] > min)) {
boundaryTicks.push(min)
}
if (addMinMax.max && (0 === length || majors[length - 1] < max)) {
boundaryTicks.push(max)
}
}
return boundaryTicks
}
setPercentLabelFormat() {
if (!this._hasLabelFormat) {
this._options.label.format = "percent"
}
}
resetAutoLabelFormat() {
if (!this._hasLabelFormat) {
delete this._options.label.format
}
}
getMultipleAxesSpacing() {
return this._options.multipleAxesSpacing || 0
}
getTicksValues() {
return {
majorTicksValues: convertTicksToValues(this._majorTicks),
minorTicksValues: convertTicksToValues(this._minorTicks)
}
}
estimateTickInterval(canvas) {
this.updateCanvas(canvas);
return this._tickInterval !== this._getTicks(this._getViewportRange(), _m_common.noop, true).tickInterval
}
setTicks(ticks) {
const majors = ticks.majorTicks || [];
this._majorTicks = majors.map(createMajorTick(this, this._renderer, this._getSkippedCategory(majors)));
this._minorTicks = (ticks.minorTicks || []).map(createMinorTick(this, this._renderer));
this._isSynchronized = true
}
_adjustDivisionFactor(val) {
return val
}
_getTicks(viewPort, incidentOccurred, skipTickGeneration) {
const options = this._options;
const customTicks = options.customTicks;
const customMinorTicks = options.customMinorTicks;
return getTickGenerator(options, incidentOccurred || this._incidentOccurred, skipTickGeneration, this._translator.getBusinessRange().isEmpty(), this._adjustDivisionFactor.bind(this), viewPort)({
min: viewPort.minVisible,
max: viewPort.maxVisible,
categories: viewPort.categories,
isSpacedMargin: viewPort.isSpacedMargin
}, this._getScreenDelta(), options.tickInterval, "ignore" === options.label.overlappingBehavior || options.forceUserTickInterval, {
majors: customTicks,
minors: customMinorTicks
}, options.minorTickInterval, options.minorTickCount, this._initialBreaks)
}
_createTicksAndLabelFormat(range, incidentOccurred) {
const options = this._options;
const ticks = this._getTicks(range, incidentOccurred, false);
if (!range.isEmpty() && options.type === _axes_constants.default.discrete && "datetime" === options.dataType && !this._hasLabelFormat && ticks.ticks.length) {
options.label.format = _format_helper.default.getDateFormatByTicks(ticks.ticks)
}
return ticks
}
getAggregationInfo(useAllAggregatedPoints, range) {
var _this$_seriesData;
const options = this._options;
const businessRange = new _range.Range(this.getTranslator().getBusinessRange()).addRange(range);
const visualRange = this.getViewport();
const minVisible = (null === visualRange || void 0 === visualRange ? void 0 : visualRange.startValue) ?? businessRange.minVisible;
const maxVisible = (null === visualRange || void 0 === visualRange ? void 0 : visualRange.endValue) ?? businessRange.maxVisible;
const aggregationInterval = options.aggregationInterval;
const aggregationGroupWidth = this._getAggregationGroupWidth();
const minInterval = !options.aggregationGroupWidth && !aggregationInterval && range.interval;
const generateTicks = configureGenerator(options, aggregationGroupWidth, businessRange, this._getScreenDelta(), minInterval);
const tickInterval = generateTicks(aggregationInterval, true, minVisible, maxVisible, null === (_this$_seriesData = this._seriesData) || void 0 === _this$_seriesData ? void 0 : _this$_seriesData.breaks).tickInterval;
const ticks = this._generateTick(useAllAggregatedPoints, businessRange, minVisible, maxVisible, tickInterval, generateTicks);
this._aggregationInterval = tickInterval;
return {
interval: tickInterval,
ticks: ticks
}
}
_getAggregationGroupWidth() {
const {
checkInterval: checkInterval,
sizePointNormalState: sizePointNormalState
} = this._marginOptions || {};
const {
aggregationGroupWidth: aggregationGroupWidth,
axisDivisionFactor: axisDivisionFactor
} = this._options;
if (aggregationGroupWidth) {
return aggregationGroupWidth
}
if (sizePointNormalState) {
return Math.min(sizePointNormalState, axisDivisionFactor)
}
if (checkInterval) {
return axisDivisionFactor
}
return aggregationGroupWidth
}
_generateTick(useAllAggregatedPoints, businessRange, minVisible, maxVisible, tickInterval, generateTicks) {
const min = useAllAggregatedPoints ? businessRange.min : minVisible;
const max = useAllAggregatedPoints ? businessRange.max : maxVisible;
if (!(0, _m_type.isDefined)(min) || !(0, _m_type.isDefined)(max)) {
return []
}
const options = this._options;
const add = (0, _utils.getAddFunction)({
base: options.logarithmBase,
axisType: options.type,
dataType: options.dataType
}, false);
let start = min;
let end = max;
if (!useAllAggregatedPoints && (0, _m_type.isDefined)(tickInterval)) {
const maxMinDistance = Math.max(this.calculateInterval(max, min), "datetime" === options.dataType ? _m_date.dateUtils.dateToMilliseconds(tickInterval) : tickInterval);
start = add(min, maxMinDistance, -1);
end = add(max, maxMinDistance)
}
start = start < businessRange.min ? businessRange.min : start;
end = end > businessRange.max ? businessRange.max : end;
const breaks = this._getScaleBreaks(options, {
minVisible: start,
maxVisible: end
}, this._series, this.isArgumentAxis);
const filteredBreaks = this._filterBreaks(breaks, {
minVisible: start,
maxVisible: end
}, options.breakStyle);
return generateTicks(tickInterval, false, start, end, filteredBreaks).ticks
}
getTickInterval() {
return this._tickInterval
}
getAggregationInterval() {
return this._aggregationInterval
}
createTicks(canvas) {
const renderer = this._renderer;
const options = this._options;
if (!canvas) {
return
}
this._isSynchronized = false;
this.updateCanvas(canvas);
const range = this._getViewportRange();
this._initialBreaks = range.breaks = this._seriesData.breaks = this._filterBreaks(this._seriesData.userBreaks, range, options.breakStyle);
this._estimatedTickInterval = this._getTicks(this.adjustViewport(this._seriesData), _m_common.noop, true).tickInterval;
const margins = this._calculateValueMargins();
range.addRange({
minVisible: margins.minValue,
maxVisible: margins.maxValue,
isSpacedMargin: margins.isSpacedMargin
});
const ticks = this._createTicksAndLabelFormat(range);
const boundaryTicks = this._getBoundaryTicks(ticks.ticks, this._getViewportRange());
if (options.showCustomBoundaryTicks && boundaryTicks.length) {
this._boundaryTicks = [boundaryTicks[0]].map(createBoundaryTick(this, renderer, true));
if (boundaryTicks.length > 1) {
this._boundaryTicks = this._boundaryTicks.concat([boundaryTicks[1]].map(createBoundaryTick(this, renderer, false)))
}
} else {
this._boundaryTicks = []
}
const minors = (ticks.minorTicks || []).filter(minor => !boundaryTicks.some(boundary => (0, _utils.valueOf)(boundary) === (0, _utils.valueOf)(minor)));
this._tickInterval = ticks.tickInterval;
this._minorTickInterval = ticks.minorTickInterval;
const oldMajorTicks = this._majorTicks || [];
const majorTicksByValues = oldMajorTicks.reduce((r, t) => {
r[t.value.valueOf()] = t;
return r
}, {});
const sameType = (0, _m_type.type)(ticks.ticks[0]) === (0, _m_type.type)(oldMajorTicks[0] && oldMajorTicks[0].value);
const skippedCategory = this._getSkippedCategory(ticks.ticks);
const majorTicks = ticks.ticks.map(v => {
const tick = majorTicksByValues[v.valueOf()];
if (tick && sameType) {
delete majorTicksByValues[v.valueOf()];
tick.setSkippedCategory(skippedCategory);
return tick
} else {
return createMajorTick(this, renderer, skippedCategory)(v)
}
});
this._majorTicks = majorTicks;
const oldMinorTicks = this._minorTicks || [];
this._minorTicks = minors.map((v, i) => {
const minorTick = oldMinorTicks[i];
if (minorTick) {
minorTick.updateValue(v);
return minorTick
}
return createMinorTick(this, renderer)(v)
});
this._ticksToRemove = Object.keys(majorTicksByValues).map(k => majorTicksByValues[k]).concat(oldMinorTicks.slice(this._minorTicks.length, oldMinorTicks.length));
this._ticksToRemove.forEach(t => {
var _t$label;
return null === (_t$label = t.label) || void 0 === _t$label ? void 0 : _t$label.removeTitle()
});
if (ticks.breaks) {
this._seriesData.breaks = ticks.breaks
}
this._reinitTranslator(this._getViewportRange())
}
_reinitTranslator(range) {
const translator = this._translator;
if (this._isSynchronized) {
return
}
translator.updateBusinessRange(range)
}
_getViewportRange() {
return this.adjustViewport(this._seriesData)
}
setMarginOptions(options) {
this._marginOptions = options
}
getMarginOptions() {
return this._marginOptions ?? {}
}
_calculateRangeInterval(interval) {
const isDateTime = "datetime" === this._options.dataType;
const minArgs = [];
const addToArgs = function(value) {
(0, _m_type.isDefined)(value) && minArgs.push(isDateTime ? _m_date.dateUtils.dateToMilliseconds(value) : value)
};
addToArgs(this._tickInterval);
addToArgs(this._estimatedTickInterval);
(0, _m_type.isDefined)(interval) && minArgs.push(interval);
addToArgs(this._aggregationInterval);
return this._calculateWorkWeekInterval(_min.apply(this, minArgs))
}
_calculateWorkWeekInterval(businessInterval) {
const options = this._options;
if ("datetime" === options.dataType && options.workdaysOnly && businessInterval) {
const workWeek = options.workWeek.length * dateIntervals.day;
const weekend = dateIntervals.week - workWeek;
if (workWeek !== businessInterval && weekend < businessInterval) {
const weekendsCount = Math.ceil(businessInterval / dateIntervals.week);
businessInterval -= weekend * weekendsCount
} else if (weekend >= businessInterval && businessInterval > dateIntervals.day) {
businessInterval = dateIntervals.day
}
}
return businessInterval
}
_getConvertIntervalCoefficient(intervalInPx, screenDelta) {
const ratioOfCanvasRange = this._translator.ratioOfCanvasRange();
return ratioOfCanvasRange / (ratioOfCanvasRange * screenDelta / (intervalInPx + screenDelta))
}
_calculateValueMargins(ticks) {
this._resetMargins();
const margins = this.getMarginOptions();
const marginSize = (margins.size || 0) / 2;
const options = this._options;
const dataRange = this._getViewportRange();
const viewPort = this.getViewport();
const screenDelta = this._getScreenDelta();
const isDiscrete = -1 !== (options.type || "").indexOf(_axes_constants.default.discrete);
const valueMarginsEnabled = options.valueMarginsEnabled && !isDiscrete && !this.customPositionIsBoundaryOrthogonalAxis();
const translator = this._translator;
const minValueMargin = options.minValueMargin;
const maxValueMargin = options.maxValueMargin;
let minPadding = 0;
let maxPadding = 0;
let interval = 0;
let rangeInterval;
if (!screenDelta) {
return {
startPadding: 0,
endPadding: 0
}
}
if (this.isArgumentAxis && margins.checkInterval) {
rangeInterval = this._calculateRangeInterval(dataRange.interval);
const pxInterval = translator.getInterval(rangeInterval);
if (isFinite(pxInterval)) {
interval = Math.ceil(pxInterval / (2 * this._getConvertIntervalCoefficient(pxInterval, screenDelta)))
} else {
rangeInterval = 0
}
}
let minPercentPadding;
let maxPercentPadding;
const maxPaddingValue = .8 * screenDelta / 2;
if (valueMarginsEnabled) {
if ((0, _m_type.isDefined)(minValueMargin)) {
minPercentPadding = isFinite(minValueMargin) ? minValueMargin : 0
} else if (!this.isArgumentAxis && margins.checkInterval && (0, _utils.valueOf)(dataRange.minVisible) > 0 && (0, _utils.valueOf)(dataRange.minVisible) === (0, _utils.valueOf)(dataRange.min)) {
minPadding = 5
} else {
minPadding = Math.max(marginSize, interval);
minPadding = Math.min(maxPaddingValue, minPadding)
}
if ((0, _m_type.isDefined)(maxValueMargin)) {
maxPercentPadding = isFinite(maxValueMargin) ? maxValueMargin : 0
} else if (!this.isArgumentAxis && margins.checkInterval && (0, _utils.valueOf)(dataRange.maxVisible) < 0 && (0, _utils.valueOf)(dataRange.maxVisible) === (0, _utils.valueOf)(dataRange.max)) {
maxPadding = 5
} else {
maxPadding = Math.max(marginSize, interval);
maxPadding = Math.min(maxPaddingValue, maxPadding)
}
}
const percentStick = margins.percentStick && !this.isArgumentAxis;
if (percentStick) {
if (1 === _abs(dataRange.max)) {
maxPadding = 0
}
if (1 === _abs(dataRange.min)) {
minPadding = 0
}
}
const canvasStartEnd = this._getCanvasStartEnd();
const commonMargin = 1 + (minPercentPadding || 0) + (maxPercentPadding || 0);
const screenDeltaWithMargins = (screenDelta - minPadding - maxPadding) / commonMargin || screenDelta;
if (void 0 !== minPercentPadding || void 0 !== maxPercentPadding) {
if (void 0 !== minPercentPadding) {
minPadding = screenDeltaWithMargins * minPercentPadding
}
if (void 0 !== maxPercentPadding) {
maxPadding = screenDeltaWithMargins * maxPercentPadding
}
}
let minValue;
let maxValue;
if (options.type !== _axes_constants.default.discrete && ticks && ticks.length > 1 && !options.skipViewportExtending && !viewPort.action && false !== options.endOnTick) {
const length = ticks.length;
const firstTickPosition = translator.translate(ticks[0].value);
const lastTickPosition = translator.translate(ticks[length - 1].value);
const invertMultiplier = firstTickPosition > lastTickPosition ? -1 : 1;
const minTickPadding = _max(invertMultiplier * (canvasStartEnd.start - firstTickPosition), 0);
const maxTickPadding = _max(invertMultiplier * (lastTickPosition - canvasStartEnd.end), 0);
if (minTickPadding > minPadding || maxTickPadding > maxPadding) {
const commonPadding = maxTickPadding + minTickPadding;
const coeff = this._getConvertIntervalCoefficient(commonPadding, screenDelta);
if (minTickPadding >= minPadding) {
minValue = ticks[0].value
}
if (maxTickPadding >= maxPadding) {
maxValue = ticks[length - 1].value
}
minPadding = _max(minTickPadding, minPadding) / coeff;
maxPadding = _max(maxTickPadding, maxPadding) / coeff
}
}
minPercentPadding = void 0 === minPercentPadding ? minPadding / screenDeltaWithMargins : minPercentPadding;
maxPercentPadding = void 0 === maxPercentPadding ? maxPadding / screenDeltaWithMargins : maxPercentPadding;
if (!isDiscrete) {
if (this._translator.isInverted()) {
minValue = minValue ?? translator.from(canvasStartEnd.start + screenDelta * minPercentPadding, -1);
maxValue = maxValue ?? translator.from(canvasStartEnd.end - screenDelta * maxPercentPadding, 1)
} else {
minValue = minValue ?? translator.from(canvasStartEnd.start - screenDelta * minPercentPadding, -1);
maxValue = maxValue ?? translator.from(canvasStartEnd.end + screenDelta * maxPercentPadding, 1)
}
}
const {
correctedMin: correctedMin,
correctedMax: correctedMax,
start: start,
end: end
} = this.getCorrectedValuesToZero(minValue, maxValue);
minPadding = start ?? minPadding;
maxPadding = end ?? maxPadding;
return {
startPadding: translator.isInverted() ? maxPadding : minPadding,
endPadding: translator.isInverted() ? minPadding : maxPadding,
minValue: correctedMin ?? minValue,
maxValue: correctedMax ?? maxValue,
interval: rangeInterval,
isSpacedMargin: minPadding === maxPadding && 0 !== minPadding
}
}
_shouldCorrectValuesToZero(minValue, maxValue) {
if (this.isArgumentAxis || "datetime" === this._options.dataType) {
return false
}
const dataRange = this._getViewportRange();
if (minValue > dataRange.max || minValue > dataRange.maxVisible) {
return false
}
if (maxValue < dataRange.min || maxValue < dataRange.minVisible) {
return false
}
return true
}
getCorrectedValuesToZero(minValue, maxValue) {
const translator = this._translator;
const canvasStartEnd = this._getCanvasStartEnd();
const dataRange = this._getViewportRange();
const screenDelta = this._getScreenDelta();
let start;
let end;
let correctedMin;
let correctedMax;
const correctZeroLevel = (minPoint, maxPoint) => {
const minExpectedPadding = _abs(canvasStartEnd.start - minPoint);
const maxExpectedPadding = _abs(canvasStartEnd.end - maxPoint);
const coeff = this._getConvertIntervalCoefficient(minExpectedPadding + maxExpectedPadding, screenDelta);
start = minExpectedPadding / coeff;
end = maxExpectedPadding / coeff
};
if (this._shouldCorrectValuesToZero(minValue, maxValue)) {
if (minValue * dataRange.min <= 0 && minValue * dataRange.minVisible <= 0) {
correctZeroLevel(translator.translate(0), translator.translate(maxValue));
correctedMin = 0
}
if (maxValue * dataRange.max <= 0 && maxValue * dataRange.maxVisible <= 0) {
correctZeroLevel(translator.translate(minValue), translator.translate(0));
correctedMax = 0
}
}
return {
start: isFinite(start) ? start : null,
end: isFinite(end) ? end : null,
correctedMin: correctedMin,
correctedMax: correctedMax
}
}
applyMargins() {
if (this._isSynchronized) {
return
}
const margins = this._calculateValueMargins(this._majorTicks);
const canvas = (0, _m_extend.extend)({}, this._canvas, {
startPadding: margins.startPadding,
endPadding: margins.endPadding
});
this._translator.updateCanvas(this._processCanvas(canvas));
if (isFinite(margins.interval)) {
const br = this._translator.getBusinessRange();
br.addRange({
interval: margins.interval
});
this._translator.updateBusinessRange(br)
}
}
_resetMargins() {
this._reinitTranslator(this._getViewportRange());
if (this._canvas) {
this._translator.updateCanvas(this._processCanvas(this._canvas))
}
}
_createConstantLines() {
const constantLines = (this._options.constantLines || []).map(o => (0, _constant_line.default)(this, o));
this._outsideConstantLines = constantLines.filter(l => "outside" === l.labelPosition);
this._insideConstantLines = constantLines.filter(l => "inside" === l.labelPosition)
}
draw(canvas, borderOptions) {
const options = this._options;
this.borderOptions = borderOptions || {
visible: false
};
this._resetMargins();
this.createTicks(canvas);
this.applyMargins();
this._clearAxisGroups();
initTickCoords(this._majorTicks);
initTickCoords(this._minorTicks);
initTickCoords(this._boundaryTicks);
this._axisGroup.append(this._axesContainerGroup);
this._drawAxis();
this._drawTitle();
drawTickMarks(this._majorTicks, options.tick);
drawTickMarks(this._minorTicks, options.minorTick);
drawTickMarks(this._boundaryTicks, options.tick);
const drawGridLine = this._getGridLineDrawer();
drawGrids(this._majorTicks, drawGridLine);
drawGrids(this._minorTicks, drawGridLine);
callAction(this._majorTicks, "drawLabel", this._getViewportRange(), this._getTemplate(options.label.template));
this._templatesRendered && this._templatesRendered.reject();
this._templatesRendered = (0, _deferred.Deferred)();
this._majorTicks.forEach(tick => {
tick.labelRotationAngle = 0;
tick.labelAlignment = void 0;
tick.labelOffset = 0
});
callAction(this._outsideConstantLines.concat(this._insideConstantLines), "draw");
callAction(this._strips, "draw");
this._dateMarkers = this._drawDateMarkers() || [];
this._stripLabelAxesGroup && this._axisStripLabelGroup.append(this._stripLabelAxesGroup);
this._gridContainerGroup && this._axisGridGroup.append(this._gridContainerGroup);
this._stripsGroup && this._axisStripGroup.append(this._stripsGroup);
this._labelsAxesGroup && this._axisElementsGroup.append(this._labelsAxesGroup);
if (this._constantLinesGroup) {
this._axisConstantLineGroups.above.inside.append(this._constantLinesGroup.above);
this._axisConstantLineGroups.above.outside1.append(this._constantLinesGroup.above);
this._axisConstantLineGroups.above.outside2.append(this._constantLinesGroup.above);
this._axisConstantLineGroups.under.inside.append(this._constantLinesGroup.under);
this._axisConstantLineGroups.under.outside1.append(this._constantLinesGroup.under);
this._axisConstantLineGroups.under.outside2.append(this._constantLinesGroup.under)
}
this._measureTitle();
(0, _axes_utils.measureLabels)(this._majorTicks);
!options.label.template && this._applyWordWrap();
(0, _axes_utils.measureLabels)(this._outsideConstantLines);
(0, _axes_utils.measureLabels)(this._insideConstantLines);
(0, _axes_utils.measureLabels)(this._strips);
(0, _axes_utils.measureLabels)(this._dateMarkers);
this._adjustConstantLineLabels(this._insideConstantLines);
this._adjustStripLabels();
let offset = this._constantLabelOffset = this._adjustConstantLineLabels(this._outsideConstantLines);
if (!this._translator.getBusinessRange().isEmpty()) {
this._setLabelsPlacement();
offset = this._adjustLabels(offset)
}
_deferred.when.apply(this, this._majorTicks.map(tick => tick.getTemplateDeferred())).done(() => {
this._templatesRendered.resolve()
});
offset = this._adjustDateMarkers(offset);
this._adjustTitle(offset)
}
getTemplatesDef() {
return this._templatesRendered
}
setRenderedState(state) {
this._drawn = state
}
isRendered() {
return this._drawn
}
_applyWordWrap() {
let convertedTickInterval;
let textWidth;
let textHeight;
const options = this._options;
const tickInterval = this._tickInterval;
if ((0, _m_type.isDefined)(tickInterval)) {
convertedTickInterval = this.getTranslator().getInterval("datetime" === options.dataType ? _m_date.dateUtils.dateToMilliseconds(tickInterval) : tickInterval)
}
const displayMode = this._validateDisplayMode(options.label.displayMode);
const overlappingMode = this._validateOverlappingMode(options.label.overlappingBehavior, displayMode);
const wordWrapMode = options.label.wordWrap || "none";
const overflowMode = options.label.textOverflow || "none";
if (("none" !== wordWrapMode || "none" !== overflowMode) && displayMode !== ROTATE && overlappingMode !== ROTATE && "auto" !== overlappingMode) {
const usefulSpace = (0, _m_type.isDefined)(options.placeholderSize) ? options.placeholderSize - options.label.indentFromAxis : void 0;
if (this._isHorizontal) {
textWidth = convertedTickInterval;
textHeight = usefulSpace
} else {
textWidth = usefulSpace;
textHeight = convertedTickInterval
}
let correctByWidth = false;
let correctByHeight = false;
if (textWidth) {
if (this._majorTicks.some(tick => tick.labelBBox.width > textWidth)) {
correctByWidth = true
}
}
if (textHeight) {
if (this._majorTicks.some(tick => tick.labelBBox.height > textHeight)) {
correctByHeight = true
}
}
if (correctByWidth || correctByHeight) {
this._majorTicks.forEach(tick => {
tick.label && tick.label.setMaxSize(textWidth, textHeight, options.label)
});
(0, _axes_utils.measureLabels)(this._majorTicks)
}
}
}
animate() {
callAction(this._majorTicks, "animateLabels")
}
updateSize(canvas, animate) {
let updateTitle = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : true;
this.updateCanvas(canvas);
if (updateTitle) {
this._checkTitleOverflow();
this._measureTitle();
this._updateTitleCoords()
}
this._reinitTranslator(this._getViewportRange());
this.applyMargins();
const animationEnabled = !this._firstDrawing && animate;
const options = this._options;
initTickCoords(this._majorTicks);
initTickCoords(this._minorTicks);
initTickCoords(this._boundaryTicks);
if (this._resetApplyingAnimation && !this._firstDrawing) {
this._resetStartCoordinates()
}
cleanUpInvalidTicks(this._majorTicks);
cleanUpInvalidTicks(this._minorTicks);
cleanUpInvalidTicks(this._boundaryTicks);
if (this._axisElement) {
this._updateAxisElementPosition()
}
updateTicksPosition(this._majorTicks, options.tick, animationEnabled);
updateTicksPosition(this._minorTicks, options.minorTick, animationEnabled);
updateTicksPosition(this._boundaryTicks, options.tick);
callAction(this._majorTicks, "updateLabelPosition", animationEnabled);
this._outsideConstantLines.concat(this._insideConstantLines || []).forEach(l => l.updatePosition(animationEnabled));
callAction(this._strips, "updatePosition", animationEnabled);
updateGridsPosition(this._majorTicks, animationEnabled);
updateGridsPosition(this._minorTicks, animationEnabled);
if (animationEnabled) {
callAction(this._ticksToRemove || [], "fadeOutElements")
}
this.prepareAnimation();
this._ticksToRemove = null;
if (!this._translator.getBusinessRange().isEmpty()) {
this._firstDrawing = false
}
this._resetApplyingAnimation = false;
this._updateLabelsPosition()
}
prepareAnimation() {
const action = "saveCoords";
callAction(this._majorTicks, action);
callAction(this._minorTicks, action);
callAction(this._insideConstantLines, action);
callAction(this._outsideConstantLines, action);
callAction(this._strips, action)
}
_resetStartCoordinates() {
const action = "resetCoordinates";
callAction(this._majorTicks, action);
callAction(this._minorTicks, action);
callAction(this._insideConstantLines, action);
callAction(this._outsideConstantLines, action);
callAction(this._strips, action)
}
applyClipRects(elementsClipID, canvasClipID) {
this._axisGroup.attr({
"clip-path": canvasClipID
});
this._axisStripGroup.attr({
"clip-path": elementsClipID
});
this._axisElementsGroup.attr({
"clip-path": canvasClipID
})
}
_validateVisualRange(optionValue) {
const range = (0, _utils.getVizRangeObject)(optionValue);
if (void 0 !== range.startValue) {
range.startValue = this.validateUnit(range.startValue)
}
if (void 0 !== range.endValue) {
range.endValue = this.validateUnit(range.endValue)
}
return (0, _utils.convertVisualRangeObject)(range, !_isArray(optionValue))
}
_validateOptions(options) {
options.wholeRange = this._validateVisualRange(options.wholeRange);
options.visualRange = options._customVisualRange = this._validateVisualRange(options._customVisualRange);
this._setVisualRange(options._customVisualRange)
}
validate() {
const options = this._options;
const dataType = this.isArgumentAxis ? options.argumentType : options.valueType;
const parser = dataType ? (0, _parse_utils.getParser)(dataType) : function(unit) {
return unit
};
this.parser = parser;
options.dataType = dataType;
this._validateOptions(options)
}
resetVisualRange(isSilent) {
this._seriesData.minVisible = this._seriesData.min;
this._seriesData.maxVisible = this._seriesData.max;
this.handleZooming([null, null], {
start: !!isSilent,
end: !!isSilent
})
}
_setVisualRange(visualRange, allowPartialUpdate) {
const range = this.adjustRange((0, _utils.getVizRangeObject)(visualRange));
if (allowPartialUpdate) {
(0, _m_type.isDefined)(range.startValue) && (this._viewport.startValue = range.startValue);
(0, _m_type.isDefined)(range.endValue) && (this._viewport.endValue = range.endValue)
} else {
this._viewport = range
}
}
_applyZooming(visualRange, allowPartialUpdate) {
this._resetVisualRangeOption();
this._setVisualRange(visualRange, allowPartialUpdate);
const viewPort = this.getViewport();
this._seriesData.userBreaks = this._getScaleBreaks(this._options, {
minVisible: viewPort.startValue,
maxVisible: viewPort.endValue
}, this._series, this.isArgumentAxis);
this._translator.updateBusinessRange(this._getViewportRange())
}
getZoomStartEventArg(event, actionType) {
return {
axis: this,
range: this.visualRange(),
cancel: false,
event: event,
actionType: actionType
}
}
_getZoomEndEventArg(previousRange, event, actionType, zoomFactor, shift) {
const newRange = this.visualRange();
return {
axis: this,
previousRange: previousRange,
range: newRange,
cancel: false,
event: event,
actionType: actionType,
zoomFactor: zoomFactor,
shift: shift,
rangeStart: newRange.startValue,
rangeEnd: newRange.endValue
}
}
getZoomBounds() {
const wholeRange = (0, _utils.getVizRangeObject)(this._options.wholeRange);
const range = this.getTranslator().getBusinessRange();
const secondPriorityRange = {
startValue: getZoomBoundValue(this._initRange.startValue, range.min),
endValue: getZoomBoundValue(this._initRange.endValue, range.max)
};
return {
startValue: getZoomBoundValue(wholeRange.startValue, secondPriorityRange.startValue),
endValue: getZoomBoundValue(wholeRange.endValue, secondPriorityRange.endValue)
}
}
setInitRange() {
this._initRange = {};
if (0 === Object.keys(this._options.wholeRange || {}).length) {
this._initRange = this.getZoomBounds()
}
}
_resetVisualRangeOption() {
this._options._customVisualRange = {}
}
getTemplatesGroups() {
const ticks = this._majorTicks;
if (ticks) {
return this._majorTicks.map(tick => tick.templateContainer).filter(item => (0, _m_type.isDefined)(item))
} else {
return []
}
}
setCustomVisualRange(range) {
this._options._customVisualRange = range
}
visualRange() {
const args = arguments;
let visualRange;
if (0 === args.length) {
const adjustedRange = this._getAdjustedBusinessRange();
let startValue = adjustedRange.minVisible;
let endValue = adjustedRange.maxVisible;
if (this._options.type === _axes_constants.default.discrete) {
startValue = startValue ?? adjustedRange.categories[0];
endValue = endValue ?? adjustedRange.categories[adjustedRange.categories.length - 1];
return {
startValue: startValue,
endValue: endValue,
categories: (0, _utils.getCategoriesInfo)(adjustedRange.categories, startValue, endValue).categories
}
}
return {
startValue: startValue,
endValue: endValue
}
} else if (_isArray(args[0])) {
visualRange = args[0]
} else if ((0, _m_type.isPlainObject)(args[0])) {
visualRange = (0, _m_extend.extend)({}, args[0])
} else {
visualRange = [args[0], args[1]]
}
const zoomResults = this.handleZooming(visualRange, args[1]);
if (!zoomResults.isPrevented) {
this._visualRange(this, zoomResults)
}
}
handleZooming(visualRange, preventEvents, domEvent, action) {
preventEvents = preventEvents || {};
if ((0, _m_type.isDefined)(visualRange)) {
visualRange = this._validateVisualRange(visualRange);
visualRange.action = action
}
const zoomStartEvent = this.getZoomStartEventArg(domEvent, action);
const previousRange = zoomStartEvent.range;
!preventEvents.start && this._eventTrigger("zoomStart", zoomStartEvent);
const zoomResults = {
isPrevented: zoomStartEvent.cancel,
skipEventRising: preventEvents.skipEventRising,
range: visualRange || zoomStartEvent.range
};
if (!zoomStartEvent.cancel) {
(0, _m_type.isDefined)(visualRange) && this._applyZooming(visualRange, preventEvents.allowPartialUpdate);
if (!(0, _m_type.isDefined)(this._storedZoomEndParams)) {
this._storedZoomEndParams = {
startRange: previousRange,
type: this.getOptions().type
}
}
this._storedZoomEndParams.event = domEvent;
this._storedZoomEndParams.action = action;
this._storedZoomEndParams.prevent = !!preventEvents.end
}
return zoomResults
}
handleZoomEnd() {
if ((0, _m_type.isDefined)(this._storedZoomEndParams) && !this._storedZoomEndParams.prevent) {
const previousRange = this._storedZoomEndParams.startRange;
const domEvent = this._storedZoomEndParams.event;
const action = this._storedZoomEndParams.action;
const previousBusinessRange = {
minVisible: previousRange.startValue,
maxVisible: previousRange.endValue,
categories: previousRange.categories
};
const typeIsNotChanged = this.getOptions().type === this._storedZoomEndParams.type;
const shift = typeIsNotChanged ? (0, _m_math.adjust)(this.getVisualRangeCenter() - this.getVisualRangeCenter(previousBusinessRange, false)) : NaN;
const calcZoomFactor = () => {
if ("pan" === action) {
return 1
}
const currentLength = this.getVisualRangeLength() || 1;
const ratio = this.getVisualRangeLength(previousBusinessRange) / currentLength;
return Math.round((0, _m_math.multiplyInExponentialForm)(ratio, 2)) / 100
};
const zoomFactor = typeIsNotChanged ? calcZoomFactor() : NaN;
const zoomEndEvent = this._getZoomEndEventArg(previousRange, domEvent, action, zoomFactor, shift);
zoomEndEvent.cancel = this.checkZoomingLowerLimitOvercome(1 === zoomFactor ? "pan" : "zoom", zoomFactor).stopInteraction;
this._eventTrigger("zoomEnd", zoomEndEvent);
if (zoomEndEvent.cancel) {
this._restorePreviousVisualRange(previousRange)
}
this._storedZoomEndParams = null
}
}
_restorePreviousVisualRange(previousRange) {
this._storedZoomEndParams = null;
this._applyZooming(previousRange);
this._visualRange(this, previousRange)
}
checkZoomingLowerLimitOvercome(actionType, zoomFactor, range) {
const options = this._options;
const translator = this._translator;
let minZoom = options.minVisualRangeLength;
let correctedRange = range;
let visualRange;
let isOvercoming = "zoom" === actionType && zoomFactor >= 1;
const businessRange = translator.getBusinessRange();
if (range) {
visualRange = this.adjustRange((0, _utils.getVizRangeObject)(range));
visualRange = {
minVisible: visualRange.startValue,
maxVisible: visualRange.endValue,
categories: businessRange.categories
}
}
const beforeVisualRangeLength = this.getVisualRangeLength(businessRange);
const afterVisualRangeLength = this.getVisualRangeLength(visualRange);
if ((0, _m_type.isDefined)(minZoom) || "discrete" === options.type) {
minZoom = translator.convert(minZoom);
if (visualRange && minZoom < beforeVisualRangeLength && minZoom >= afterVisualRangeLength) {
correctedRange = (0, _utils.getVizRangeObject)(translator.getRangeByMinZoomValue(minZoom, visualRange));
isOvercoming = false
} else {
isOvercoming &= minZoom > afterVisualRangeLength
}
} else {
const canvasLength = this._translator.canvasLength;
const fullRange = {
minVisible: businessRange.min,
maxVisible: businessRange.max,
categories: businessRange.categories
};
isOvercoming &= this.getVisualRangeLength(fullRange) / canvasLength >= afterVisualRangeLength
}
return {
stopInteraction: !!isOvercoming,
correctedRange: correctedRange
}
}
isExtremePosition(isMax) {
let extremeDataValue;
let seriesData;
if ("discrete" === this._options.type) {
seriesData = this._translator.getBusinessRange();
extremeDataValue = isMax ? seriesData.categories[seriesData.categories.length - 1] : seriesData.categories[0]
} else {
seriesData = this.getZoomBounds();
extremeDataValue = isMax ? seriesData.endValue : seriesData.startValue
}
const translator = this.getTranslator();
const extremePoint = translator.translate(extremeDataValue);
const visualRange = this.visualRange();
const visualRangePoint = isMax ? translator.translate(visualRange.endValue) : translator.translate(visualRange.startValue);
return _abs(visualRangePoint - extremePoint) < 5
}
getViewport() {
return this._viewport
}
getFullTicks() {
const majors = this._majorTicks || [];
if (this._options.type === _axes_constants.default.discrete) {
return convertTicksToValues(majors)
} else {
return convertTicksToValues(majors.concat(this._minorTicks, this._boundaryTicks)).sort((a, b) => (0, _utils.valueOf)(a) - (0, _utils.valueOf)(b))
}
}
measureLabels(canvas, withIndents) {
const options = this._options;
const widthAxis = options.visible ? options.width : 0;
let ticks;
const indent = withIndents ? options.label.indentFromAxis + .5 * options.tick.length : 0;
let tickInterval;
const viewportRange = this._getViewportRange();
if (viewportRange.isEmpty() || !options.label.visible || !this._axisElementsGroup) {
return {
height: widthAxis,
width: widthAxis,
x: 0,
y: 0
}
}
if (this._majorTicks) {
ticks = convertTicksToValues(this._majorTicks)
} else {
this.updateCanvas(canvas);
ticks = this._createTicksAndLabelFormat(viewportRange, _m_common.noop);
tickInterval = ticks.tickInterval;
ticks = ticks.ticks
}
const maxText = ticks.reduce((prevLabel, tick, index) => {
const label = this.formatLabel(tick, options.label, viewportRange, void 0, tickInterval, ticks);
if (prevLabel.length < label.length) {
return label
} else {
return prevLabel
}
}, this.formatLabel(ticks[0], options.label, viewportRange, void 0, tickInterval, ticks));
const text = this._renderer.text(maxText, 0, 0).css(this._textFontStyles).attr(this._textOptions).append(this._renderer.root);
const box = text.getBBox();
text.remove();
return {
x: box.x,
y: box.y,
width: box.width + indent,
height: box.height + indent
}
}
_setLabelsPlacement() {
if (!this._options.label.visible) {
return
}
const labelOpt = this._options.label;
const displayMode = this._validateDisplayMode(labelOpt.displayMode);
const overlappingMode = this._validateOverlappingMode(labelOpt.overlappingBehavior, displayMode);
const ignoreOverlapping = "none" === overlappingMode || "ignore" === overlappingMode;
const behavior = {
rotationAngle: labelOpt.rotationAngle,
staggeringSpacing: labelOpt.staggeringSpacing
};
let notRecastStep;
const boxes = this._majorTicks.map(tick => tick.labelBBox);
let step = this._getStep(boxes);
switch (displayMode) {
case ROTATE:
if (ignoreOverlapping) {
notRecastStep = true;
step = 1
}
this._applyLabelMode(displayMode, step, boxes, labelOpt, notRecastStep);
break;
case "stagger":
if (ignoreOverlapping) {
step = 2
}
this._applyLabelMode(displayMode, _max(step, 2), boxes, labelOpt);
break;
default:
this._applyLabelOverlapping(boxes, overlappingMode, step, behavior)
}
}
_applyLabelOverlapping(boxes, mode, step, behavior) {
const labelOpt = this._options.label;
const majorTicks = this._majorTicks;
if ("none" === mode || "ignore" === mode) {
return
}
if (step > 1 && boxes.some(function(box, index, array) {
if (0 === index) {
return false
}
return _axes_constants.default.areLabelsOverlap(box, array[index - 1], labelOpt.minSpacing, labelOpt.alignment)
})) {
this._applyLabelMode(mode, step, boxes, behavior)
}
this._checkBoundedLabelsOverlapping(majorTicks, boxes, mode);
this._checkShiftedLabels(majorTicks, boxes, labelOpt.minSpacing, labelOpt.alignment)
}
_applyLabelMode(mode, step, boxes, behavior, notRecastStep) {
const majorTicks = this._majorTicks;
const labelOpt = this._options.label;
const angle = behavior.rotationAngle;
let labelHeight;
let alignment;
let func;
switch (mode) {
case ROTATE:
if (!labelOpt.userAlignment) {
alignment = angle < 0 ? RIGHT : LEFT;
if (angle % 90 === 0) {
alignment = CENTER
}
}
step = notRecastStep ? step : this._getStep(boxes, angle);
func = function(tick) {
const contentContainer = tick.getContentContainer();
if (!contentContainer) {
return
}
contentContainer.rotate(angle);
tick.labelRotationAngle = angle;
alignment && (tick.labelAlignment = alignment)
};
updateLabels(majorTicks, step, func);
break;
case "stagger":
labelHeight = this._getMaxLabelHeight(boxes, behavior.staggeringSpacing);
func = function(tick, index) {
if (index / (step - 1) % 2 !== 0) {
tick.labelOffset = labelHeight
}
};
updateLabels(majorTicks, step - 1, func);
break;
case "auto":
case "_auto":
if (2 === step) {
this._applyLabelMode("stagger", step, boxes, behavior)
} else {
this._applyLabelMode(ROTATE, step, boxes, {
rotationAngle: getOptimalAngle(boxes, labelOpt)
})
}
break;
default:
updateLabels(majorTicks, step)
}
}
_createTranslator() {
return new _translator2d.Translator2D({}, {}, {})
}
_updateTranslator() {
const translator = this._translator;
translator.update(translator.getBusinessRange(), this._canvas || {}, this._getTranslatorOptions())
}
_getTranslatorOptions() {
var _options$workWeek2, _options$breakStyle;
const options = this._options;
return {
isHorizontal: this._isHorizontal,
shiftZeroValue: !this.isArgumentAxis,
interval: options.semiDiscreteInterval,
firstDayOfWeek: null === (_options$workWeek2 = options.workWeek) || void 0 === _options$workWeek2 ? void 0 : _options$workWeek2[0],
stick: this._getStick(),
breaksSize: (null === (_options$breakStyle = options.breakStyle) || void 0 === _options$breakStyle ? void 0 : _options$breakStyle.width) ?? 0
}
}
getVisibleArea() {
const canvas = this._getCanvasStartEnd();
return [canvas.start, canvas.end].sort((a, b) => a - b)
}
_getCanvasStartEnd() {
const isHorizontal = this._isHorizontal;
const canvas = this._canvas || {};
const invert = this._translator.getBusinessRange().invert;
const coords = isHorizontal ? [canvas.left, canvas.width - canvas.right] : [canvas.height - canvas.bottom, canvas.top];
invert && coords.reverse();
return {
start: coords[0],
end: coords[1]
}
}
_getScreenDelta() {
const canvas = this._getCanvasStartEnd();
const breaks = this._seriesData ? this._seriesData.breaks || [] : [];
const breaksLength = breaks.length;
const screenDelta = _abs(canvas.start - canvas.end);
return screenDelta - (breaksLength ? breaks[breaksLength - 1].cumulativeWidth : 0)
}
_getScaleBreaks() {
return []
}
_filterBreaks() {
return []
}
applyVisualRangeSetter(visualRangeSetter) {
this._visualRange = visualRangeSetter
}
getCategoriesSorter(argCategories) {
let sort;
if (this.isArgumentAxis) {
sort = argCategories
} else {
const categoriesSortingMethod = this._options.categoriesSortingMethod;
sort = categoriesSortingMethod ?? this._options.categories
}
return sort
}
_getAdjustedBusinessRange() {
return this.adjustViewport(this._translator.getBusinessRange())
}
};
Object.assign(Axis.prototype, {
getOrthogonalAxis: _m_common.noop,
getCustomPosition: _m_common.noop,
getCustomBoundaryPosition: _m_common.noop,
resolveOverlappingForCustomPositioning: _m_common.noop,
_disposeBreaksGroup: _m_common.noop,
_measureTitle: _m_common.noop,
_updateLabelsPosition: _m_common.noop,
getMarkerTrackers: _m_common.noop,
_drawDateMarkers: _m_common.noop,
_adjustDateMarkers: _m_common.noop,
coordsIn: _m_common.noop,
areCoordsOutsideAxis: _m_common.noop,
_getSkippedCategory: _m_common.noop,
_initAxisPositions: _m_common.noop,
_drawTitle: _m_common.noop,
_updateTitleCoords: _m_common.noop,
_adjustConstantLineLabels: _m_common.noop,
_adjustTitle: _m_common.noop,
_checkTitleOverflow: _m_common.noop,
getSpiderTicks: _m_common.noop,
setSpiderTicks: _m_common.noop,
_checkBoundedLabelsOverlapping: _m_common.noop,
_checkShiftedLabels: _m_common.noop,
drawScaleBreaks: _m_common.noop,
_visualRange: _m_common.noop,
_rotateConstantLine: _m_common.noop
});