index.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. 'use strict';
  2. const valueParser = require('postcss-value-parser');
  3. const declarationValueIndex = require('../../utils/declarationValueIndex');
  4. const getDeclarationValue = require('../../utils/getDeclarationValue');
  5. const isStandardSyntaxValue = require('../../utils/isStandardSyntaxValue');
  6. const report = require('../../utils/report');
  7. const ruleMessages = require('../../utils/ruleMessages');
  8. const setDeclarationValue = require('../../utils/setDeclarationValue');
  9. const validateOptions = require('../../utils/validateOptions');
  10. const { assert } = require('../../utils/validateTypes');
  11. const ruleName = 'function-calc-no-unspaced-operator';
  12. const messages = ruleMessages(ruleName, {
  13. expectedBefore: (operator) => `Expected single space before "${operator}" operator`,
  14. expectedAfter: (operator) => `Expected single space after "${operator}" operator`,
  15. expectedOperatorBeforeSign: (operator) => `Expected an operator before sign "${operator}"`,
  16. });
  17. const meta = {
  18. url: 'https://stylelint.io/user-guide/rules/list/function-calc-no-unspaced-operator',
  19. fixable: true,
  20. };
  21. const OPERATORS = new Set(['+', '-']);
  22. const OPERATOR_REGEX = /[+-]/;
  23. const ALL_OPERATORS = new Set([...OPERATORS, '*', '/']);
  24. /** @type {import('stylelint').Rule} */
  25. const rule = (primary, _secondaryOptions, context) => {
  26. return (root, result) => {
  27. const validOptions = validateOptions(result, ruleName, { actual: primary });
  28. if (!validOptions) return;
  29. /**
  30. * @param {string} message
  31. * @param {import('postcss').Node} node
  32. * @param {number} index
  33. * @param {string} operator
  34. */
  35. function complain(message, node, index, operator) {
  36. const endIndex = index + operator.length;
  37. report({ message, node, index, endIndex, result, ruleName });
  38. }
  39. root.walkDecls((decl) => {
  40. let needsFix = false;
  41. const valueIndex = declarationValueIndex(decl);
  42. const parsedValue = valueParser(getDeclarationValue(decl));
  43. /**
  44. * @param {import('postcss-value-parser').Node} operatorNode
  45. * @param {import('postcss-value-parser').Node} currentNode
  46. * @param {boolean} isBeforeOp
  47. */
  48. function checkAroundOperator(operatorNode, currentNode, isBeforeOp) {
  49. const operator = operatorNode.value;
  50. const operatorSourceIndex = operatorNode.sourceIndex;
  51. if (currentNode && !isSingleSpace(currentNode)) {
  52. if (currentNode.type === 'word') {
  53. if (isBeforeOp) {
  54. const lastChar = currentNode.value.slice(-1);
  55. if (OPERATORS.has(lastChar)) {
  56. if (context.fix) {
  57. currentNode.value = `${currentNode.value.slice(0, -1)} ${lastChar}`;
  58. return true;
  59. }
  60. complain(
  61. messages.expectedOperatorBeforeSign(operator),
  62. decl,
  63. operatorSourceIndex,
  64. operator,
  65. );
  66. return true;
  67. }
  68. } else {
  69. const firstChar = currentNode.value.slice(0, 1);
  70. if (OPERATORS.has(firstChar)) {
  71. if (context.fix) {
  72. currentNode.value = `${firstChar} ${currentNode.value.slice(1)}`;
  73. return true;
  74. }
  75. complain(messages.expectedAfter(operator), decl, operatorSourceIndex, operator);
  76. return true;
  77. }
  78. }
  79. if (context.fix) {
  80. needsFix = true;
  81. currentNode.value = isBeforeOp ? `${currentNode.value} ` : ` ${currentNode.value}`;
  82. return true;
  83. }
  84. complain(
  85. isBeforeOp ? messages.expectedBefore(operator) : messages.expectedAfter(operator),
  86. decl,
  87. valueIndex + operatorSourceIndex,
  88. operator,
  89. );
  90. return true;
  91. }
  92. if (currentNode.type === 'space') {
  93. const indexOfFirstNewLine = currentNode.value.search(/(\n|\r\n)/);
  94. if (indexOfFirstNewLine === 0) return;
  95. if (context.fix) {
  96. needsFix = true;
  97. currentNode.value =
  98. indexOfFirstNewLine === -1 ? ' ' : currentNode.value.slice(indexOfFirstNewLine);
  99. return true;
  100. }
  101. const message = isBeforeOp
  102. ? messages.expectedBefore(operator)
  103. : messages.expectedAfter(operator);
  104. complain(message, decl, valueIndex + operatorSourceIndex, operator);
  105. return true;
  106. }
  107. if (currentNode.type === 'function') {
  108. if (context.fix) {
  109. needsFix = true;
  110. currentNode.value = isBeforeOp ? `${currentNode.value} ` : ` ${currentNode.value}`;
  111. return true;
  112. }
  113. const message = isBeforeOp
  114. ? messages.expectedBefore(operator)
  115. : messages.expectedAfter(operator);
  116. complain(message, decl, valueIndex + operatorSourceIndex, operator);
  117. return true;
  118. }
  119. }
  120. return false;
  121. }
  122. /**
  123. * @param {import('postcss-value-parser').Node[]} nodes
  124. */
  125. function checkForOperatorInFirstNode(nodes) {
  126. const firstNode = nodes[0];
  127. assert(firstNode);
  128. if (firstNode.type !== 'word') return false;
  129. if (!isStandardSyntaxValue(firstNode.value)) return false;
  130. const operatorIndex = firstNode.value.search(OPERATOR_REGEX);
  131. const operator = firstNode.value.slice(operatorIndex, operatorIndex + 1);
  132. if (operatorIndex <= 0) return false;
  133. const charBefore = firstNode.value.charAt(operatorIndex - 1);
  134. const charAfter = firstNode.value.charAt(operatorIndex + 1);
  135. if (charBefore && charBefore !== ' ' && charAfter && charAfter !== ' ') {
  136. if (context.fix) {
  137. needsFix = true;
  138. firstNode.value = insertCharAtIndex(firstNode.value, operatorIndex + 1, ' ');
  139. firstNode.value = insertCharAtIndex(firstNode.value, operatorIndex, ' ');
  140. } else {
  141. complain(
  142. messages.expectedBefore(operator),
  143. decl,
  144. valueIndex + firstNode.sourceIndex + operatorIndex,
  145. operator,
  146. );
  147. complain(
  148. messages.expectedAfter(operator),
  149. decl,
  150. valueIndex + firstNode.sourceIndex + operatorIndex + 1,
  151. operator,
  152. );
  153. }
  154. } else if (charBefore && charBefore !== ' ') {
  155. if (context.fix) {
  156. needsFix = true;
  157. firstNode.value = insertCharAtIndex(firstNode.value, operatorIndex, ' ');
  158. } else {
  159. complain(
  160. messages.expectedBefore(operator),
  161. decl,
  162. valueIndex + firstNode.sourceIndex + operatorIndex,
  163. operator,
  164. );
  165. }
  166. } else if (charAfter && charAfter !== ' ') {
  167. if (context.fix) {
  168. needsFix = true;
  169. firstNode.value = insertCharAtIndex(firstNode.value, operatorIndex, ' ');
  170. } else {
  171. complain(
  172. messages.expectedAfter(operator),
  173. decl,
  174. valueIndex + firstNode.sourceIndex + operatorIndex + 1,
  175. operator,
  176. );
  177. }
  178. }
  179. return true;
  180. }
  181. /**
  182. * @param {import('postcss-value-parser').Node[]} nodes
  183. */
  184. function checkForOperatorInLastNode(nodes) {
  185. if (nodes.length === 1) return false;
  186. const lastNode = nodes[nodes.length - 1];
  187. assert(lastNode);
  188. if (lastNode.type !== 'word') return false;
  189. const operatorIndex = lastNode.value.search(OPERATOR_REGEX);
  190. if (operatorIndex === -1) return false;
  191. if (lastNode.value.charAt(operatorIndex - 1) === ' ') return false;
  192. // E.g. "10px * -2" when the last node is "-2"
  193. if (
  194. isOperator(nodes[nodes.length - 3], ALL_OPERATORS) &&
  195. isSingleSpace(nodes[nodes.length - 2])
  196. ) {
  197. return false;
  198. }
  199. if (context.fix) {
  200. needsFix = true;
  201. lastNode.value = insertCharAtIndex(lastNode.value, operatorIndex + 1, ' ').trim();
  202. lastNode.value = insertCharAtIndex(lastNode.value, operatorIndex, ' ').trim();
  203. return true;
  204. }
  205. const operator = lastNode.value.charAt(operatorIndex);
  206. complain(
  207. messages.expectedOperatorBeforeSign(operator),
  208. decl,
  209. valueIndex + lastNode.sourceIndex + operatorIndex,
  210. operator,
  211. );
  212. return true;
  213. }
  214. /**
  215. * @param {import('postcss-value-parser').Node[]} nodes
  216. */
  217. function checkWords(nodes) {
  218. if (checkForOperatorInFirstNode(nodes) || checkForOperatorInLastNode(nodes)) return;
  219. for (const [index, node] of nodes.entries()) {
  220. const lastChar = node.value.slice(-1);
  221. const firstChar = node.value.slice(0, 1);
  222. if (node.type === 'word') {
  223. if (index === 0 && OPERATORS.has(lastChar)) {
  224. if (context.fix) {
  225. node.value = `${node.value.slice(0, -1)} ${lastChar}`;
  226. continue;
  227. }
  228. complain(messages.expectedBefore(lastChar), decl, node.sourceIndex, lastChar);
  229. } else if (index === nodes.length && OPERATORS.has(firstChar)) {
  230. if (context.fix) {
  231. node.value = `${firstChar} ${node.value.slice(1)}`;
  232. continue;
  233. }
  234. complain(
  235. messages.expectedOperatorBeforeSign(firstChar),
  236. decl,
  237. node.sourceIndex,
  238. firstChar,
  239. );
  240. }
  241. }
  242. }
  243. }
  244. parsedValue.walk((node) => {
  245. if (node.type !== 'function' || node.value.toLowerCase() !== 'calc') return;
  246. const { nodes } = node;
  247. let foundOperatorNode = false;
  248. for (const [nodeIndex, currNode] of nodes.entries()) {
  249. if (!isOperator(currNode)) continue;
  250. foundOperatorNode = true;
  251. const nodeBefore = nodes[nodeIndex - 1];
  252. const nodeAfter = nodes[nodeIndex + 1];
  253. if (isSingleSpace(nodeBefore) && isSingleSpace(nodeAfter)) continue;
  254. if (nodeAfter && checkAroundOperator(currNode, nodeAfter, false)) continue;
  255. nodeBefore && checkAroundOperator(currNode, nodeBefore, true);
  256. }
  257. if (!foundOperatorNode) {
  258. checkWords(nodes);
  259. }
  260. });
  261. if (needsFix) {
  262. setDeclarationValue(decl, parsedValue.toString());
  263. }
  264. });
  265. };
  266. };
  267. /**
  268. * @param {string} str
  269. * @param {number} index
  270. * @param {string} char
  271. */
  272. function insertCharAtIndex(str, index, char) {
  273. return str.slice(0, index) + char + str.slice(index, str.length);
  274. }
  275. /**
  276. * @param {import('postcss-value-parser').Node | undefined} node
  277. * @returns {node is import('postcss-value-parser').SpaceNode & { value: ' ' } }
  278. */
  279. function isSingleSpace(node) {
  280. return node != null && node.type === 'space' && node.value === ' ';
  281. }
  282. /**
  283. * @param {import('postcss-value-parser').Node | undefined} node
  284. * @param {Set<string>} [operators]
  285. * @returns {node is import('postcss-value-parser').WordNode}
  286. */
  287. function isOperator(node, operators = OPERATORS) {
  288. return node != null && node.type === 'word' && operators.has(node.value);
  289. }
  290. rule.ruleName = ruleName;
  291. rule.messages = messages;
  292. rule.meta = meta;
  293. module.exports = rule;