export function getXCoordinateFromTimeResolved(
chart: IChartApi,
series: SeriesApi,
time: Time,
): Coordinate | null {
const directCoordinate = chart.timeScale().timeToCoordinate(time);
if (directCoordinate !== null) {
return directCoordinate;
}
if (typeof time !== 'number') {
return null;
}
const data = series.data() as readonly { time: Time }[];
if (data.length < 2) {
return null;
}
let leftIndex = -1;
let rightIndex = data.length;
while (leftIndex + 1 < rightIndex) {
const middleIndex = Math.floor((leftIndex + rightIndex) / 2);
const middleTime = data[middleIndex]?.time;
if (typeof middleTime !== 'number') {
return null;
}
if (middleTime <= time) {
leftIndex = middleIndex;
} else {
rightIndex = middleIndex;
}
}
if (leftIndex < 0 || rightIndex >= data.length) {
return null;
}
const leftPoint = data[leftIndex];
const rightPoint = data[rightIndex];
if (typeof leftPoint.time !== 'number' || typeof rightPoint.time !== 'number') {
return null;
}
const leftCoordinate = chart.timeScale().timeToCoordinate(leftPoint.time as Time);
const rightCoordinate = chart.timeScale().timeToCoordinate(rightPoint.time as Time);
if (leftCoordinate === null || rightCoordinate === null) {
return null;
}
if (leftPoint.time === rightPoint.time) {
return leftCoordinate;
}
const progress = (time - leftPoint.time) / (rightPoint.time - leftPoint.time);
return (Number(leftCoordinate) + (Number(rightCoordinate) - Number(leftCoordinate)) * progress) as Coordinate;
}