static-class-names-order.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. categories: undefined
  20. },
  21. fixable: 'code',
  22. schema: []
  23. },
  24. /** @param {RuleContext} context */
  25. create: (context) => {
  26. return defineTemplateBodyVisitor(context, {
  27. /** @param {VAttribute} node */
  28. "VAttribute[directive=false][key.name='class']"(node) {
  29. const value = node.value
  30. if (!value) {
  31. return
  32. }
  33. const classList = value.value
  34. const classListWithWhitespace = classList.split(/(\s+)/)
  35. // Detect and reuse any type of whitespace.
  36. let divider = ''
  37. if (classListWithWhitespace.length > 1) {
  38. divider = classListWithWhitespace[1]
  39. }
  40. const classListNoWhitespace = classListWithWhitespace.filter(
  41. (className) => className.trim() !== ''
  42. )
  43. const classListSorted = classListNoWhitespace.sort().join(divider)
  44. if (classList !== classListSorted) {
  45. context.report({
  46. node,
  47. loc: node.loc,
  48. message: 'Classes should be ordered alphabetically.',
  49. fix: (fixer) => fixer.replaceText(value, `"${classListSorted}"`)
  50. })
  51. }
  52. }
  53. })
  54. }
  55. }