remToPx.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. "use strict";
  2. exports.__esModule = true;
  3. exports["default"] = remToPx;
  4. var _getValueAndUnit = _interopRequireDefault(require("./getValueAndUnit"));
  5. var _errors = _interopRequireDefault(require("../internalHelpers/_errors"));
  6. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  7. var defaultFontSize = 16;
  8. function convertBase(base) {
  9. var deconstructedValue = (0, _getValueAndUnit["default"])(base);
  10. if (deconstructedValue[1] === 'px') {
  11. return parseFloat(base);
  12. }
  13. if (deconstructedValue[1] === '%') {
  14. return parseFloat(base) / 100 * defaultFontSize;
  15. }
  16. throw new _errors["default"](78, deconstructedValue[1]);
  17. }
  18. function getBaseFromDoc() {
  19. /* eslint-disable */
  20. /* istanbul ignore next */
  21. if (typeof document !== 'undefined' && document.documentElement !== null) {
  22. var rootFontSize = getComputedStyle(document.documentElement).fontSize;
  23. return rootFontSize ? convertBase(rootFontSize) : defaultFontSize;
  24. }
  25. /* eslint-enable */
  26. /* istanbul ignore next */
  27. return defaultFontSize;
  28. }
  29. /**
  30. * 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.
  31. * @example
  32. * // Styles as object usage
  33. * const styles = {
  34. * 'height': remToPx('1.6rem')
  35. * 'height': remToPx('1.6rem', '10px')
  36. * }
  37. *
  38. * // styled-components usage
  39. * const div = styled.div`
  40. * height: ${remToPx('1.6rem')}
  41. * height: ${remToPx('1.6rem', '10px')}
  42. * `
  43. *
  44. * // CSS in JS Output
  45. *
  46. * element {
  47. * 'height': '25.6px',
  48. * 'height': '16px',
  49. * }
  50. */
  51. function remToPx(value, base) {
  52. var deconstructedValue = (0, _getValueAndUnit["default"])(value);
  53. if (deconstructedValue[1] !== 'rem' && deconstructedValue[1] !== '') {
  54. throw new _errors["default"](77, deconstructedValue[1]);
  55. }
  56. var newBase = base ? convertBase(base) : getBaseFromDoc();
  57. return deconstructedValue[0] * newBase + "px";
  58. }
  59. module.exports = exports.default;