@mui/x-charts
Version:
The community edition of MUI X Charts components.
44 lines (43 loc) • 1.57 kB
JavaScript
import { isOrdinalScale } from "../../../scaleGuards.mjs";
import { getAsNumber } from "../../../getAsNumber.mjs";
import { findClosestIndex } from "../../../findClosestIndex.mjs";
/**
* For a pointer coordinate, this function returns the dataIndex associated.
* Returns `-1` if no dataIndex matches.
*/
export function getAxisIndex(axisConfig, pointerValue) {
const {
scale,
data: axisData,
reverse
} = axisConfig;
if (!isOrdinalScale(scale)) {
if (axisData === undefined) {
return -1;
}
const valueAsNumber = getAsNumber(scale.invert(pointerValue));
return findClosestIndex(axisData, valueAsNumber);
}
const dataIndex = scale.bandwidth() === 0 ? Math.floor((pointerValue - Math.min(...scale.range()) + scale.step() / 2) / scale.step()) : Math.floor((pointerValue - Math.min(...scale.range())) / scale.step());
if (dataIndex < 0 || dataIndex >= axisData.length) {
return -1;
}
return reverse ? axisData.length - 1 - dataIndex : dataIndex;
}
/**
* For a pointer coordinate, this function returns the value associated.
* Returns `null` if the coordinate has no value associated.
*/
export function getAxisValue(scale, axisData, pointerValue, dataIndex) {
if (!isOrdinalScale(scale)) {
if (dataIndex === null) {
const invertedValue = scale.invert(pointerValue);
return Number.isNaN(invertedValue) ? null : invertedValue;
}
return axisData[dataIndex];
}
if (dataIndex === null || dataIndex < 0 || dataIndex >= axisData.length) {
return null;
}
return axisData[dataIndex];
}