/
cssVar.js
52 lines (46 loc) · 1.11 KB
/
cssVar.js
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
49
50
51
52
// @flow
import PolishedError from '../internalHelpers/_errors'
const cssVariableRegex = /--[\S]*/g
/**
* Fetches the value of a passed CSS Variable in the :root scope, or otherwise returns a defaultValue if provided.
*
* @example
* // Styles as object usage
* const styles = {
* 'background': cssVar('--background-color'),
* }
*
* // styled-components usage
* const div = styled.div`
* background: ${cssVar('--background-color')};
* `
*
* // CSS in JS Output
*
* element {
* 'background': 'red'
* }
*/
export default function cssVar(
cssVariable: string,
defaultValue?: string | number,
): string | number {
if (!cssVariable || !cssVariable.match(cssVariableRegex)) {
throw new PolishedError(73)
}
let variableValue
/* eslint-disable */
/* istanbul ignore next */
if (document.documentElement !== null) {
variableValue = getComputedStyle(document.documentElement).getPropertyValue(
cssVariable,
)
}
/* eslint-enable */
if (variableValue) {
return variableValue.trim()
} else if (defaultValue) {
return defaultValue
}
throw new PolishedError(74)
}