UNPKG

2.58 kBJavaScriptView Raw
1'use strict';
2
3const atRuleParamIndex = require('../../utils/atRuleParamIndex');
4const mediaQueryListCommaWhitespaceChecker = require('../mediaQueryListCommaWhitespaceChecker');
5const ruleMessages = require('../../utils/ruleMessages');
6const validateOptions = require('../../utils/validateOptions');
7const whitespaceChecker = require('../../utils/whitespaceChecker');
8
9const ruleName = 'media-query-list-comma-space-after';
10
11const messages = ruleMessages(ruleName, {
12 expectedAfter: () => 'Expected single space after ","',
13 rejectedAfter: () => 'Unexpected whitespace after ","',
14 expectedAfterSingleLine: () => 'Expected single space after "," in a single-line list',
15 rejectedAfterSingleLine: () => 'Unexpected whitespace after "," in a single-line list',
16});
17
18const meta = {
19 url: 'https://stylelint.io/user-guide/rules/list/media-query-list-comma-space-after',
20};
21
22/** @type {import('stylelint').Rule} */
23const rule = (primary, _secondaryOptions, context) => {
24 const checker = whitespaceChecker('space', primary, messages);
25
26 return (root, result) => {
27 const validOptions = validateOptions(result, ruleName, {
28 actual: primary,
29 possible: ['always', 'never', 'always-single-line', 'never-single-line'],
30 });
31
32 if (!validOptions) {
33 return;
34 }
35
36 /** @type {Map<import('postcss').AtRule, number[]> | undefined} */
37 let fixData;
38
39 mediaQueryListCommaWhitespaceChecker({
40 root,
41 result,
42 locationChecker: checker.after,
43 checkedRuleName: ruleName,
44 fix: context.fix
45 ? (atRule, index) => {
46 const paramCommaIndex = index - atRuleParamIndex(atRule);
47
48 fixData = fixData || new Map();
49 const commaIndices = fixData.get(atRule) || [];
50
51 commaIndices.push(paramCommaIndex);
52 fixData.set(atRule, commaIndices);
53
54 return true;
55 }
56 : null,
57 });
58
59 if (fixData) {
60 for (const [atRule, commaIndices] of fixData.entries()) {
61 let params = atRule.raws.params ? atRule.raws.params.raw : atRule.params;
62
63 for (const index of commaIndices.sort((a, b) => b - a)) {
64 const beforeComma = params.slice(0, index + 1);
65 const afterComma = params.slice(index + 1);
66
67 if (primary.startsWith('always')) {
68 params = beforeComma + afterComma.replace(/^\s*/, ' ');
69 } else if (primary.startsWith('never')) {
70 params = beforeComma + afterComma.replace(/^\s*/, '');
71 }
72 }
73
74 if (atRule.raws.params) {
75 atRule.raws.params.raw = params;
76 } else {
77 atRule.params = params;
78 }
79 }
80 }
81 };
82};
83
84rule.ruleName = ruleName;
85rule.messages = messages;
86rule.meta = meta;
87module.exports = rule;