-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
index.ts
69 lines (55 loc) · 1.56 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
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: number | null = null
function clear() {
if (timeout != null) {
clearTimeout(timeout)
timeout = null
}
}
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,
) as unknown as number
}
const listenerOptions: AddEventListenerOptions = {
capture: options?.modifiers?.capture,
once: options?.modifiers?.once,
}
useEventListener(elementRef, 'pointerdown', onDown, listenerOptions)
useEventListener(elementRef, 'pointerup', clear, listenerOptions)
useEventListener(elementRef, 'pointerleave', clear, listenerOptions)
}