Skip to content

feat(onLongPress): allow function as value in delay #4979

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

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions packages/core/onLongPress/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@ describe('onLongPress', () => {
expect(onLongPressCallback).toHaveBeenCalledTimes(1)
}

async function triggerCallbackWithDelay(isRef: boolean) {
async function triggerCallbackWithDelay(isRef: boolean, delayFunc?: (ev: PointerEvent) => number) {
const onLongPressCallback = vi.fn()
onLongPress(isRef ? element : element.value, onLongPressCallback, { delay: 1000 })
onLongPress(isRef ? element : element.value, onLongPressCallback, { delay: delayFunc ?? 1000 })
// first pointer down
element.value.dispatchEvent(pointerdownEvent)

Expand Down Expand Up @@ -199,6 +199,7 @@ describe('onLongPress', () => {
it('should remove event listeners after being stopped', () => stopEventListeners(isRef))
it('should trigger longpress if pointer is moved', () => triggerCallbackWithThreshold(isRef))
it('should trigger onMouseUp when pointer is released', () => triggerOnMouseUp(isRef))
it('should trigger longpress after options.delay ms when options.delay is a function', () => triggerCallbackWithDelay(isRef, () => 1000))
})
}

Expand Down
12 changes: 10 additions & 2 deletions packages/core/onLongPress/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export interface OnLongPressOptions {
*
* @default 500
*/
delay?: number
delay?: number | ((ev: PointerEvent) => number)

modifiers?: OnLongPressModifiers

Expand Down Expand Up @@ -64,6 +64,14 @@ export function onLongPress(
hasLongPressed = false
}

function getDelay(ev: PointerEvent): number {
const delay = options?.delay
if (typeof delay === 'function') {
return delay(ev)
}
return delay ?? DEFAULT_DELAY
}

function onRelease(ev: PointerEvent) {
const [_startTimestamp, _posStart, _hasLongPressed] = [startTimestamp, posStart, hasLongPressed]
clear()
Expand Down Expand Up @@ -108,7 +116,7 @@ export function onLongPress(
hasLongPressed = true
handler(ev)
},
options?.delay ?? DEFAULT_DELAY,
getDelay(ev),
)
}

Expand Down