getValueAndUnit.js 885 B

123456789101112131415161718192021222324252627282930313233343536
  1. "use strict";
  2. exports.__esModule = true;
  3. exports["default"] = getValueAndUnit;
  4. var cssRegex = /^([+-]?(?:\d+|\d*\.\d+))([a-z]*|%)$/;
  5. /**
  6. * Returns a given CSS value and its unit as elements of an array.
  7. *
  8. * @example
  9. * // Styles as object usage
  10. * const styles = {
  11. * '--dimension': getValueAndUnit('100px')[0],
  12. * '--unit': getValueAndUnit('100px')[1],
  13. * }
  14. *
  15. * // styled-components usage
  16. * const div = styled.div`
  17. * --dimension: ${getValueAndUnit('100px')[0]};
  18. * --unit: ${getValueAndUnit('100px')[1]};
  19. * `
  20. *
  21. * // CSS in JS Output
  22. *
  23. * element {
  24. * '--dimension': 100,
  25. * '--unit': 'px',
  26. * }
  27. */
  28. function getValueAndUnit(value) {
  29. if (typeof value !== 'string') return [value, ''];
  30. var matchedValue = value.match(cssRegex);
  31. if (matchedValue) return [parseFloat(value), matchedValue[2]];
  32. return [value, undefined];
  33. }
  34. module.exports = exports.default;