style: corrected the positioning of the charts tooltip (#2402)

* style: corrected the positioning of the charts tooltip

* style: stored value for pixel in variable

* chore: logic is shifted to plugin

---------

Co-authored-by: palashgdev <palashgdev@gmail.com>
This commit is contained in:
Mary Ojo 2023-02-28 08:46:31 +00:00 committed by GitHub
parent 80cd317b3b
commit b0d5b15330
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 56 additions and 0 deletions

View File

@ -0,0 +1,46 @@
import {
ActiveElement,
ChartTypeRegistry,
Point,
TooltipModel,
TooltipXAlignment,
TooltipYAlignment,
} from 'chart.js';
export function TooltipPosition(
this: TooltipModel<keyof ChartTypeRegistry>,
_: readonly ActiveElement[],
eventPosition: Point,
): ITooltipPosition {
const {
chartArea: { width },
scales: { x, y },
} = this.chart;
const valueForPixelOnX = Number(x.getValueForPixel(eventPosition.x));
const valueForPixelonY = Number(y.getValueForPixel(eventPosition.y));
const rightmostWidth = this.width + x.getPixelForValue(valueForPixelOnX) + 20;
if (rightmostWidth > width) {
return {
x: x.getPixelForValue(valueForPixelOnX) - 20,
y: y.getPixelForValue(valueForPixelonY) + 10,
xAlign: 'right',
yAlign: 'top',
};
}
return {
x: x.getPixelForValue(valueForPixelOnX) + 20,
y: y.getPixelForValue(valueForPixelonY) + 10,
xAlign: 'left',
yAlign: 'top',
};
}
interface ITooltipPosition {
x: number;
y: number;
xAlign: TooltipXAlignment;
yAlign: TooltipYAlignment;
}

View File

@ -44,6 +44,7 @@ import {
intersectionCursorPluginId,
IntersectionCursorPluginOptions,
} from './Plugin/IntersectionCursor';
import { TooltipPosition as TooltipPositionHandler } from './Plugin/Tooltip';
import { LegendsContainer } from './styles';
import { useXAxisTimeUnit } from './xAxisConfig';
import { getToolTipValue, getYAxisFormattedValue } from './yAxisConfig';
@ -67,6 +68,8 @@ Chart.register(
annotationPlugin,
);
Tooltip.positioners.custom = TooltipPositionHandler;
function Graph({
animate = true,
data,
@ -177,6 +180,7 @@ function Graph({
return 'rgba(255, 255, 255, 0.75)';
},
},
position: 'custom',
},
[dragSelectPluginId]: createDragSelectPluginOptions(
!!onDragSelect,
@ -324,6 +328,12 @@ function Graph({
);
}
declare module 'chart.js' {
interface TooltipPositionerMap {
custom: TooltipPositionerFunction<ChartType>;
}
}
type CustomChartOptions = ChartOptions & {
plugins: {
[dragSelectPluginId]: DragSelectPluginOptions | false;