index.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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/media-feature-colon-space-before',
  14. fixable: true,
  15. deprecated: true,
  16. };
  17. /** @type {import('stylelint').Rule} */
  18. const rule = (primary, _secondaryOptions, context) => {
  19. const checker = whitespaceChecker('space', primary, messages);
  20. return (root, result) => {
  21. const validOptions = validateOptions(result, ruleName, {
  22. actual: primary,
  23. possible: ['always', 'never'],
  24. });
  25. if (!validOptions) {
  26. return;
  27. }
  28. /** @type {Map<import('postcss').AtRule, number[]> | undefined} */
  29. let fixData;
  30. mediaFeatureColonSpaceChecker({
  31. root,
  32. result,
  33. locationChecker: checker.before,
  34. checkedRuleName: ruleName,
  35. fix: context.fix
  36. ? (atRule, index) => {
  37. const paramColonIndex = index - atRuleParamIndex(atRule);
  38. fixData = fixData || new Map();
  39. const colonIndices = fixData.get(atRule) || [];
  40. colonIndices.push(paramColonIndex);
  41. fixData.set(atRule, colonIndices);
  42. return true;
  43. }
  44. : null,
  45. });
  46. if (fixData) {
  47. for (const [atRule, colonIndices] of fixData.entries()) {
  48. let params = atRule.raws.params ? atRule.raws.params.raw : atRule.params;
  49. for (const index of colonIndices.sort((a, b) => b - a)) {
  50. const beforeColon = params.slice(0, index);
  51. const afterColon = params.slice(index);
  52. if (primary === 'always') {
  53. params = beforeColon.replace(/\s*$/, ' ') + afterColon;
  54. } else if (primary === 'never') {
  55. params = beforeColon.replace(/\s*$/, '') + afterColon;
  56. }
  57. }
  58. if (atRule.raws.params) {
  59. atRule.raws.params.raw = params;
  60. } else {
  61. atRule.params = params;
  62. }
  63. }
  64. }
  65. };
  66. };
  67. rule.ruleName = ruleName;
  68. rule.messages = messages;
  69. rule.meta = meta;
  70. module.exports = rule;