Skip to content

Commit

Permalink
feat(onLongClick): return stop function (#3506)
Browse files Browse the repository at this point in the history
Co-authored-by: lee <lee@feeditback.co.uk>
  • Loading branch information
its-lee and lee committed Nov 9, 2023
1 parent 9b0141c commit 8eb0b2d
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
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
}

0 comments on commit 8eb0b2d

Please sign in to comment.