1+ import { parse } from 'culori'
12import { RNStyle } from '../types'
3+ import { formatColor } from './formatColor'
24
35const 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+
1351export 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