Skip to content

Commit d78c720

Browse files
committed
✨ (useMotionValues) implement useMotionValues composable
1 parent 77a7c88 commit d78c720

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

src/useMotionValues.ts

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import { tryOnUnmounted } from '@vueuse/shared'
2+
import { del as __del, set as __set } from 'vue-demi'
3+
import { getMotionValue, MotionValue } from './motionValue'
4+
import { MotionProperties, MotionValuesMap } from './types'
5+
const { isArray } = Array
6+
7+
export function useMotionValues() {
8+
const motionValues: MotionValuesMap = {}
9+
10+
const stop = (keys?: string | string[]) => {
11+
// Destroy key closure
12+
const destroyKey = (key: string) => {
13+
if (!motionValues[key]) return
14+
15+
motionValues[key].stop()
16+
motionValues[key].destroy()
17+
__del(motionValues, key)
18+
}
19+
20+
// Check if keys argument is defined
21+
if (keys) {
22+
if (isArray(keys)) {
23+
// If `keys` are an array, loop on specified keys and destroy them
24+
keys.forEach(destroyKey)
25+
} else {
26+
// If `keys` is a string, destroy the specified one
27+
destroyKey(keys)
28+
}
29+
} else {
30+
// No keys specified, destroy all animations
31+
Object.keys(motionValues).forEach(destroyKey)
32+
}
33+
}
34+
35+
const get = (
36+
key: keyof MotionProperties,
37+
from: any,
38+
target: MotionProperties,
39+
): MotionValue => {
40+
if (motionValues[key]) return motionValues[key]
41+
42+
// Create motion value
43+
const motionValue = getMotionValue(from)
44+
45+
// Set motion properties mapping
46+
motionValue.onChange((v) => {
47+
__set(target, key, v)
48+
})
49+
50+
// Set instance motion value
51+
__set(motionValues, key, motionValue)
52+
53+
return motionValue
54+
}
55+
56+
// Ensure everything is cleared on unmount
57+
tryOnUnmounted(stop)
58+
59+
return {
60+
motionValues,
61+
get,
62+
stop,
63+
}
64+
}

0 commit comments

Comments
 (0)