-
-
Notifications
You must be signed in to change notification settings - Fork 94
/
Copy pathuseElementStyle.ts
68 lines (59 loc) · 2.2 KB
/
useElementStyle.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
import type { MaybeRef, Reactive } from 'vue'
import { watch } from 'vue'
import { reactiveStyle } from './reactiveStyle'
import type { MotionTarget, PermissiveTarget, StyleProperties } from './types'
import { usePermissiveTarget } from './usePermissiveTarget'
import { valueTypes } from './utils/style'
import { isTransformOriginProp, isTransformProp } from './utils/transform'
/**
* A Composable giving access to a StyleProperties object, and binding the generated style object to a target.
*
* @param target
*/
export function useElementStyle(target: MaybeRef<PermissiveTarget>, onInit?: (initData: Partial<StyleProperties>) => void): { style: Reactive<StyleProperties> } {
// Transform cache available before the element is mounted
let _cache: StyleProperties | undefined
// Local target cache as we need to resolve the element from PermissiveTarget
let _target: MotionTarget
// Create a reactive style object
const { state, style } = reactiveStyle()
usePermissiveTarget(target, (el) => {
_target = el
// Loop on style keys
for (const key of Object.keys(valueTypes)) {
// @ts-expect-error - Fix errors later for typescript 5
if (el.style[key] === null || el.style[key] === '' || isTransformProp(key) || isTransformOriginProp(key))
continue
// Append a defined key to the local StyleProperties state object
// @ts-expect-error - Fix errors later for typescript 5
state[key] = el.style[key]
}
// If cache is present, init the target with the current cached value
if (_cache) {
// @ts-expect-error - Fix errors later for typescript 5
Object.entries(_cache).forEach(([key, value]) => (el.style[key] = value))
}
if (onInit)
onInit(state)
})
// Sync reactive style to element
watch(
style,
(newVal) => {
// Add the current value to the cache so it is set on target creation
if (!_target) {
_cache = newVal
return
}
// Append the state object to the target style properties
// @ts-expect-error - Fix errors later for typescript 5
for (const key in newVal) _target.style[key] = newVal[key]
},
{
immediate: true,
},
)
return {
style: state,
}
}