UNPKG

1.34 kBJavaScriptView Raw
1// @ts-nocheck
2
3'use strict';
4
5const report = require('../../utils/report');
6const ruleMessages = require('../../utils/ruleMessages');
7const styleSearch = require('style-search');
8const validateOptions = require('../../utils/validateOptions');
9
10const ruleName = 'color-no-hex';
11
12const messages = ruleMessages(ruleName, {
13 rejected: (hex) => `Unexpected hex color "${hex}"`,
14});
15
16function rule(actual) {
17 return (root, result) => {
18 const validOptions = validateOptions(result, ruleName, { actual });
19
20 if (!validOptions) {
21 return;
22 }
23
24 root.walkDecls((decl) => {
25 const declString = decl.toString();
26
27 styleSearch({ source: declString, target: '#' }, (match) => {
28 // If there's not a colon, comma, or whitespace character before, we'll assume this is
29 // not intended to be a hex color, but is instead something like the
30 // hash in a url() argument
31 if (!/[:,\s]/.test(declString[match.startIndex - 1])) {
32 return;
33 }
34
35 const hexMatch = /^#[0-9A-Za-z]+/.exec(declString.substr(match.startIndex));
36
37 if (!hexMatch) {
38 return;
39 }
40
41 const hexValue = hexMatch[0];
42
43 report({
44 message: messages.rejected(hexValue),
45 node: decl,
46 index: match.startIndex,
47 result,
48 ruleName,
49 });
50 });
51 });
52 };
53}
54
55rule.ruleName = ruleName;
56rule.messages = messages;
57module.exports = rule;