remToPx.js.flow 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // @flow
  2. import getValueAndUnit from './getValueAndUnit'
  3. import PolishedError from '../internalHelpers/_errors'
  4. const defaultFontSize = 16
  5. function convertBase(base: string | number): number {
  6. const deconstructedValue = getValueAndUnit(base)
  7. if (deconstructedValue[1] === 'px') {
  8. return parseFloat(base)
  9. }
  10. if (deconstructedValue[1] === '%') {
  11. return (parseFloat(base) / 100) * defaultFontSize
  12. }
  13. throw new PolishedError(78, deconstructedValue[1])
  14. }
  15. function getBaseFromDoc(): number {
  16. /* eslint-disable */
  17. /* istanbul ignore next */
  18. if (typeof document !== 'undefined' && document.documentElement !== null) {
  19. const rootFontSize = getComputedStyle(document.documentElement).fontSize
  20. return rootFontSize ? convertBase(rootFontSize) : defaultFontSize
  21. }
  22. /* eslint-enable */
  23. /* istanbul ignore next */
  24. return defaultFontSize
  25. }
  26. /**
  27. * Convert rem values to px. By default, the base value is pulled from the font-size property on the root element (if it is set in % or px). It defaults to 16px if not found on the root. You can also override the base value by providing your own base in % or px.
  28. * @example
  29. * // Styles as object usage
  30. * const styles = {
  31. * 'height': remToPx('1.6rem')
  32. * 'height': remToPx('1.6rem', '10px')
  33. * }
  34. *
  35. * // styled-components usage
  36. * const div = styled.div`
  37. * height: ${remToPx('1.6rem')}
  38. * height: ${remToPx('1.6rem', '10px')}
  39. * `
  40. *
  41. * // CSS in JS Output
  42. *
  43. * element {
  44. * 'height': '25.6px',
  45. * 'height': '16px',
  46. * }
  47. */
  48. export default function remToPx(value: string | number, base?: string | number): string {
  49. const deconstructedValue = getValueAndUnit(value)
  50. if (deconstructedValue[1] !== 'rem' && deconstructedValue[1] !== '') {
  51. throw new PolishedError(77, deconstructedValue[1])
  52. }
  53. const newBase = base ? convertBase(base) : getBaseFromDoc()
  54. return `${deconstructedValue[0] * newBase}px`
  55. }