index.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. 'use strict';
  2. const blockString = require('../../utils/blockString');
  3. const rawNodeString = require('../../utils/rawNodeString');
  4. const report = require('../../utils/report');
  5. const ruleMessages = require('../../utils/ruleMessages');
  6. const validateOptions = require('../../utils/validateOptions');
  7. const whitespaceChecker = require('../../utils/whitespaceChecker');
  8. const { isAtRule, isRule } = require('../../utils/typeGuards');
  9. const ruleName = 'declaration-block-semicolon-space-after';
  10. const messages = ruleMessages(ruleName, {
  11. expectedAfter: () => 'Expected single space after ";"',
  12. rejectedAfter: () => 'Unexpected whitespace after ";"',
  13. expectedAfterSingleLine: () =>
  14. 'Expected single space after ";" in a single-line declaration block',
  15. rejectedAfterSingleLine: () =>
  16. 'Unexpected whitespace after ";" in a single-line declaration block',
  17. });
  18. const meta = {
  19. url: 'https://stylelint.io/user-guide/rules/list/declaration-block-semicolon-space-after',
  20. };
  21. /** @type {import('stylelint').Rule} */
  22. const rule = (primary, _secondaryOptions, context) => {
  23. const checker = whitespaceChecker('space', primary, messages);
  24. return function (root, result) {
  25. const validOptions = validateOptions(result, ruleName, {
  26. actual: primary,
  27. possible: ['always', 'never', 'always-single-line', 'never-single-line'],
  28. });
  29. if (!validOptions) {
  30. return;
  31. }
  32. root.walkDecls((decl) => {
  33. // Ignore last declaration if there's no trailing semicolon
  34. const parentRule = decl.parent;
  35. if (!parentRule) throw new Error('A parent node must be present');
  36. if (!isAtRule(parentRule) && !isRule(parentRule)) {
  37. return;
  38. }
  39. if (!parentRule.raws.semicolon && parentRule.last === decl) {
  40. return;
  41. }
  42. const nextDecl = decl.next();
  43. if (!nextDecl) {
  44. return;
  45. }
  46. checker.after({
  47. source: rawNodeString(nextDecl),
  48. index: -1,
  49. lineCheckStr: blockString(parentRule),
  50. err: (m) => {
  51. if (context.fix) {
  52. if (primary.startsWith('always')) {
  53. nextDecl.raws.before = ' ';
  54. return;
  55. }
  56. if (primary.startsWith('never')) {
  57. nextDecl.raws.before = '';
  58. return;
  59. }
  60. }
  61. report({
  62. message: m,
  63. node: decl,
  64. index: decl.toString().length + 1,
  65. result,
  66. ruleName,
  67. });
  68. },
  69. });
  70. });
  71. };
  72. };
  73. rule.ruleName = ruleName;
  74. rule.messages = messages;
  75. rule.meta = meta;
  76. module.exports = rule;