-
-
Notifications
You must be signed in to change notification settings - Fork 83
/
eventListeners.ts
88 lines (67 loc) · 2.73 KB
/
eventListeners.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
76
77
78
79
80
81
82
83
84
85
86
87
88
import { useEventListener } from '@vueuse/core'
import { computed, ref, unref, watch } from 'vue'
import type { MotionInstance, MotionVariants } from '../types'
import { supportsMouseEvents, supportsPointerEvents, supportsTouchEvents } from '../utils/events'
export function registerEventListeners<T extends string, V extends MotionVariants<T>>({ target, state, variants, apply }: MotionInstance<T, V>) {
const _variants = unref(variants)
// State
const hovered = ref(false)
const tapped = ref(false)
const focused = ref(false)
const mutableKeys = computed(() => {
let result: string[] = [...Object.keys(state.value || {})]
if (!_variants) return result
if (_variants.hovered) result = [...result, ...Object.keys(_variants.hovered)]
if (_variants.tapped) result = [...result, ...Object.keys(_variants.tapped)]
if (_variants.focused) result = [...result, ...Object.keys(_variants.focused)]
return result
})
const computedProperties = computed(() => {
const result: Partial<V> = {}
Object.assign(result, state.value)
if (hovered.value && _variants.hovered) Object.assign(result, _variants.hovered)
if (tapped.value && _variants.tapped) Object.assign(result, _variants.tapped)
if (focused.value && _variants.focused) Object.assign(result, _variants.focused)
for (const key in result) {
if (!mutableKeys.value.includes(key)) delete result[key]
}
return result
})
// Hovered
if (_variants.hovered) {
useEventListener(target as any, 'mouseenter', () => (hovered.value = true))
useEventListener(target as any, 'mouseleave', () => {
hovered.value = false
tapped.value = false
})
useEventListener(target as any, 'mouseout', () => {
hovered.value = false
tapped.value = false
})
}
// Tapped
if (_variants.tapped) {
// Mouse
if (supportsMouseEvents()) {
useEventListener(target as any, 'mousedown', () => (tapped.value = true))
useEventListener(target as any, 'mouseup', () => (tapped.value = false))
}
// Pointer
if (supportsPointerEvents()) {
useEventListener(target as any, 'pointerdown', () => (tapped.value = true))
useEventListener(target as any, 'pointerup', () => (tapped.value = false))
}
// Touch
if (supportsTouchEvents()) {
useEventListener(target as any, 'touchstart', () => (tapped.value = true))
useEventListener(target as any, 'touchend', () => (tapped.value = false))
}
}
// Focused
if (_variants.focused) {
useEventListener(target as any, 'focus', () => (focused.value = true))
useEventListener(target as any, 'blur', () => (focused.value = false))
}
// Watch local computed variant, apply it dynamically
watch(computedProperties, apply)
}