forked from stylelint/stylelint
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
78 lines (61 loc) · 1.85 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
'use strict';
const valueParser = require('postcss-value-parser');
const declarationValueIndex = require('../../utils/declarationValueIndex');
const getDeclarationValue = require('../../utils/getDeclarationValue');
const report = require('../../utils/report');
const ruleMessages = require('../../utils/ruleMessages');
const validateOptions = require('../../utils/validateOptions');
const ruleName = 'color-no-hex';
const messages = ruleMessages(ruleName, {
rejected: (hex) => `Unexpected hex color "${hex}"`,
});
const meta = {
url: 'https://stylelint.io/user-guide/rules/color-no-hex',
};
const HEX = /^#[\da-z]+$/i;
const CONTAINS_HEX = /#[\da-z]+/i;
const IGNORED_FUNCTIONS = new Set(['url']);
/** @type {import('stylelint').Rule} */
const rule = (primary) => {
return (root, result) => {
const validOptions = validateOptions(result, ruleName, { actual: primary });
if (!validOptions) {
return;
}
root.walkDecls((decl) => {
if (!CONTAINS_HEX.test(decl.value)) return;
const parsedValue = valueParser(getDeclarationValue(decl));
parsedValue.walk((node) => {
if (isIgnoredFunction(node)) return false;
if (!isHexColor(node)) return;
const index = declarationValueIndex(decl) + node.sourceIndex;
const endIndex = index + node.value.length;
report({
message: messages.rejected,
messageArgs: [node.value],
node: decl,
index,
endIndex,
result,
ruleName,
});
});
});
};
};
/**
* @param {import('postcss-value-parser').Node} node
*/
function isIgnoredFunction({ type, value }) {
return type === 'function' && IGNORED_FUNCTIONS.has(value.toLowerCase());
}
/**
* @param {import('postcss-value-parser').Node} node
*/
function isHexColor({ type, value }) {
return type === 'word' && HEX.test(value);
}
rule.ruleName = ruleName;
rule.messages = messages;
rule.meta = meta;
module.exports = rule;