@mui/x-charts
Version:
The community edition of MUI X Charts components.
82 lines (80 loc) • 2.6 kB
JavaScript
import { isOrdinalScale } from "../../../scaleGuards.mjs";
import { getAsNumber } from "../../../getAsNumber.mjs";
import { findClosestIndex } from "../../../findClosestIndex.mjs";
import { clampAngleRad } from "../../../clampAngle.mjs";
/**
* For a pointer coordinate, this function returns the value and dataIndex associated.
* Returns `-1` if the coordinate does not match a value.
*/
export function getRotationAxisIndex(axisConfig, pointerValue) {
const {
scale,
data: axisData,
reverse,
isFullCircle
} = axisConfig;
const [startAngle, endAngle] = scale.range();
const angleGap = clampAngleRad(pointerValue - startAngle);
const maxAngleGap = clampAngleRad(endAngle - startAngle);
if (!isFullCircle && angleGap > maxAngleGap) {
// If not a full circle we only consider pointer inside the rotation range.
return -1;
}
if (!isOrdinalScale(scale)) {
if (axisData === undefined) {
return -1;
}
const angle = startAngle + clampAngleRad(pointerValue - startAngle);
const valueAsNumber = getAsNumber(scale.invert(angle));
return findClosestIndex(axisData, valueAsNumber);
}
if (!axisData) {
return -1;
}
let dataIndex;
if (scale.bandwidth() === 0) {
dataIndex = Math.floor((angleGap + scale.step() / 2) / scale.step());
if (isFullCircle) {
// To show dataIndex 0 when we are before the startAngle
dataIndex = dataIndex % axisData.length;
}
} else {
dataIndex = Math.floor(angleGap / 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 and dataIndex associated.
* Returns `-1` if the coordinate does not match a value.
*/
export function getRadiusAxisIndex(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);
}
if (!axisData) {
return -1;
}
let dataIndex;
const distFromStart = pointerValue - Math.min(...scale.range());
if (scale.bandwidth() === 0) {
dataIndex = Math.floor((distFromStart + scale.step() / 2) / scale.step());
} else {
dataIndex = Math.floor(distFromStart / scale.step());
}
if (dataIndex < 0 || dataIndex >= axisData.length) {
return -1;
}
return reverse ? axisData.length - 1 - dataIndex : dataIndex;
}