-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
index.ts
75 lines (59 loc) · 1.66 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import type { Fn } from '@vueuse/shared'
import { computed } from 'vue-demi'
import type { MaybeElementRef } from '../unrefElement'
import { unrefElement } from '../unrefElement'
import { useEventListener } from '../useEventListener'
const DEFAULT_DELAY = 500
export interface OnLongPressOptions {
/**
* Time in ms till `longpress` gets called
*
* @default 500
*/
delay?: number
modifiers?: OnLongPressModifiers
}
export interface OnLongPressModifiers {
stop?: boolean
once?: boolean
prevent?: boolean
capture?: boolean
self?: boolean
}
export function onLongPress(
target: MaybeElementRef,
handler: (evt: PointerEvent) => void,
options?: OnLongPressOptions,
) {
const elementRef = computed(() => unrefElement(target))
let timeout: ReturnType<typeof setTimeout> | undefined
function clear() {
if (timeout) {
clearTimeout(timeout)
timeout = undefined
}
}
function onDown(ev: PointerEvent) {
if (options?.modifiers?.self && ev.target !== elementRef.value)
return
clear()
if (options?.modifiers?.prevent)
ev.preventDefault()
if (options?.modifiers?.stop)
ev.stopPropagation()
timeout = setTimeout(
() => handler(ev),
options?.delay ?? DEFAULT_DELAY,
)
}
const listenerOptions: AddEventListenerOptions = {
capture: options?.modifiers?.capture,
once: options?.modifiers?.once,
}
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
}