-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpressHandler.js
More file actions
57 lines (49 loc) · 1.71 KB
/
pressHandler.js
File metadata and controls
57 lines (49 loc) · 1.71 KB
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
export class PressHandler {
#element; #startTime
onPress; onRelease
longPressDuration = 800;
#timer
/** @param {HTMLElement} element */
constructor(element) {
this.#element = element
this.active(true)
}
active(active) {
const addOrRemove = active ? 'addEventListener' : 'removeEventListener'
this.#element[addOrRemove]('contextmenu', this.#contextmenu)
this.#element[addOrRemove]('touchstart', this.#startPress, {passive: true})
this.#element[addOrRemove]('touchmove', this.#checkTouchPosition, {passive: true})
this.#element[addOrRemove]('touchend', this.#endPress)
this.#element[addOrRemove]('touchcancel', this.#endPress)
this.#startTime = null
}
#contextmenu = (event) => {
event.preventDefault() // prevent it on long press
}
#startPress = (event) => {
this.#startTime = performance.now()
this.onPress?.({element: this.#element, target: event.target, event})
if (this.longPressDuration) {
this.#timer = setTimeout(this.#endPress, this.longPressDuration, event)
}
}
#endPress = (event) => {
if (this.#startTime === null) return
clearTimeout(this.#timer)
const endTime = performance.now()
const pressDuration = endTime - this.#startTime
this.#startTime = null
this.onRelease({
element: this.#element, target: event.target, pressDuration,
longPress: pressDuration >= this.longPressDuration, event
})
}
#checkTouchPosition = (event) => {
if (this.#startTime === null) return
const touch = event.touches[0]
const touchedElement = document.elementFromPoint(touch.clientX, touch.clientY)
if (touchedElement && !this.#element.contains(touchedElement)) {
this.#endPress(event)
}
}
}