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

feat(onLongClick): return stop function #3506

Merged
merged 1 commit into from Nov 9, 2023
Merged
Show file tree
Hide file tree
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
24 changes: 24 additions & 0 deletions packages/core/onLongPress/index.test.ts
Expand Up @@ -87,6 +87,29 @@ describe('onLongPress', () => {
expect(onParentLongPressCallback).toHaveBeenCalledTimes(0)
}

async function stopEventListeners(isRef: boolean) {
const onLongPressCallback = vi.fn()
const stop = onLongPress(isRef ? element : element.value, onLongPressCallback, { modifiers: { stop: true } })

// before calling stop, the callback should be called
element.value.dispatchEvent(pointerdownEvent)

await promiseTimeout(500)

expect(onLongPressCallback).toHaveBeenCalledTimes(1)

stop()

// before calling stop, the callback should no longer be called
onLongPressCallback.mockClear()

element.value.dispatchEvent(pointerdownEvent)

await promiseTimeout(500)

expect(onLongPressCallback).toHaveBeenCalledTimes(0)
}

function suites(isRef: boolean) {
describe('given no options', () => {
it('should trigger longpress after 500ms', () => triggerCallback(isRef))
Expand All @@ -97,6 +120,7 @@ describe('onLongPress', () => {
it('should not tirgger longpress when child element on longpress', () => notTriggerCallbackOnChildLongPress(isRef))
it('should work with once and prevent modifiers', () => workOnceAndPreventModifiers(isRef))
it('should stop propagation', () => stopPropagation(isRef))
it('should remove event listeners after being stopped', () => stopEventListeners(isRef))
})
}

Expand Down
11 changes: 9 additions & 2 deletions packages/core/onLongPress/index.ts
@@ -1,3 +1,4 @@
import type { Fn } from '@vueuse/shared'
import { computed } from 'vue-demi'
import type { MaybeElementRef } from '../unrefElement'
import { unrefElement } from '../unrefElement'
Expand Down Expand Up @@ -63,6 +64,12 @@ export function onLongPress(
once: options?.modifiers?.once,
}

useEventListener(elementRef, 'pointerdown', onDown, listenerOptions)
useEventListener(elementRef, ['pointerup', 'pointerleave'], clear, listenerOptions)
const cleanup = [
useEventListener(elementRef, 'pointerdown', onDown, listenerOptions),
useEventListener(elementRef, ['pointerup', 'pointerleave'], clear, listenerOptions),
].filter(Boolean) as Fn[]

const stop = () => cleanup.forEach(fn => fn())

return stop
}