static-class-names-order.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /**
  2. * @fileoverview Alphabetizes static class names.
  3. * @author Maciej Chmurski
  4. */
  5. 'use strict'
  6. // ------------------------------------------------------------------------------
  7. // Requirements
  8. // ------------------------------------------------------------------------------
  9. const { defineTemplateBodyVisitor } = require('../utils')
  10. // ------------------------------------------------------------------------------
  11. // Rule Definition
  12. // ------------------------------------------------------------------------------
  13. module.exports = {
  14. meta: {
  15. type: 'suggestion',
  16. docs: {
  17. url: 'https://eslint.vuejs.org/rules/static-class-names-order.html',
  18. description: 'enforce static class names order',
  19. category: undefined
  20. },
  21. fixable: 'code',
  22. schema: []
  23. },
  24. create: context => {
  25. return defineTemplateBodyVisitor(context, {
  26. "VAttribute[directive=false][key.name='class']" (node) {
  27. const classList = node.value.value
  28. const classListWithWhitespace = classList.split(/(\s+)/)
  29. // Detect and reuse any type of whitespace.
  30. let divider = ''
  31. if (classListWithWhitespace.length > 1) {
  32. divider = classListWithWhitespace[1]
  33. }
  34. const classListNoWhitespace = classListWithWhitespace.filter(className => className.trim() !== '')
  35. const classListSorted = classListNoWhitespace.sort().join(divider)
  36. if (classList !== classListSorted) {
  37. context.report({
  38. node,
  39. loc: node.loc,
  40. message: 'Classes should be ordered alphabetically.',
  41. fix: (fixer) => fixer.replaceTextRange(
  42. [node.value.range[0], node.value.range[1]], `"${classListSorted}"`
  43. )
  44. })
  45. }
  46. }
  47. })
  48. }
  49. }