Files
headlessui/packages/@headlessui-react/src/hooks/use-tracked-pointer.ts
T
Jordan Pittman 2e941f85dd Ignore mouse move/leave events when the cursor hasn’t moved (#2069)
* Ignore mouse move/leave events when the cursor hasn’t moved

A mouse enter / leave event where the cursor hasn’t moved happen only because of:
- Scrolling
- The container moved

* Fix linting errors

* Update changelog

* wip

* Fix tests

* fix linting error

* Tweak tests to bypass tracked pointer checks

* Fixup

* Add stuff

* Fix build script

* fix stuff

* wip
2022-12-07 13:50:57 -05:00

36 lines
1005 B
TypeScript

import { useRef } from 'react'
type PointerPosition = [x: number, y: number]
function eventToPosition(evt: PointerEvent): PointerPosition {
return [evt.screenX, evt.screenY]
}
export function useTrackedPointer() {
let lastPos = useRef<PointerPosition>([-1, -1])
return {
wasMoved(evt: PointerEvent) {
// FIXME: Remove this once we use browser testing in all the relevant places.
// NOTE: This is replaced with a compile-time define during the build process
// This hack exists to work around a few failing tests caused by our inability to "move" the virtual pointer in JSDOM pointer events.
if (process.env.TEST_BYPASS_TRACKED_POINTER) {
return true
}
let newPos = eventToPosition(evt)
if (lastPos.current[0] === newPos[0] && lastPos.current[1] === newPos[1]) {
return false
}
lastPos.current = newPos
return true
},
update(evt: PointerEvent) {
lastPos.current = eventToPosition(evt)
},
}
}