no-duplicate-attributes.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. /**
  2. * @author Toru Nagashima
  3. * @copyright 2017 Toru Nagashima. All rights reserved.
  4. * See LICENSE file in root directory for full license.
  5. */
  6. 'use strict'
  7. const utils = require('../utils')
  8. /**
  9. * Get the name of the given attribute node.
  10. * @param {VAttribute | VDirective} attribute The attribute node to get.
  11. * @returns {string | null} The name of the attribute.
  12. */
  13. function getName(attribute) {
  14. if (!attribute.directive) {
  15. return attribute.key.name
  16. }
  17. if (attribute.key.name.name === 'bind') {
  18. return (
  19. (attribute.key.argument &&
  20. attribute.key.argument.type === 'VIdentifier' &&
  21. attribute.key.argument.name) ||
  22. null
  23. )
  24. }
  25. return null
  26. }
  27. module.exports = {
  28. meta: {
  29. type: 'problem',
  30. docs: {
  31. description: 'disallow duplication of attributes',
  32. categories: ['vue3-essential', 'essential'],
  33. url: 'https://eslint.vuejs.org/rules/no-duplicate-attributes.html'
  34. },
  35. fixable: null,
  36. schema: [
  37. {
  38. type: 'object',
  39. properties: {
  40. allowCoexistClass: {
  41. type: 'boolean'
  42. },
  43. allowCoexistStyle: {
  44. type: 'boolean'
  45. }
  46. },
  47. additionalProperties: false
  48. }
  49. ]
  50. },
  51. /** @param {RuleContext} context */
  52. create(context) {
  53. const options = context.options[0] || {}
  54. const allowCoexistStyle = options.allowCoexistStyle !== false
  55. const allowCoexistClass = options.allowCoexistClass !== false
  56. /** @type {Set<string>} */
  57. const directiveNames = new Set()
  58. /** @type {Set<string>} */
  59. const attributeNames = new Set()
  60. /**
  61. * @param {string} name
  62. * @param {boolean} isDirective
  63. */
  64. function isDuplicate(name, isDirective) {
  65. if (
  66. (allowCoexistStyle && name === 'style') ||
  67. (allowCoexistClass && name === 'class')
  68. ) {
  69. return isDirective ? directiveNames.has(name) : attributeNames.has(name)
  70. }
  71. return directiveNames.has(name) || attributeNames.has(name)
  72. }
  73. return utils.defineTemplateBodyVisitor(context, {
  74. VStartTag() {
  75. directiveNames.clear()
  76. attributeNames.clear()
  77. },
  78. VAttribute(node) {
  79. const name = getName(node)
  80. if (name == null) {
  81. return
  82. }
  83. if (isDuplicate(name, node.directive)) {
  84. context.report({
  85. node,
  86. loc: node.loc,
  87. message: "Duplicate attribute '{{name}}'.",
  88. data: { name }
  89. })
  90. }
  91. if (node.directive) {
  92. directiveNames.add(name)
  93. } else {
  94. attributeNames.add(name)
  95. }
  96. }
  97. })
  98. }
  99. }