v-for-delimiter-style.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /**
  2. * @fileoverview enforce `v-for` directive's delimiter style
  3. * @author Flo Edelmann
  4. * @copyright 2020 Flo Edelmann. All rights reserved.
  5. * See LICENSE file in root directory for full license.
  6. */
  7. 'use strict'
  8. // ------------------------------------------------------------------------------
  9. // Requirements
  10. // ------------------------------------------------------------------------------
  11. const utils = require('../utils')
  12. // ------------------------------------------------------------------------------
  13. // Rule Definition
  14. // ------------------------------------------------------------------------------
  15. module.exports = {
  16. meta: {
  17. type: 'layout',
  18. docs: {
  19. description: "enforce `v-for` directive's delimiter style",
  20. categories: undefined,
  21. recommended: false,
  22. url: 'https://eslint.vuejs.org/rules/v-for-delimiter-style.html'
  23. },
  24. fixable: 'code',
  25. schema: [{ enum: ['in', 'of'] }]
  26. },
  27. /** @param {RuleContext} context */
  28. create(context) {
  29. const preferredDelimiter =
  30. /** @type {string|undefined} */ (context.options[0]) || 'in'
  31. return utils.defineTemplateBodyVisitor(context, {
  32. /** @param {VForExpression} node */
  33. VForExpression(node) {
  34. const tokenStore =
  35. context.parserServices.getTemplateBodyTokenStore &&
  36. context.parserServices.getTemplateBodyTokenStore()
  37. const delimiterToken = /** @type {Token} */ (
  38. tokenStore.getTokenAfter(
  39. node.left.length
  40. ? node.left[node.left.length - 1]
  41. : tokenStore.getFirstToken(node),
  42. (token) => token.type !== 'Punctuator' || token.value !== ')'
  43. )
  44. )
  45. if (delimiterToken.value === preferredDelimiter) {
  46. return
  47. }
  48. context.report({
  49. node,
  50. loc: node.loc,
  51. message: `Expected '{{preferredDelimiter}}' instead of '{{usedDelimiter}}' in 'v-for'.`,
  52. data: {
  53. preferredDelimiter,
  54. usedDelimiter: delimiterToken.value
  55. },
  56. *fix(fixer) {
  57. yield fixer.replaceText(delimiterToken, preferredDelimiter)
  58. }
  59. })
  60. }
  61. })
  62. }
  63. }