fix(BOOK-138): Fixed several issues after country map functionality was added
* fix(BOOK-138): Fixed issue when hovering markers and info windows for both city cluster marker as city markers. Approved-by: Matilda Landström
This commit is contained in:
49
packages/common/hooks/map/useMarkerHover.ts
Normal file
49
packages/common/hooks/map/useMarkerHover.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { useRef } from "react"
|
||||
|
||||
/**
|
||||
* Custom hook to manage hover state across marker and InfoWindow elements.
|
||||
* The Google Maps InfoWindow component does not natively support hover events.
|
||||
* This hook provides a way to track hover state across both elements simultaneously.
|
||||
*
|
||||
* This hook solves the problem where moving from a marker to its InfoWindow
|
||||
* causes the InfoWindow to close prematurely. It uses a counter to track
|
||||
* how many elements (marker, InfoWindow) are currently being hovered over.
|
||||
*
|
||||
* When moving from marker to InfoWindow, the InfoWindow's onMouseEnter fires
|
||||
* before the marker's onMouseLeave, causing the counter to correctly remain > 0.
|
||||
*
|
||||
* @param onHoverChange - Callback function that receives true when hovering starts, false when it ends
|
||||
* @returns Object with handleMouseEnter and handleMouseLeave functions
|
||||
*/
|
||||
export function useMarkerHover(onHoverChange: (isHovering: boolean) => void) {
|
||||
const hoverCountRef = useRef(0)
|
||||
|
||||
function handleMouseEnter() {
|
||||
hoverCountRef.current += 1
|
||||
|
||||
if (hoverCountRef.current >= 1) {
|
||||
onHoverChange(true)
|
||||
|
||||
// In case of rapid mouse movements, or close markers/info windows,
|
||||
// The counter can increase beyond 2, which is unnecessary. We reset
|
||||
// it to 1 which works to track hover state correctly.
|
||||
if (hoverCountRef.current > 2) {
|
||||
hoverCountRef.current = 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function handleMouseLeave() {
|
||||
hoverCountRef.current -= 1
|
||||
|
||||
if (hoverCountRef.current <= 0) {
|
||||
onHoverChange(false)
|
||||
hoverCountRef.current = 0
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
handleMouseEnter,
|
||||
handleMouseLeave,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user