valid-v-slot.js 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. /**
  2. * @author Toru Nagashima
  3. * See LICENSE file in root directory for full license.
  4. */
  5. 'use strict'
  6. const utils = require('../utils')
  7. /**
  8. * Get all `v-slot` directives on a given element.
  9. * @param {VElement} node The VElement node to check.
  10. * @returns {VAttribute[]} The array of `v-slot` directives.
  11. */
  12. function getSlotDirectivesOnElement (node) {
  13. return node.startTag.attributes.filter(attribute =>
  14. attribute.directive &&
  15. attribute.key.name.name === 'slot'
  16. )
  17. }
  18. /**
  19. * Get all `v-slot` directives on the children of a given element.
  20. * @param {VElement} node The VElement node to check.
  21. * @returns {VAttribute[][]}
  22. * The array of the group of `v-slot` directives.
  23. * The group bundles `v-slot` directives of element sequence which is connected
  24. * by `v-if`/`v-else-if`/`v-else`.
  25. */
  26. function getSlotDirectivesOnChildren (node) {
  27. return node.children
  28. .reduce(({ groups, vIf }, childNode) => {
  29. if (childNode.type === 'VElement') {
  30. let connected
  31. if (utils.hasDirective(childNode, 'if')) {
  32. connected = false
  33. vIf = true
  34. } else if (utils.hasDirective(childNode, 'else-if')) {
  35. connected = vIf
  36. vIf = true
  37. } else if (utils.hasDirective(childNode, 'else')) {
  38. connected = vIf
  39. vIf = false
  40. } else {
  41. connected = false
  42. vIf = false
  43. }
  44. if (connected) {
  45. groups[groups.length - 1].push(childNode)
  46. } else {
  47. groups.push([childNode])
  48. }
  49. } else if (childNode.type !== 'VText' || childNode.value.trim() !== '') {
  50. vIf = false
  51. }
  52. return { groups, vIf }
  53. }, { groups: [], vIf: false })
  54. .groups
  55. .map(group =>
  56. group
  57. .map(childElement =>
  58. childElement.name === 'template'
  59. ? utils.getDirective(childElement, 'slot')
  60. : null
  61. )
  62. .filter(Boolean)
  63. )
  64. .filter(group => group.length >= 1)
  65. }
  66. /**
  67. * Get the normalized name of a given `v-slot` directive node.
  68. * @param {VAttribute} node The `v-slot` directive node.
  69. * @returns {string} The normalized name.
  70. */
  71. function getNormalizedName (node, sourceCode) {
  72. return node.key.argument == null ? 'default' : sourceCode.getText(node.key.argument)
  73. }
  74. /**
  75. * Get all `v-slot` directives which are distributed to the same slot as a given `v-slot` directive node.
  76. * @param {VAttribute[][]} vSlotGroups The result of `getAllNamedSlotElements()`.
  77. * @param {VElement} currentVSlot The current `v-slot` directive node.
  78. * @returns {VAttribute[][]} The array of the group of `v-slot` directives.
  79. */
  80. function filterSameSlot (vSlotGroups, currentVSlot, sourceCode) {
  81. const currentName = getNormalizedName(currentVSlot, sourceCode)
  82. return vSlotGroups
  83. .map(vSlots =>
  84. vSlots.filter(vSlot => getNormalizedName(vSlot, sourceCode) === currentName)
  85. )
  86. .filter(slots => slots.length >= 1)
  87. }
  88. /**
  89. * Check whether a given argument node is using an iteration variable that the element defined.
  90. * @param {VExpressionContainer|VIdentifier|null} argument The argument node to check.
  91. * @param {VElement} element The element node which has the argument.
  92. * @returns {boolean} `true` if the argument node is using the iteration variable.
  93. */
  94. function isUsingIterationVar (argument, element) {
  95. if (argument && argument.type === 'VExpressionContainer') {
  96. for (const { variable } of argument.references) {
  97. if (
  98. variable != null &&
  99. variable.kind === 'v-for' &&
  100. variable.id.range[0] > element.startTag.range[0] &&
  101. variable.id.range[1] < element.startTag.range[1]
  102. ) {
  103. return true
  104. }
  105. }
  106. }
  107. return false
  108. }
  109. /**
  110. * Check whether a given argument node is using an scope variable that the directive defined.
  111. * @param {VAttribute} vSlot The `v-slot` directive to check.
  112. * @returns {boolean} `true` if that argument node is using a scope variable the directive defined.
  113. */
  114. function isUsingScopeVar (vSlot) {
  115. const argument = vSlot.key.argument
  116. const value = vSlot.value
  117. if (argument && value && argument.type === 'VExpressionContainer') {
  118. for (const { variable } of argument.references) {
  119. if (
  120. variable != null &&
  121. variable.kind === 'scope' &&
  122. variable.id.range[0] > value.range[0] &&
  123. variable.id.range[1] < value.range[1]
  124. ) {
  125. return true
  126. }
  127. }
  128. }
  129. }
  130. module.exports = {
  131. meta: {
  132. type: 'problem',
  133. docs: {
  134. description: 'enforce valid `v-slot` directives',
  135. category: undefined, // essential
  136. // TODO Change with major version.
  137. // category: 'essential',
  138. url: 'https://eslint.vuejs.org/rules/valid-v-slot.html'
  139. },
  140. fixable: null,
  141. schema: [],
  142. messages: {
  143. ownerMustBeCustomElement: "'v-slot' directive must be owned by a custom element, but '{{name}}' is not.",
  144. namedSlotMustBeOnTemplate: "Named slots must use '<template>' on a custom element.",
  145. defaultSlotMustBeOnTemplate: "Default slot must use '<template>' on a custom element when there are other named slots.",
  146. disallowDuplicateSlotsOnElement: "An element cannot have multiple 'v-slot' directives.",
  147. disallowDuplicateSlotsOnChildren: "An element cannot have multiple '<template>' elements which are distributed to the same slot.",
  148. disallowArgumentUseSlotParams: "Dynamic argument of 'v-slot' directive cannot use that slot parameter.",
  149. disallowAnyModifier: "'v-slot' directive doesn't support any modifier.",
  150. requireAttributeValue: "'v-slot' directive on a custom element requires that attribute value."
  151. }
  152. },
  153. create (context) {
  154. const sourceCode = context.getSourceCode()
  155. return utils.defineTemplateBodyVisitor(context, {
  156. "VAttribute[directive=true][key.name.name='slot']" (node) {
  157. const isDefaultSlot = node.key.argument == null || node.key.argument.name === 'default'
  158. const element = node.parent.parent
  159. const parentElement = element.parent
  160. const ownerElement = element.name === 'template' ? parentElement : element
  161. const vSlotsOnElement = getSlotDirectivesOnElement(element)
  162. const vSlotGroupsOnChildren = getSlotDirectivesOnChildren(ownerElement)
  163. // Verify location.
  164. if (!utils.isCustomComponent(ownerElement)) {
  165. context.report({
  166. node,
  167. messageId: 'ownerMustBeCustomElement',
  168. data: { name: ownerElement.rawName }
  169. })
  170. }
  171. if (!isDefaultSlot && element.name !== 'template') {
  172. context.report({
  173. node,
  174. messageId: 'namedSlotMustBeOnTemplate'
  175. })
  176. }
  177. if (ownerElement === element && vSlotGroupsOnChildren.length >= 1) {
  178. context.report({
  179. node,
  180. messageId: 'defaultSlotMustBeOnTemplate'
  181. })
  182. }
  183. // Verify duplication.
  184. if (vSlotsOnElement.length >= 2 && vSlotsOnElement[0] !== node) {
  185. // E.g., <my-component #one #two>
  186. context.report({
  187. node,
  188. messageId: 'disallowDuplicateSlotsOnElement'
  189. })
  190. }
  191. if (ownerElement === parentElement) {
  192. const vSlotGroupsOfSameSlot = filterSameSlot(vSlotGroupsOnChildren, node, sourceCode)
  193. const vFor = utils.getDirective(element, 'for')
  194. if (
  195. vSlotGroupsOfSameSlot.length >= 2 &&
  196. !vSlotGroupsOfSameSlot[0].includes(node)
  197. ) {
  198. // E.g., <template #one></template>
  199. // <template #one></template>
  200. context.report({
  201. node,
  202. messageId: 'disallowDuplicateSlotsOnChildren'
  203. })
  204. }
  205. if (vFor && !isUsingIterationVar(node.key.argument, element)) {
  206. // E.g., <template v-for="x of xs" #one></template>
  207. context.report({
  208. node,
  209. messageId: 'disallowDuplicateSlotsOnChildren'
  210. })
  211. }
  212. }
  213. // Verify argument.
  214. if (isUsingScopeVar(node)) {
  215. context.report({
  216. node,
  217. messageId: 'disallowArgumentUseSlotParams'
  218. })
  219. }
  220. // Verify modifiers.
  221. if (node.key.modifiers.length >= 1) {
  222. context.report({
  223. node,
  224. messageId: 'disallowAnyModifier'
  225. })
  226. }
  227. // Verify value.
  228. if (ownerElement === element && isDefaultSlot && !utils.hasAttributeValue(node)) {
  229. context.report({
  230. node,
  231. messageId: 'requireAttributeValue'
  232. })
  233. }
  234. }
  235. })
  236. }
  237. }