cssVar.js.flow 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. // @flow
  2. import PolishedError from '../internalHelpers/_errors'
  3. const cssVariableRegex = /--[\S]*/g
  4. /**
  5. * Fetches the value of a passed CSS Variable in the :root scope, or otherwise returns a defaultValue if provided.
  6. *
  7. * @example
  8. * // Styles as object usage
  9. * const styles = {
  10. * 'background': cssVar('--background-color'),
  11. * }
  12. *
  13. * // styled-components usage
  14. * const div = styled.div`
  15. * background: ${cssVar('--background-color')};
  16. * `
  17. *
  18. * // CSS in JS Output
  19. *
  20. * element {
  21. * 'background': 'red'
  22. * }
  23. */
  24. export default function cssVar(
  25. cssVariable: string,
  26. defaultValue?: string | number,
  27. ): string | number {
  28. if (!cssVariable || !cssVariable.match(cssVariableRegex)) {
  29. throw new PolishedError(73)
  30. }
  31. let variableValue
  32. /* eslint-disable */
  33. /* istanbul ignore next */
  34. if (typeof document !== 'undefined' && document.documentElement !== null) {
  35. variableValue = getComputedStyle(document.documentElement).getPropertyValue(cssVariable)
  36. }
  37. /* eslint-enable */
  38. if (variableValue) {
  39. return variableValue.trim()
  40. } else if (defaultValue) {
  41. return defaultValue
  42. }
  43. throw new PolishedError(74)
  44. }