index.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. 'use strict';
  2. const declarationBangSpaceChecker = require('../declarationBangSpaceChecker');
  3. const declarationValueIndex = require('../../utils/declarationValueIndex');
  4. const getDeclarationValue = require('../../utils/getDeclarationValue');
  5. const ruleMessages = require('../../utils/ruleMessages');
  6. const setDeclarationValue = require('../../utils/setDeclarationValue');
  7. const validateOptions = require('../../utils/validateOptions');
  8. const whitespaceChecker = require('../../utils/whitespaceChecker');
  9. const ruleName = 'declaration-bang-space-after';
  10. const messages = ruleMessages(ruleName, {
  11. expectedAfter: () => 'Expected single space after "!"',
  12. rejectedAfter: () => 'Unexpected whitespace after "!"',
  13. });
  14. const meta = {
  15. url: 'https://stylelint.io/user-guide/rules/list/declaration-bang-space-after',
  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. declarationBangSpaceChecker({
  29. root,
  30. result,
  31. locationChecker: checker.after,
  32. checkedRuleName: ruleName,
  33. fix: context.fix
  34. ? (decl, index) => {
  35. let bangIndex = index - declarationValueIndex(decl);
  36. const declValue = getDeclarationValue(decl);
  37. let target;
  38. /** @type {(value: string) => void} */
  39. let setFixed;
  40. if (bangIndex < declValue.length) {
  41. target = declValue;
  42. setFixed = (value) => {
  43. setDeclarationValue(decl, value);
  44. };
  45. } else if (decl.important) {
  46. target = decl.raws.important || ' !important';
  47. bangIndex -= declValue.length;
  48. setFixed = (value) => {
  49. decl.raws.important = value;
  50. };
  51. } else {
  52. return false; // not standard
  53. }
  54. const targetBefore = target.slice(0, bangIndex + 1);
  55. const targetAfter = target.slice(bangIndex + 1);
  56. if (primary === 'always') {
  57. setFixed(targetBefore + targetAfter.replace(/^\s*/, ' '));
  58. return true;
  59. }
  60. if (primary === 'never') {
  61. setFixed(targetBefore + targetAfter.replace(/^\s*/, ''));
  62. return true;
  63. }
  64. return false;
  65. }
  66. : null,
  67. });
  68. };
  69. };
  70. rule.ruleName = ruleName;
  71. rule.messages = messages;
  72. rule.meta = meta;
  73. module.exports = rule;