no-deprecated-v-on-number-modifiers.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /**
  2. * @fileoverview disallow using deprecated number (keycode) modifiers
  3. * @author yoyo930021
  4. */
  5. 'use strict'
  6. // ------------------------------------------------------------------------------
  7. // Requirements
  8. // ------------------------------------------------------------------------------
  9. const utils = require('../utils')
  10. const keyCodeToKey = require('../utils/keycode-to-key')
  11. // ------------------------------------------------------------------------------
  12. // Rule Definition
  13. // ------------------------------------------------------------------------------
  14. module.exports = {
  15. meta: {
  16. type: 'problem',
  17. docs: {
  18. description:
  19. 'disallow using deprecated number (keycode) modifiers (in Vue.js 3.0.0+)',
  20. categories: ['vue3-essential'],
  21. url: 'https://eslint.vuejs.org/rules/no-deprecated-v-on-number-modifiers.html'
  22. },
  23. fixable: 'code',
  24. schema: [],
  25. messages: {
  26. numberModifierIsDeprecated:
  27. "'KeyboardEvent.keyCode' modifier on 'v-on' directive is deprecated. Using 'KeyboardEvent.key' instead."
  28. }
  29. },
  30. /** @param {RuleContext} context */
  31. create(context) {
  32. return utils.defineTemplateBodyVisitor(context, {
  33. /** @param {VDirectiveKey} node */
  34. "VAttribute[directive=true][key.name.name='on'] > VDirectiveKey"(node) {
  35. const modifier = node.modifiers.find((mod) =>
  36. Number.isInteger(parseInt(mod.name, 10))
  37. )
  38. if (!modifier) return
  39. const keyCodes = parseInt(modifier.name, 10)
  40. if (keyCodes > 9 || keyCodes < 0) {
  41. context.report({
  42. node: modifier,
  43. messageId: 'numberModifierIsDeprecated',
  44. fix(fixer) {
  45. const key = keyCodeToKey[keyCodes]
  46. if (!key) return null
  47. return fixer.replaceText(modifier, `${key}`)
  48. }
  49. })
  50. }
  51. }
  52. })
  53. }
  54. }