index.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. 'use strict';
  2. const atRuleParamIndex = require('../../utils/atRuleParamIndex');
  3. const mediaFeatureColonSpaceChecker = require('../mediaFeatureColonSpaceChecker');
  4. const ruleMessages = require('../../utils/ruleMessages');
  5. const validateOptions = require('../../utils/validateOptions');
  6. const whitespaceChecker = require('../../utils/whitespaceChecker');
  7. const ruleName = 'media-feature-colon-space-before';
  8. const messages = ruleMessages(ruleName, {
  9. expectedBefore: () => 'Expected single space before ":"',
  10. rejectedBefore: () => 'Unexpected whitespace before ":"',
  11. });
  12. const meta = {
  13. url: 'https://stylelint.io/user-guide/rules/list/media-feature-colon-space-before',
  14. };
  15. /** @type {import('stylelint').Rule} */
  16. const rule = (primary, _secondaryOptions, context) => {
  17. const checker = whitespaceChecker('space', primary, messages);
  18. return (root, result) => {
  19. const validOptions = validateOptions(result, ruleName, {
  20. actual: primary,
  21. possible: ['always', 'never'],
  22. });
  23. if (!validOptions) {
  24. return;
  25. }
  26. /** @type {Map<import('postcss').AtRule, number[]> | undefined} */
  27. let fixData;
  28. mediaFeatureColonSpaceChecker({
  29. root,
  30. result,
  31. locationChecker: checker.before,
  32. checkedRuleName: ruleName,
  33. fix: context.fix
  34. ? (atRule, index) => {
  35. const paramColonIndex = index - atRuleParamIndex(atRule);
  36. fixData = fixData || new Map();
  37. const colonIndices = fixData.get(atRule) || [];
  38. colonIndices.push(paramColonIndex);
  39. fixData.set(atRule, colonIndices);
  40. return true;
  41. }
  42. : null,
  43. });
  44. if (fixData) {
  45. for (const [atRule, colonIndices] of fixData.entries()) {
  46. let params = atRule.raws.params ? atRule.raws.params.raw : atRule.params;
  47. for (const index of colonIndices.sort((a, b) => b - a)) {
  48. const beforeColon = params.slice(0, index);
  49. const afterColon = params.slice(index);
  50. if (primary === 'always') {
  51. params = beforeColon.replace(/\s*$/, ' ') + afterColon;
  52. } else if (primary === 'never') {
  53. params = beforeColon.replace(/\s*$/, '') + afterColon;
  54. }
  55. }
  56. if (atRule.raws.params) {
  57. atRule.raws.params.raw = params;
  58. } else {
  59. atRule.params = params;
  60. }
  61. }
  62. }
  63. };
  64. };
  65. rule.ruleName = ruleName;
  66. rule.messages = messages;
  67. rule.meta = meta;
  68. module.exports = rule;