index.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. 'use strict';
  2. const valueParser = require('postcss-value-parser');
  3. const declarationValueIndex = require('../../utils/declarationValueIndex');
  4. const isCustomProperty = require('../../utils/isCustomProperty');
  5. const report = require('../../utils/report');
  6. const ruleMessages = require('../../utils/ruleMessages');
  7. const validateOptions = require('../../utils/validateOptions');
  8. const ruleName = 'custom-property-no-missing-var-function';
  9. const messages = ruleMessages(ruleName, {
  10. rejected: (customProperty) => `Unexpected missing var function for "${customProperty}"`,
  11. });
  12. const meta = {
  13. url: 'https://stylelint.io/user-guide/rules/custom-property-no-missing-var-function',
  14. };
  15. /** @type {import('stylelint').Rule} */
  16. const rule = (primary) => {
  17. return (root, result) => {
  18. const validOptions = validateOptions(result, ruleName, { actual: primary });
  19. if (!validOptions) return;
  20. /** @type {Set<string>} */
  21. const knownCustomProperties = new Set();
  22. root.walkAtRules(/^property$/i, (atRule) => {
  23. knownCustomProperties.add(atRule.params);
  24. });
  25. root.walkDecls(({ prop }) => {
  26. if (isCustomProperty(prop)) knownCustomProperties.add(prop);
  27. });
  28. root.walkDecls((decl) => {
  29. const { value } = decl;
  30. const parsedValue = valueParser(value);
  31. parsedValue.walk((node) => {
  32. if (isVarFunction(node)) return false;
  33. if (!isDashedIdent(node)) return;
  34. if (!knownCustomProperties.has(node.value)) return;
  35. const index = declarationValueIndex(decl) + node.sourceIndex;
  36. const endIndex = index + node.value.length;
  37. report({
  38. message: messages.rejected(node.value),
  39. node: decl,
  40. index,
  41. endIndex,
  42. result,
  43. ruleName,
  44. });
  45. return false;
  46. });
  47. });
  48. };
  49. };
  50. /**
  51. * @param {import('postcss-value-parser').Node} node
  52. */
  53. function isDashedIdent({ type, value }) {
  54. return type === 'word' && value.startsWith('--');
  55. }
  56. /**
  57. * @param {import('postcss-value-parser').Node} node
  58. */
  59. function isVarFunction({ type, value }) {
  60. return type === 'function' && value === 'var';
  61. }
  62. rule.ruleName = ruleName;
  63. rule.messages = messages;
  64. rule.meta = meta;
  65. module.exports = rule;