static-class-names-order.js 1.5 KB

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