unitless-zero.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. module.exports = {
  2. name: 'unitless-zero',
  3. syntax: ['css', 'less', 'sass', 'scss'],
  4. accepts: { boolean: [true] },
  5. /**
  6. * Processes tree node.
  7. *
  8. * @param {node} node
  9. */
  10. process: function(node) {
  11. var UNITS = ['cm', 'em', 'ex', 'pt', 'px'];
  12. if (!node.is('value') && !node.is('braces')) return;
  13. node.forEach(function(value) {
  14. if (typeof value === 'string') return;
  15. if (value.is('dimension')) {
  16. var unit = value.first('ident').content;
  17. if (value.first('number').content === '0' &&
  18. UNITS.indexOf(unit) !== -1) {
  19. value.remove(1);
  20. }
  21. } else if (value.is('percentage')) {
  22. // XXX(tonyganch): There is a bug in Gonzales when in Less,
  23. // percentage's content is not wrapped as an array but actually
  24. // type of node's content is object. This bug has already been
  25. // fixed in newer versions of Gonzales so the issue should be
  26. // gone after update of dependencies and csscomb@4.0 release.
  27. // This hack is here as a hotfix for csscomb@3.1 and must be
  28. // removed once csscom@4.0 is released. See #389.
  29. var number;
  30. if (!Array.isArray(value.content) &&
  31. value.content.is('number')) {
  32. number = value.content;
  33. } else {
  34. number = value.first('number').content;
  35. }
  36. if (number === '0') {
  37. value.type = 'number';
  38. value.content = number;
  39. }
  40. }
  41. });
  42. },
  43. /**
  44. * Detects the value of an option at the tree node.
  45. *
  46. * @param {node} node
  47. */
  48. detect: function(node) {
  49. var result;
  50. // If we see a zero with unit and it is not degree, then we don’t have an option
  51. if (node.is('percentage') && node.first('number').content[1] === '0') {
  52. result = false;
  53. } else if (node.is('dimension') &&
  54. node.first('number').content === '0' &&
  55. node.first('ident').content !== 'deg') {
  56. result = false;
  57. }
  58. // If we see a zero and previous node is not percentage or dimension, then we have an option
  59. if (node.is('number') &&
  60. node.content === '0' &&
  61. this._prev !== 'percentage' &&
  62. this._prev !== 'dimension') {
  63. result = true;
  64. }
  65. // Store the previous nodeType
  66. this._prev = node.type;
  67. return result;
  68. }
  69. };