1 |
|
2 |
|
3 | 'use strict';
|
4 |
|
5 | const blurFunctionArguments = require('../../utils/blurFunctionArguments');
|
6 | const report = require('../../utils/report');
|
7 | const ruleMessages = require('../../utils/ruleMessages');
|
8 | const styleSearch = require('style-search');
|
9 | const validateOptions = require('../../utils/validateOptions');
|
10 |
|
11 | const ruleName = 'color-hex-case';
|
12 |
|
13 | const messages = ruleMessages(ruleName, {
|
14 | expected: (actual, expected) => `Expected "${actual}" to be "${expected}"`,
|
15 | });
|
16 |
|
17 | function rule(expectation, options, context) {
|
18 | return (root, result) => {
|
19 | const validOptions = validateOptions(result, ruleName, {
|
20 | actual: expectation,
|
21 | possible: ['lower', 'upper'],
|
22 | });
|
23 |
|
24 | if (!validOptions) {
|
25 | return;
|
26 | }
|
27 |
|
28 | root.walkDecls((decl) => {
|
29 | const declString = blurFunctionArguments(decl.toString(), 'url');
|
30 | const fixPositions = [];
|
31 |
|
32 | styleSearch({ source: declString, target: '#' }, (match) => {
|
33 | const hexMatch = /^#[0-9A-Za-z]+/.exec(declString.substr(match.startIndex));
|
34 |
|
35 | if (!hexMatch) {
|
36 | return;
|
37 | }
|
38 |
|
39 | const hexValue = hexMatch[0];
|
40 | const hexValueLower = hexValue.toLowerCase();
|
41 | const hexValueUpper = hexValue.toUpperCase();
|
42 | const expectedHex = expectation === 'lower' ? hexValueLower : hexValueUpper;
|
43 |
|
44 | if (hexValue === expectedHex) {
|
45 | return;
|
46 | }
|
47 |
|
48 | if (context.fix) {
|
49 | fixPositions.unshift({
|
50 | expectedHex,
|
51 | currentHex: hexValue,
|
52 | startIndex: match.startIndex,
|
53 | });
|
54 |
|
55 | return;
|
56 | }
|
57 |
|
58 | report({
|
59 | message: messages.expected(hexValue, expectedHex),
|
60 | node: decl,
|
61 | index: match.startIndex,
|
62 | result,
|
63 | ruleName,
|
64 | });
|
65 | });
|
66 |
|
67 | if (fixPositions.length) {
|
68 | const declProp = decl.prop;
|
69 | const declBetween = decl.raws.between;
|
70 |
|
71 | fixPositions.forEach((fixPosition) => {
|
72 |
|
73 | decl.value = replaceHex(
|
74 | decl.value,
|
75 | fixPosition.currentHex,
|
76 | fixPosition.expectedHex,
|
77 | fixPosition.startIndex - declProp.length - declBetween.length - 1,
|
78 | );
|
79 | });
|
80 | }
|
81 | });
|
82 | };
|
83 | }
|
84 |
|
85 | function replaceHex(input, searchString, replaceString, startIndex) {
|
86 | const offset = startIndex + 1;
|
87 | const stringStart = input.slice(0, offset);
|
88 | const stringEnd = input.slice(offset + searchString.length);
|
89 |
|
90 | return stringStart + replaceString + stringEnd;
|
91 | }
|
92 |
|
93 | rule.ruleName = ruleName;
|
94 | rule.messages = messages;
|
95 | module.exports = rule;
|