All files / lib/helpers em.js

100% Statements 24/24
95% Branches 19/20
100% Functions 2/2
100% Lines 24/24
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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74    1x       1x   1x   1x   1x   2x                                                         10x   10x 10x 10x 8x 1x   7x     9x 8x 1x   7x     8x 1x     7x 1x     6x     1x 1x
'use strict';
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
 
var _endsWith = require('../internalHelpers/_endsWith');
 
var _endsWith2 = _interopRequireDefault(_endsWith);
 
var _stripUnit = require('./stripUnit');
 
var _stripUnit2 = _interopRequireDefault(_stripUnit);
 
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
 
/**
 * Convert pixel value to ems. The default base value is 16px, but can be changed by passing a
 * second argument to the function.
 * @static
 * @param {string|number} pxval - The pixel value you want to convert
 * @param {string|number} [base = "16px"] - The base size to convert from
 * @return {String} The converted value
 * @example
 * // Styles as object usage
 * const styles = {
 *   'height': em('16px')
 * }
 *
 * // styled-components usage
 * const div = styled.div`
 *   height: ${em('16px')}
 * `
 *
 * // CSS in JS Output
 *
 * element {
 *   'height': '1em'
 * }
 */
 
/* eslint-disable no-param-reassign */
function em(pxval) {
  var base = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '16px';
 
  var newPxval = pxval;
  var newBase = base;
  if (typeof pxval === 'string') {
    if (!(0, _endsWith2.default)(pxval, 'px')) {
      throw new Error('Expected a string ending in "px" or a number passed as the first argument to em(), got "' + pxval + '" instead.');
    }
    newPxval = (0, _stripUnit2.default)(pxval);
  }
 
  if (typeof base === 'string') {
    if (!(0, _endsWith2.default)(base, 'px')) {
      throw new Error('Expected a string ending in "px" or a number passed as the second argument to em(), got "' + base + '" instead.');
    }
    newBase = (0, _stripUnit2.default)(base);
  }
 
  if (typeof newPxval === 'string') {
    throw new Error('Passed invalid pixel value ("' + pxval + '") to em(), please pass a value like "12px" or 12.');
  }
 
  if (typeof newBase === 'string') {
    throw new Error('Passed invalid base value ("' + base + '") to em(), please pass a value like "12px" or 12.');
  }
 
  return newPxval / newBase + 'em';
}
 
exports.default = em;
module.exports = exports['default'];