-
-
Notifications
You must be signed in to change notification settings - Fork 93
/
Copy pathuseMotionValues.ts
67 lines (54 loc) · 1.69 KB
/
useMotionValues.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
import { tryOnUnmounted } from '@vueuse/shared'
import { ref } from 'vue'
import type { Ref } from 'vue'
import type { MotionValue } from './motionValue'
import { getMotionValue } from './motionValue'
import type { MotionProperties, MotionValuesMap } from './types'
const { isArray } = Array
export function useMotionValues() {
const motionValues = ref({}) as Ref<MotionValuesMap>
const stop = (keys?: string | string[]) => {
// Destroy key closure
const destroyKey = (key: string) => {
if (!motionValues.value[key])
return
motionValues.value[key].stop()
motionValues.value[key].destroy()
delete motionValues.value[key]
}
// Check if keys argument is defined
if (keys) {
if (isArray(keys)) {
// If `keys` are an array, loop on specified keys and destroy them
keys.forEach(destroyKey)
}
else {
// If `keys` is a string, destroy the specified one
destroyKey(keys)
}
}
else {
// No keys specified, destroy all animations
Object.keys(motionValues.value).forEach(destroyKey)
}
}
const get = (key: string, from: any, target: MotionProperties): MotionValue => {
if (motionValues.value[key])
return motionValues.value[key] as MotionValue
// Create motion value
const motionValue = getMotionValue(from)
// Set motion properties mapping
// @ts-expect-error - Fix errors later for typescript 5
motionValue.onChange(v => (target[key] = v))
// Set instance motion value
motionValues.value[key] = motionValue
return motionValue
}
// Ensure everything is cleared on unmount
tryOnUnmounted(stop)
return {
motionValues,
get,
stop,
}
}