getDimension.mjs 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import valueParser from 'postcss-value-parser';
  2. import blurInterpolation from './blurInterpolation.mjs';
  3. import isStandardSyntaxValue from './isStandardSyntaxValue.mjs';
  4. /**
  5. * Get Dimension from value node;
  6. * `unit` and `number` return null if neither is found
  7. *
  8. * @param {import('postcss-value-parser').Node} node
  9. *
  10. * @returns {{unit: null, number: null} | valueParser.Dimension}
  11. */
  12. export default function getDimension(node) {
  13. if (!node || !node.value) {
  14. return {
  15. unit: null,
  16. number: null,
  17. };
  18. }
  19. // Ignore non-word nodes
  20. if (node.type !== 'word') {
  21. return {
  22. unit: null,
  23. number: null,
  24. };
  25. }
  26. // Ignore non standard syntax
  27. if (!isStandardSyntaxValue(node.value)) {
  28. return {
  29. unit: null,
  30. number: null,
  31. };
  32. }
  33. // Ignore HEX
  34. if (node.value.startsWith('#')) {
  35. return {
  36. unit: null,
  37. number: null,
  38. };
  39. }
  40. // Remove non standard stuff
  41. const value = blurInterpolation(node.value, '')
  42. // ignore hack unit
  43. .replace('\\0', '')
  44. .replace('\\9', '');
  45. const parsedUnit = valueParser.unit(value);
  46. if (!parsedUnit) {
  47. return {
  48. unit: null,
  49. number: null,
  50. };
  51. }
  52. return parsedUnit;
  53. }