@mui/x-charts
Version:
The community edition of the Charts components (MUI X).
92 lines (91 loc) • 2.27 kB
JavaScript
import * as React from 'react';
import { useSvgRef } from '../hooks';
export function generateVirtualElement(mousePosition) {
if (mousePosition === null) {
return {
getBoundingClientRect: () => ({
width: 0,
height: 0,
x: 0,
y: 0,
top: 0,
right: 0,
bottom: 0,
left: 0,
toJSON: () => ''
})
};
}
const {
x,
y
} = mousePosition;
return {
getBoundingClientRect: () => ({
width: 0,
height: 0,
x,
y,
top: y,
right: x,
bottom: y,
left: x,
toJSON: () => JSON.stringify({
width: 0,
height: 0,
x,
y,
top: y,
right: x,
bottom: y,
left: x
})
})
};
}
export function useMouseTracker() {
const svgRef = useSvgRef();
// Use a ref to avoid rerendering on every mousemove event.
const [mousePosition, setMousePosition] = React.useState(null);
React.useEffect(() => {
const element = svgRef.current;
if (element === null) {
return () => {};
}
const handleOut = () => {
setMousePosition(null);
};
const handleMove = event => {
const target = 'targetTouches' in event ? event.targetTouches[0] : event;
setMousePosition({
x: target.clientX,
y: target.clientY
});
};
element.addEventListener('mouseout', handleOut);
element.addEventListener('mousemove', handleMove);
element.addEventListener('touchend', handleOut);
element.addEventListener('touchmove', handleMove);
return () => {
element.removeEventListener('mouseout', handleOut);
element.removeEventListener('mousemove', handleMove);
element.addEventListener('touchend', handleOut);
element.addEventListener('touchmove', handleMove);
};
}, [svgRef]);
return mousePosition;
}
export function getTooltipHasData(trigger, displayedData) {
if (trigger === 'item') {
return displayedData !== null;
}
const hasAxisXData = displayedData.x !== null;
const hasAxisYData = displayedData.y !== null;
return hasAxisXData || hasAxisYData;
}
export function utcFormatter(v) {
if (v instanceof Date) {
return v.toUTCString();
}
return v.toLocaleString();
}