Skip to content

Commit

Permalink
fix(useMouse): position won't be changed on page scroll when type i…
Browse files Browse the repository at this point in the history
…s `page`, closes #2922 (#3244)

Co-authored-by: Anthony Fu <anthonyfu117@hotmail.com>
  • Loading branch information
CatsJuice and antfu committed Aug 25, 2023
1 parent 1903fb5 commit c2f641d
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions packages/core/useMouse/index.ts
Expand Up @@ -31,6 +31,13 @@ export interface UseMouseOptions extends ConfigurableWindow, ConfigurableEventFi
*/
touch?: boolean

/**
* Listen to `scroll` events on window, only effective on type `page`
*
* @default true
*/
scroll?: boolean

/**
* Reset to initial value when `touchend` event fired
*
Expand Down Expand Up @@ -69,9 +76,12 @@ export function useMouse(options: UseMouseOptions = {}) {
initialValue = { x: 0, y: 0 },
window = defaultWindow,
target = window,
scroll = true,
eventFilter,
} = options

let _prevMouseEvent: MouseEvent | null = null

const x = ref(initialValue.x)
const y = ref(initialValue.y)
const sourceType = ref<UseMouseSourceType>(null)
Expand All @@ -82,6 +92,7 @@ export function useMouse(options: UseMouseOptions = {}) {

const mouseHandler = (event: MouseEvent) => {
const result = extractor(event)
_prevMouseEvent = event

if (result) {
[x.value, y.value] = result
Expand All @@ -99,6 +110,17 @@ export function useMouse(options: UseMouseOptions = {}) {
}
}

const scrollHandler = () => {
if (!_prevMouseEvent || !window)
return
const pos = extractor(_prevMouseEvent)

if (_prevMouseEvent instanceof MouseEvent && pos) {
x.value = pos[0] + window.scrollX
y.value = pos[1] + window.scrollY
}
}

const reset = () => {
x.value = initialValue.x
y.value = initialValue.y
Expand All @@ -112,6 +134,10 @@ export function useMouse(options: UseMouseOptions = {}) {
? (event: TouchEvent) => eventFilter(() => touchHandler(event), {} as any)
: (event: TouchEvent) => touchHandler(event)

const scrollHandlerWrapper = eventFilter
? () => eventFilter(() => scrollHandler(), {} as any)
: () => scrollHandler()

if (target) {
const listenerOptions = { passive: true }
useEventListener(target, ['mousemove', 'dragover'], mouseHandlerWrapper, listenerOptions)
Expand All @@ -120,6 +146,8 @@ export function useMouse(options: UseMouseOptions = {}) {
if (resetOnTouchEnds)
useEventListener(target, 'touchend', reset, listenerOptions)
}
if (scroll && type === 'page')
useEventListener(window, 'scroll', scrollHandlerWrapper, { passive: true })
}

return {
Expand Down

0 comments on commit c2f641d

Please sign in to comment.