UNPKG

1.9 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 ? rule.raws.selector.raw : rule.selector;
17
18 const fixedSelector = parseSelector(selector, opts.result, rule, (selectorTree) => {
19 selectorTree.walkCombinators((node) => {
20 // Ignore spaced descendant combinator
21 if (/\s/.test(node.value)) {
22 return;
23 }
24
25 // Check the exist of node in prev of the combinator.
26 // in case some that aren't the first begin with combinators (nesting syntax)
27 if (opts.locationType === 'before' && !node.prev()) {
28 return;
29 }
30
31 const parentParentNode = node.parent && node.parent.parent;
32
33 // Ignore pseudo-classes selector like `.foo:nth-child(2n + 1) {}`
34 if (parentParentNode && parentParentNode.type === 'pseudo') {
35 return;
36 }
37
38 const sourceIndex = node.sourceIndex;
39 const index =
40 node.value.length > 1 && opts.locationType === 'before'
41 ? sourceIndex
42 : sourceIndex + node.value.length - 1;
43
44 check(selector, node, index, rule, sourceIndex);
45 });
46 });
47
48 if (hasFixed) {
49 if (!rule.raws.selector) {
50 rule.selector = fixedSelector;
51 } else {
52 rule.raws.selector.raw = fixedSelector;
53 }
54 }
55 });
56
57 function check(source, combinator, index, node, sourceIndex) {
58 opts.locationChecker({
59 source,
60 index,
61 errTarget: combinator.value,
62 err: (m) => {
63 if (opts.fix && opts.fix(combinator)) {
64 hasFixed = true;
65
66 return;
67 }
68
69 report({
70 message: m,
71 node,
72 index: sourceIndex,
73 result: opts.result,
74 ruleName: opts.checkedRuleName,
75 });
76 },
77 });
78 }
79};