index.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. 'use strict';
  2. const blockString = require('../../utils/blockString');
  3. const hasBlock = require('../../utils/hasBlock');
  4. const rawNodeString = require('../../utils/rawNodeString');
  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. const ruleName = 'block-closing-brace-space-after';
  10. const messages = ruleMessages(ruleName, {
  11. expectedAfter: () => 'Expected single space after "}"',
  12. rejectedAfter: () => 'Unexpected whitespace after "}"',
  13. expectedAfterSingleLine: () => 'Expected single space after "}" of a single-line block',
  14. rejectedAfterSingleLine: () => 'Unexpected whitespace after "}" of a single-line block',
  15. expectedAfterMultiLine: () => 'Expected single space after "}" of a multi-line block',
  16. rejectedAfterMultiLine: () => 'Unexpected whitespace after "}" of a multi-line block',
  17. });
  18. const meta = {
  19. url: 'https://stylelint.io/user-guide/rules/list/block-closing-brace-space-after',
  20. };
  21. /** @type {import('stylelint').Rule} */
  22. const rule = (primary) => {
  23. const checker = whitespaceChecker('space', primary, messages);
  24. return function (root, result) {
  25. const validOptions = validateOptions(result, ruleName, {
  26. actual: primary,
  27. possible: [
  28. 'always',
  29. 'never',
  30. 'always-single-line',
  31. 'never-single-line',
  32. 'always-multi-line',
  33. 'never-multi-line',
  34. ],
  35. });
  36. if (!validOptions) {
  37. return;
  38. }
  39. // Check both kinds of statements: rules and at-rules
  40. root.walkRules(check);
  41. root.walkAtRules(check);
  42. /**
  43. * @param {import('postcss').Rule | import('postcss').AtRule} statement
  44. */
  45. function check(statement) {
  46. const nextNode = statement.next();
  47. if (!nextNode) {
  48. return;
  49. }
  50. if (!hasBlock(statement)) {
  51. return;
  52. }
  53. let reportIndex = statement.toString().length;
  54. let source = rawNodeString(nextNode);
  55. // Skip a semicolon at the beginning, if any
  56. if (source && source.startsWith(';')) {
  57. source = source.slice(1);
  58. reportIndex++;
  59. }
  60. checker.after({
  61. source,
  62. index: -1,
  63. lineCheckStr: blockString(statement),
  64. err: (msg) => {
  65. report({
  66. message: msg,
  67. node: statement,
  68. index: reportIndex,
  69. result,
  70. ruleName,
  71. });
  72. },
  73. });
  74. }
  75. };
  76. };
  77. rule.ruleName = ruleName;
  78. rule.messages = messages;
  79. rule.meta = meta;
  80. module.exports = rule;