From 8eb0b2d7bb254150c8498afe747a7c1a5179b747 Mon Sep 17 00:00:00 2001 From: Lee Crosby Date: Thu, 9 Nov 2023 15:07:53 +0000 Subject: [PATCH] feat(onLongClick): return stop function (#3506) Co-authored-by: lee --- packages/core/onLongPress/index.test.ts | 24 ++++++++++++++++++++++++ packages/core/onLongPress/index.ts | 11 +++++++++-- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/packages/core/onLongPress/index.test.ts b/packages/core/onLongPress/index.test.ts index 8e51a919249..86d6a7f9107 100644 --- a/packages/core/onLongPress/index.test.ts +++ b/packages/core/onLongPress/index.test.ts @@ -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)) @@ -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)) }) } diff --git a/packages/core/onLongPress/index.ts b/packages/core/onLongPress/index.ts index eae6cdce882..86227fb31b7 100644 --- a/packages/core/onLongPress/index.ts +++ b/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' @@ -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 }