| | import { useState, useEffect } from 'react'; |
| |
|
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | function useCssVariable( |
| | variableName: string, |
| | element: Element | null = typeof document !== 'undefined' ? document.documentElement : null, |
| | observe: boolean = false |
| | ): string { |
| | const [ value, setValue ] = useState< string >( '' ); |
| |
|
| | useEffect( () => { |
| | |
| | if ( typeof window === 'undefined' ) { |
| | return; |
| | } |
| |
|
| | |
| | if ( ! element ) { |
| | return; |
| | } |
| |
|
| | |
| | const updateValue = (): void => { |
| | const styles = window.getComputedStyle( element ); |
| | const newValue = styles.getPropertyValue( variableName ).trim(); |
| | setValue( newValue ); |
| | }; |
| |
|
| | |
| | setTimeout( updateValue, 200 ); |
| |
|
| | |
| | if ( observe ) { |
| | const observer = new MutationObserver( ( mutations: MutationRecord[] ): void => { |
| | mutations.forEach( ( mutation: MutationRecord ): void => { |
| | if ( |
| | mutation.type === 'attributes' && |
| | ( mutation.attributeName === 'style' || mutation.attributeName === 'class' ) |
| | ) { |
| | updateValue(); |
| | } |
| | } ); |
| | } ); |
| |
|
| | observer.observe( element, { |
| | attributes: true, |
| | attributeFilter: [ 'style', 'class' ], |
| | } ); |
| |
|
| | |
| | return () => observer.disconnect(); |
| | } |
| | }, [ variableName, element, observe ] ); |
| |
|
| | return value; |
| | } |
| |
|
| | export default useCssVariable; |
| |
|