| 1 |
/** |
| 2 |
* @param {Object|string} styles { base: { shared: '', variant: { shared: '', h1: '', h2: '' } }, dark: { shared: '', variant: { shared: '', h1: '', h2: '' } } } |
| 3 |
* @param {Object} props { variant: 'h1', size: 'xl' } |
| 4 |
* @param {string} type shared/unique (in case that only the shared/unique styles are needed) |
| 5 |
* @return {string} - style |
| 6 |
*/ |
| 7 |
export const getStyle = ( styles, props, type ) => { |
| 8 |
if ( ! styles ) { |
| 9 |
return ''; |
| 10 |
} |
| 11 |
|
| 12 |
if ( 'string' === typeof styles ) { |
| 13 |
return styles; |
| 14 |
} |
| 15 |
|
| 16 |
const config = props?.theme?.config || { variants: {} }, |
| 17 |
style = { |
| 18 |
shared: '', |
| 19 |
unique: '', |
| 20 |
}; |
| 21 |
|
| 22 |
// Creating an array that holds only the active theme variants values. |
| 23 |
const themeVariants = Object.keys( config.variants ).filter( ( key ) => config.variants[ key ] ), |
| 24 |
addStyle = ( data, keys = [] ) => { |
| 25 |
if ( 'string' === typeof data && 'unique' !== type ) { |
| 26 |
style.shared += data; |
| 27 |
|
| 28 |
return; |
| 29 |
} |
| 30 |
|
| 31 |
Object.values( keys ).forEach( ( key ) => { |
| 32 |
const styleObjKey = 'shared' !== key ? 'unique' : 'shared'; |
| 33 |
|
| 34 |
if ( ! type || styleObjKey === type ) { |
| 35 |
style[ styleObjKey ] += data[ key ] || ''; |
| 36 |
} |
| 37 |
} ); |
| 38 |
}; |
| 39 |
|
| 40 |
// Adding the 'base' key, to be included as the first variant. |
| 41 |
themeVariants.unshift( 'base' ); |
| 42 |
|
| 43 |
themeVariants.forEach( ( key ) => { |
| 44 |
const themeVariant = styles[ key ]; |
| 45 |
|
| 46 |
// If key exist in the styles obj (dark, light etc.) |
| 47 |
if ( themeVariant ) { |
| 48 |
addStyle( themeVariant, [ 'shared' ] ); |
| 49 |
|
| 50 |
const styledProps = getStyledProps( props ); |
| 51 |
|
| 52 |
// Getting the styled props css from the styles object. |
| 53 |
Object.entries( styledProps ).forEach( ( [ propName, propValue ] ) => { |
| 54 |
const styleData = themeVariant[ propName ]; |
| 55 |
|
| 56 |
if ( styleData && propValue ) { |
| 57 |
addStyle( styleData, [ 'shared', propValue ] ); |
| 58 |
} |
| 59 |
} ); |
| 60 |
} |
| 61 |
} ); |
| 62 |
|
| 63 |
// Both properties are returned but their values are depended on the third argument of this function, if empty: both will be calculated. |
| 64 |
return style.shared + style.unique; |
| 65 |
}; |
| 66 |
|
| 67 |
const getStyledProps = ( props ) => { |
| 68 |
const styledProps = { ...props }; |
| 69 |
|
| 70 |
// Removing props names that are not related to the styles objects. |
| 71 |
[ 'className', 'children', 'tag', 'as', 'theme' ].forEach( ( prop ) => delete styledProps[ prop ] ); |
| 72 |
|
| 73 |
return styledProps; |
| 74 |
}; |
| 75 |
|