-
-
Notifications
You must be signed in to change notification settings - Fork 94
/
Copy pathreactiveStyle.ts
48 lines (42 loc) · 1.22 KB
/
reactiveStyle.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
import type { Reactive, Ref } from 'vue'
import { reactive, ref, watch } from 'vue'
import type { StyleProperties } from './types'
import { getValueAsType, getValueType } from './utils/style'
/**
* Reactive style object implementing all native CSS properties.
*
* @param props
*/
export function reactiveStyle(props: StyleProperties = {}): { state: Reactive<StyleProperties>, style: Ref<StyleProperties> } {
// Reactive StyleProperties object
const state = reactive<StyleProperties>({
...props,
})
const style = ref<StyleProperties>({})
// Reactive DOM Element compatible `style` object bound to state
watch(
state,
() => {
// Init result object
const result: StyleProperties = {}
for (const [key, value] of Object.entries(state)) {
// Get value type for key
const valueType = getValueType(key)
// Get value as type for key
const valueAsType = getValueAsType(value, valueType)
// Append the computed style to result object
// @ts-expect-error - Fix errors later for typescript 5
result[key] = valueAsType
}
style.value = result
},
{
immediate: true,
deep: true,
},
)
return {
state,
style,
}
}