-
-
Notifications
You must be signed in to change notification settings - Fork 93
/
Copy pathuseElementTransform.ts
58 lines (50 loc) · 1.77 KB
/
useElementTransform.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
import { watch } from 'vue'
import type { MaybeRef, Reactive } from 'vue'
import { reactiveTransform } from './reactiveTransform'
import type { MotionTarget, PermissiveTarget, TransformProperties } from './types'
import { usePermissiveTarget } from './usePermissiveTarget'
import { stateFromTransform } from './utils/transform-parser'
/**
* A Composable giving access to a TransformProperties object, and binding the generated transform string to a target.
*
* @param target
*/
export function useElementTransform(target: MaybeRef<PermissiveTarget>, onInit?: (initData: Partial<TransformProperties>) => void): { transform: Reactive<TransformProperties> } {
// Transform cache available before the element is mounted
let _cache: string | undefined
// Local target cache as we need to resolve the element from PermissiveTarget
let _target: MotionTarget
// Create a reactive transform object
const { state, transform } = reactiveTransform()
// Cache transform until the element is alive and we can bind to it
usePermissiveTarget(target, (el) => {
_target = el
// Parse transform properties and applies them to the current state
if (el.style.transform)
stateFromTransform(state, el.style.transform)
// If cache is present, init the target with the current cached value
if (_cache)
el.style.transform = _cache
if (onInit)
onInit(state)
})
// Sync reactive transform to element
watch(
transform,
(newValue) => {
// Add the current value to the cache so it is set on target creation
if (!_target) {
_cache = newValue
return
}
// Set the transform string on the target
_target.style.transform = newValue
},
{
immediate: true,
},
)
return {
transform: state,
}
}