1 |
|
2 |
|
3 | 'use strict';
|
4 |
|
5 | const atRuleParamIndex = require('../../utils/atRuleParamIndex');
|
6 | const findMediaOperator = require('../findMediaOperator');
|
7 | const report = require('../../utils/report');
|
8 | const ruleMessages = require('../../utils/ruleMessages');
|
9 | const validateOptions = require('../../utils/validateOptions');
|
10 | const whitespaceChecker = require('../../utils/whitespaceChecker');
|
11 |
|
12 | const ruleName = 'media-feature-range-operator-space-after';
|
13 |
|
14 | const messages = ruleMessages(ruleName, {
|
15 | expectedAfter: () => 'Expected single space after range operator',
|
16 | rejectedAfter: () => 'Unexpected whitespace after range operator',
|
17 | });
|
18 |
|
19 | function rule(expectation, options, context) {
|
20 | const checker = whitespaceChecker('space', expectation, messages);
|
21 |
|
22 | return (root, result) => {
|
23 | const validOptions = validateOptions(result, ruleName, {
|
24 | actual: expectation,
|
25 | possible: ['always', 'never'],
|
26 | });
|
27 |
|
28 | if (!validOptions) {
|
29 | return;
|
30 | }
|
31 |
|
32 | root.walkAtRules(/^media$/i, (atRule) => {
|
33 | const fixOperatorIndices = [];
|
34 | const fix = context.fix ? (index) => fixOperatorIndices.push(index) : null;
|
35 |
|
36 | findMediaOperator(atRule, (match, params, node) => {
|
37 | checkAfterOperator(match, params, node, fix);
|
38 | });
|
39 |
|
40 | if (fixOperatorIndices.length) {
|
41 | let params = atRule.raws.params ? atRule.raws.params.raw : atRule.params;
|
42 |
|
43 | fixOperatorIndices
|
44 | .sort((a, b) => b - a)
|
45 | .forEach((index) => {
|
46 | const beforeOperator = params.slice(0, index + 1);
|
47 | const afterOperator = params.slice(index + 1);
|
48 |
|
49 | if (expectation === 'always') {
|
50 | params = beforeOperator + afterOperator.replace(/^\s*/, ' ');
|
51 | } else if (expectation === 'never') {
|
52 | params = beforeOperator + afterOperator.replace(/^\s*/, '');
|
53 | }
|
54 | });
|
55 |
|
56 | if (atRule.raws.params) {
|
57 | atRule.raws.params.raw = params;
|
58 | } else {
|
59 | atRule.params = params;
|
60 | }
|
61 | }
|
62 | });
|
63 |
|
64 | function checkAfterOperator(match, params, node, fix) {
|
65 | const endIndex = match.startIndex + match.target.length - 1;
|
66 |
|
67 | checker.after({
|
68 | source: params,
|
69 | index: endIndex,
|
70 | err: (m) => {
|
71 | if (fix) {
|
72 | fix(endIndex);
|
73 |
|
74 | return;
|
75 | }
|
76 |
|
77 | report({
|
78 | message: m,
|
79 | node,
|
80 | index: endIndex + atRuleParamIndex(node) + 1,
|
81 | result,
|
82 | ruleName,
|
83 | });
|
84 | },
|
85 | });
|
86 | }
|
87 | };
|
88 | }
|
89 |
|
90 | rule.ruleName = ruleName;
|
91 | rule.messages = messages;
|
92 | module.exports = rule;
|