Skip to content

Commit bc26678

Browse files
authored
fix: useResolveClassName on web collect styles that were affected by className (#88)
1 parent 66a85d6 commit bc26678

File tree

1 file changed

+52
-1
lines changed

1 file changed

+52
-1
lines changed

packages/uniwind/src/core/web/getWebStyles.ts

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1+
import { parse } from 'culori'
12
import { RNStyle } from '../types'
3+
import { formatColor } from './formatColor'
24

35
const dummy = typeof document !== 'undefined'
46
? Object.assign(document.createElement('div'), {
@@ -10,6 +12,42 @@ if (dummy) {
1012
document.body.appendChild(dummy)
1113
}
1214

15+
const getComputedStyles = () => {
16+
if (!dummy) {
17+
return {} as CSSStyleDeclaration
18+
}
19+
20+
const computedStyles = window.getComputedStyle(dummy)
21+
const styles = {} as CSSStyleDeclaration
22+
23+
// eslint-disable-next-line @typescript-eslint/prefer-for-of
24+
for (let i = 0; i < computedStyles.length; i++) {
25+
// Typescript is unable to infer it properly
26+
const prop = computedStyles[i] as any
27+
28+
styles[prop] = computedStyles.getPropertyValue(prop)
29+
}
30+
31+
return styles
32+
}
33+
34+
const initialStyles = typeof document !== 'undefined'
35+
? getComputedStyles()
36+
: {} as CSSStyleDeclaration
37+
38+
const getObjectDifference = <T extends object>(obj1: T, obj2: T): T => {
39+
const diff = {} as T
40+
const keys = Object.keys(obj2) as Array<keyof T>
41+
42+
keys.forEach(key => {
43+
if (obj2[key] !== obj1[key]) {
44+
diff[key] = obj2[key]
45+
}
46+
})
47+
48+
return diff
49+
}
50+
1351
export const getWebStyles = (className?: string): RNStyle => {
1452
if (className === undefined) {
1553
return {}
@@ -21,5 +59,18 @@ export const getWebStyles = (className?: string): RNStyle => {
2159

2260
dummy.className = className
2361

24-
return window.getComputedStyle(dummy) as unknown as RNStyle
62+
const computedStyles = getObjectDifference(initialStyles, getComputedStyles())
63+
64+
return Object.fromEntries(
65+
Object.entries(computedStyles).map(([key, value]) => {
66+
const parsedValue = isNaN(Number(value)) && parse(value) !== undefined
67+
? formatColor(value)
68+
: value
69+
70+
return [
71+
key.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase()),
72+
parsedValue,
73+
]
74+
}),
75+
)
2576
}

0 commit comments

Comments
 (0)