All files / platform/core/src/hooks useViewportMousePosition.ts

90.47% Statements 19/21
83.33% Branches 5/6
83.33% Functions 5/6
90.47% Lines 19/21

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68                          772x 772x   772x               772x 500x 3x     497x 182x         182x 182x   182x   182x   182x 7x     182x                 497x   497x 463x       772x          
import { useState, useEffect } from 'react';
import { useViewportRef } from './useViewportRef';
import { useViewportSize } from './useViewportSize';
 
interface MousePosition {
  x: number;
  y: number;
  isInViewport: boolean;
  relativeY: number; // Position as percentage from top (0-1)
  isInBottomPercentage: (percentage: number) => boolean;
}
 
function useViewportMousePosition(viewportId: string): MousePosition {
  const viewportRef = useViewportRef(viewportId);
  const { height, clientRect } = useViewportSize(viewportId);
 
  const [mousePosition, setMousePosition] = useState<MousePosition>({
    x: 0,
    y: 0,
    isInViewport: false,
    relativeY: 0,
    isInBottomPercentage: (percentage: number) => false,
  });
 
  useEffect(() => {
    if (!viewportRef.current) {
      return;
    }
 
    const handleMouseMove = (event: MouseEvent) => {
      Iif (!clientRect) {
        return;
      }
 
      // Get mouse position relative to viewport
      const x = event.clientX - clientRect.left;
      const y = event.clientY - clientRect.top;
 
      const isInViewport = x >= 0 && x <= clientRect.width && y >= 0 && y <= clientRect.height;
 
      const relativeY = Math.max(0, Math.min(1, y / height));
 
      const isInBottomPercentage = (percentage: number) => {
        return relativeY >= 1 - percentage / 100;
      };
 
      setMousePosition({
        x,
        y,
        isInViewport,
        relativeY,
        isInBottomPercentage,
      });
    };
 
    document.addEventListener('mousemove', handleMouseMove);
 
    return () => {
      document.removeEventListener('mousemove', handleMouseMove);
    };
  }, [viewportRef, height, clientRect]);
 
  return mousePosition;
}
 
export default useViewportMousePosition;
export { useViewportMousePosition };