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