UNPKG

2.18 kBJavaScriptView Raw
1"use strict";
2
3const isStandardSyntaxRule = require("../utils/isStandardSyntaxRule");
4const parseSelector = require("../utils/parseSelector");
5const report = require("../utils/report");
6
7module.exports = function(opts) {
8 let hasFixed;
9
10 opts.root.walkRules(rule => {
11 if (!isStandardSyntaxRule(rule)) {
12 return;
13 }
14
15 hasFixed = false;
16 const selector = rule.raws.selector
17 ? rule.raws.selector.raw
18 : rule.selector;
19
20 const fixedSelector = parseSelector(
21 selector,
22 opts.result,
23 rule,
24 selectorTree => {
25 selectorTree.walkCombinators(node => {
26 // Ignore spaced descendant combinator
27 if (/\s/.test(node.value)) {
28 return;
29 }
30
31 // Check the exist of node in prev of the combinator.
32 // in case some that aren't the first begin with combinators (nesting syntax)
33 if (opts.locationType === "before" && !node.prev()) {
34 return;
35 }
36
37 const parentParentNode = node.parent && node.parent.parent;
38
39 // Ignore pseudo-classes selector like `.foo:nth-child(2n + 1) {}`
40 if (parentParentNode && parentParentNode.type === "pseudo") {
41 return;
42 }
43
44 const sourceIndex = node.sourceIndex;
45 const index =
46 node.value.length > 1 && opts.locationType === "before"
47 ? sourceIndex
48 : sourceIndex + node.value.length - 1;
49
50 check(selector, node, index, rule, sourceIndex);
51 });
52 }
53 );
54
55 if (hasFixed) {
56 if (!rule.raws.selector) {
57 rule.selector = fixedSelector;
58 } else {
59 rule.raws.selector.raw = fixedSelector;
60 }
61 }
62 });
63
64 function check(source, combinator, index, node, sourceIndex) {
65 opts.locationChecker({
66 source,
67 index,
68 errTarget: combinator.value,
69 err: m => {
70 if (opts.fix && opts.fix(combinator)) {
71 hasFixed = true;
72
73 return;
74 }
75
76 report({
77 message: m,
78 node,
79 index: sourceIndex,
80 result: opts.result,
81 ruleName: opts.checkedRuleName
82 });
83 }
84 });
85 }
86};