@cursorify/react
Version:
Customizable cursor component for any style 🕹️
84 lines (83 loc) • 2.8 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const react_1 = require("react");
const __1 = require("..");
/*
const getCursorStyleFromTagName = (tagName: string): CursorStyle => {
switch (tagName) {
case 'A':
return 'pointer'
case 'P':
case 'H1':
case 'H2':
case 'H3':
case 'H4':
case 'H5':
case 'H6':
case 'SPAN':
return 'text'
default:
return 'default'
}
}
*/
const useMouseMoveEffect = (mouseRef) => {
const { delay, opacity } = (0, __1.useCursorifyState)();
const dispatch = (0, __1.useCursorifyDispatch)();
const endX = (0, react_1.useRef)(0);
const endY = (0, react_1.useRef)(0);
const _x = (0, react_1.useRef)(null);
const _y = (0, react_1.useRef)(null);
const requestRef = (0, react_1.useRef)(0);
const animateMouse = () => {
if (mouseRef.current === null)
return;
if (_x.current !== null && _y.current !== null) {
_x.current += (endX.current - _x.current) / delay;
_y.current += (endY.current - _y.current) / delay;
mouseRef.current.style.opacity = `${opacity}`;
mouseRef.current.style.transform = `translate(-50%, -50%) translate3d(${_x.current}px, ${_y.current}px, 0)`;
}
requestRef.current = requestAnimationFrame(animateMouse);
};
const handleMouseMove = (e) => {
if (mouseRef.current === null)
return;
endX.current = e.clientX;
endY.current = e.clientY;
if (_x.current === null || _y.current === null) {
_x.current = endX.current;
_y.current = endY.current;
mouseRef.current.style.opacity = `${opacity}`;
mouseRef.current.style.transform = `translate(-50%, -50%) translate3d(${_x.current}px, ${_y.current}px, 0)`;
}
if (!(e.target instanceof HTMLElement))
return;
let cursorStyle = 'default';
let currentElement = e.target;
while (currentElement) {
const _cursorStyle = currentElement.style.cursor;
if (_cursorStyle) {
cursorStyle = _cursorStyle;
break;
}
currentElement = currentElement.parentElement;
}
dispatch({
type: 'UPDATE_STYLE',
payload: cursorStyle,
});
};
(0, react_1.useEffect)(() => {
if (!mouseRef.current)
return;
animateMouse();
window.addEventListener('mousemove', handleMouseMove);
return () => {
window.removeEventListener('mousemove', handleMouseMove);
cancelAnimationFrame(requestRef.current);
};
}, [delay, opacity]);
return mouseRef;
};
exports.default = useMouseMoveEffect;