Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(useMouse): position won't be changed on page scroll when type is page, closes #2922 #3244

Merged
merged 4 commits into from Aug 25, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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