static-class-names-order.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. },
  18. /** @param {RuleContext} context */
  19. create: (context) =>
  20. defineTemplateBodyVisitor(context, {
  21. /** @param {VAttribute} node */
  22. "VAttribute[directive=false][key.name='class']"(node) {
  23. const value = node.value
  24. if (!value) {
  25. return
  26. }
  27. const classList = 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(
  35. (className) => className.trim() !== ''
  36. )
  37. const classListSorted = classListNoWhitespace.sort().join(divider)
  38. if (classList !== classListSorted) {
  39. context.report({
  40. node,
  41. loc: node.loc,
  42. message: 'Classes should be ordered alphabetically.',
  43. fix: (fixer) => fixer.replaceText(value, `"${classListSorted}"`)
  44. })
  45. }
  46. }
  47. })
  48. }