UNPKG

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