UNPKG

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