valid-v-slot.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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. * @typedef { { expr: VForExpression, variables: VVariable[] } } VSlotVForVariables
  9. */
  10. /**
  11. * Get all `v-slot` directives on a given element.
  12. * @param {VElement} node The VElement node to check.
  13. * @returns {VDirective[]} The array of `v-slot` directives.
  14. */
  15. function getSlotDirectivesOnElement(node) {
  16. return utils.getDirectives(node, 'slot')
  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 {VDirective[][]}
  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. /** @type {VDirective[][]} */
  28. const groups = []
  29. for (const group of utils.iterateChildElementsChains(node)) {
  30. const slotDirs = group
  31. .map((childElement) =>
  32. childElement.name === 'template'
  33. ? utils.getDirective(childElement, 'slot')
  34. : null
  35. )
  36. .filter(utils.isDef)
  37. if (slotDirs.length > 0) {
  38. groups.push(slotDirs)
  39. }
  40. }
  41. return groups
  42. }
  43. /**
  44. * Get the normalized name of a given `v-slot` directive node with modifiers after `v-slot:` directive.
  45. * @param {VDirective} node The `v-slot` directive node.
  46. * @param {SourceCode} sourceCode The source code.
  47. * @returns {string} The normalized name.
  48. */
  49. function getNormalizedName(node, sourceCode) {
  50. if (node.key.argument == null) {
  51. return 'default'
  52. }
  53. return node.key.modifiers.length === 0
  54. ? sourceCode.getText(node.key.argument)
  55. : sourceCode.text.slice(node.key.argument.range[0], node.key.range[1])
  56. }
  57. /**
  58. * Get all `v-slot` directives which are distributed to the same slot as a given `v-slot` directive node.
  59. * @param {VDirective[][]} vSlotGroups The result of `getAllNamedSlotElements()`.
  60. * @param {VDirective} currentVSlot The current `v-slot` directive node.
  61. * @param {VSlotVForVariables | null} currentVSlotVForVars The current `v-for` variables.
  62. * @param {SourceCode} sourceCode The source code.
  63. * @param {ParserServices.TokenStore} tokenStore The token store.
  64. * @returns {VDirective[][]} The array of the group of `v-slot` directives.
  65. */
  66. function filterSameSlot(
  67. vSlotGroups,
  68. currentVSlot,
  69. currentVSlotVForVars,
  70. sourceCode,
  71. tokenStore
  72. ) {
  73. const currentName = getNormalizedName(currentVSlot, sourceCode)
  74. return vSlotGroups
  75. .map((vSlots) =>
  76. vSlots.filter((vSlot) => {
  77. if (getNormalizedName(vSlot, sourceCode) !== currentName) {
  78. return false
  79. }
  80. const vForExpr = getVSlotVForVariableIfUsingIterationVars(
  81. vSlot,
  82. utils.getDirective(vSlot.parent.parent, 'for')
  83. )
  84. if (!currentVSlotVForVars || !vForExpr) {
  85. return !currentVSlotVForVars && !vForExpr
  86. }
  87. if (
  88. !equalVSlotVForVariables(currentVSlotVForVars, vForExpr, tokenStore)
  89. ) {
  90. return false
  91. }
  92. //
  93. return true
  94. })
  95. )
  96. .filter((slots) => slots.length > 0)
  97. }
  98. /**
  99. * Determines whether the two given `v-slot` variables are considered to be equal.
  100. * @param {VSlotVForVariables} a First element.
  101. * @param {VSlotVForVariables} b Second element.
  102. * @param {ParserServices.TokenStore} tokenStore The token store.
  103. * @returns {boolean} `true` if the elements are considered to be equal.
  104. */
  105. function equalVSlotVForVariables(a, b, tokenStore) {
  106. if (a.variables.length !== b.variables.length) {
  107. return false
  108. }
  109. if (!equal(a.expr.right, b.expr.right)) {
  110. return false
  111. }
  112. const checkedVarNames = new Set()
  113. const len = Math.min(a.expr.left.length, b.expr.left.length)
  114. for (let index = 0; index < len; index++) {
  115. const aPtn = a.expr.left[index]
  116. const bPtn = b.expr.left[index]
  117. const aVar = a.variables.find(
  118. (v) => aPtn.range[0] <= v.id.range[0] && v.id.range[1] <= aPtn.range[1]
  119. )
  120. const bVar = b.variables.find(
  121. (v) => bPtn.range[0] <= v.id.range[0] && v.id.range[1] <= bPtn.range[1]
  122. )
  123. if (aVar && bVar) {
  124. if (aVar.id.name !== bVar.id.name) {
  125. return false
  126. }
  127. if (!equal(aPtn, bPtn)) {
  128. return false
  129. }
  130. checkedVarNames.add(aVar.id.name)
  131. } else if (aVar || bVar) {
  132. return false
  133. }
  134. }
  135. return a.variables.every(
  136. (v) =>
  137. checkedVarNames.has(v.id.name) ||
  138. b.variables.some((bv) => v.id.name === bv.id.name)
  139. )
  140. /**
  141. * Determines whether the two given nodes are considered to be equal.
  142. * @param {ASTNode} a First node.
  143. * @param {ASTNode} b Second node.
  144. * @returns {boolean} `true` if the nodes are considered to be equal.
  145. */
  146. function equal(a, b) {
  147. if (a.type !== b.type) {
  148. return false
  149. }
  150. return utils.equalTokens(a, b, tokenStore)
  151. }
  152. }
  153. /**
  154. * Gets the `v-for` directive and variable that provide the variables used by the given` v-slot` directive.
  155. * @param {VDirective} vSlot The current `v-slot` directive node.
  156. * @param {VDirective | null} [vFor] The current `v-for` directive node.
  157. * @returns { VSlotVForVariables | null } The VSlotVForVariable.
  158. */
  159. function getVSlotVForVariableIfUsingIterationVars(vSlot, vFor) {
  160. const expr =
  161. vFor && vFor.value && /** @type {VForExpression} */ (vFor.value.expression)
  162. const variables =
  163. expr && getUsingIterationVars(vSlot.key.argument, vSlot.parent.parent)
  164. return expr && variables && variables.length > 0 ? { expr, variables } : null
  165. }
  166. /**
  167. * Gets iterative variables if a given argument node is using iterative variables that the element defined.
  168. * @param {VExpressionContainer|VIdentifier|null} argument The argument node to check.
  169. * @param {VElement} element The element node which has the argument.
  170. * @returns {VVariable[]} The argument node is using iteration variables.
  171. */
  172. function getUsingIterationVars(argument, element) {
  173. const vars = []
  174. if (argument && argument.type === 'VExpressionContainer') {
  175. for (const { variable } of argument.references) {
  176. if (
  177. variable != null &&
  178. variable.kind === 'v-for' &&
  179. variable.id.range[0] > element.startTag.range[0] &&
  180. variable.id.range[1] < element.startTag.range[1]
  181. ) {
  182. vars.push(variable)
  183. }
  184. }
  185. }
  186. return vars
  187. }
  188. /**
  189. * Check whether a given argument node is using an scope variable that the directive defined.
  190. * @param {VDirective} vSlot The `v-slot` directive to check.
  191. * @returns {boolean} `true` if that argument node is using a scope variable the directive defined.
  192. */
  193. function isUsingScopeVar(vSlot) {
  194. const argument = vSlot.key.argument
  195. const value = vSlot.value
  196. if (argument && value && argument.type === 'VExpressionContainer') {
  197. for (const { variable } of argument.references) {
  198. if (
  199. variable != null &&
  200. variable.kind === 'scope' &&
  201. variable.id.range[0] > value.range[0] &&
  202. variable.id.range[1] < value.range[1]
  203. ) {
  204. return true
  205. }
  206. }
  207. }
  208. return false
  209. }
  210. /**
  211. * If `allowModifiers` option is set to `true`, check whether a given argument node has invalid modifiers like `v-slot.foo`.
  212. * Otherwise, check whether a given argument node has at least one modifier.
  213. * @param {VDirective} vSlot The `v-slot` directive to check.
  214. * @param {boolean} allowModifiers `allowModifiers` option in context.
  215. * @return {boolean} `true` if that argument node has invalid modifiers like `v-slot.foo`.
  216. */
  217. function hasInvalidModifiers(vSlot, allowModifiers) {
  218. return allowModifiers
  219. ? vSlot.key.argument == null && vSlot.key.modifiers.length > 0
  220. : vSlot.key.modifiers.length > 0
  221. }
  222. module.exports = {
  223. meta: {
  224. type: 'problem',
  225. docs: {
  226. description: 'enforce valid `v-slot` directives',
  227. categories: ['vue3-essential', 'vue2-essential'],
  228. url: 'https://eslint.vuejs.org/rules/valid-v-slot.html'
  229. },
  230. fixable: null,
  231. schema: [
  232. {
  233. type: 'object',
  234. properties: {
  235. allowModifiers: {
  236. type: 'boolean'
  237. }
  238. },
  239. additionalProperties: false
  240. }
  241. ],
  242. messages: {
  243. ownerMustBeCustomElement:
  244. "'v-slot' directive must be owned by a custom element, but '{{name}}' is not.",
  245. namedSlotMustBeOnTemplate:
  246. "Named slots must use '<template>' on a custom element.",
  247. defaultSlotMustBeOnTemplate:
  248. "Default slot must use '<template>' on a custom element when there are other named slots.",
  249. disallowDuplicateSlotsOnElement:
  250. "An element cannot have multiple 'v-slot' directives.",
  251. disallowDuplicateSlotsOnChildren:
  252. "An element cannot have multiple '<template>' elements which are distributed to the same slot.",
  253. disallowArgumentUseSlotParams:
  254. "Dynamic argument of 'v-slot' directive cannot use that slot parameter.",
  255. disallowAnyModifier: "'v-slot' directive doesn't support any modifier.",
  256. requireAttributeValue:
  257. "'v-slot' directive on a custom element requires that attribute value."
  258. }
  259. },
  260. /** @param {RuleContext} context */
  261. create(context) {
  262. const sourceCode = context.getSourceCode()
  263. const tokenStore =
  264. sourceCode.parserServices.getTemplateBodyTokenStore &&
  265. sourceCode.parserServices.getTemplateBodyTokenStore()
  266. const options = context.options[0] || {}
  267. const allowModifiers = options.allowModifiers === true
  268. return utils.defineTemplateBodyVisitor(context, {
  269. /** @param {VDirective} node */
  270. "VAttribute[directive=true][key.name.name='slot']"(node) {
  271. const isDefaultSlot =
  272. node.key.argument == null ||
  273. (node.key.argument.type === 'VIdentifier' &&
  274. node.key.argument.name === 'default')
  275. const element = node.parent.parent
  276. const parentElement = element.parent
  277. const ownerElement =
  278. element.name === 'template' ? parentElement : element
  279. if (ownerElement.type === 'VDocumentFragment') {
  280. return
  281. }
  282. const vSlotsOnElement = getSlotDirectivesOnElement(element)
  283. const vSlotGroupsOnChildren = getSlotDirectivesOnChildren(ownerElement)
  284. // Verify location.
  285. if (!utils.isCustomComponent(ownerElement)) {
  286. context.report({
  287. node,
  288. messageId: 'ownerMustBeCustomElement',
  289. data: { name: ownerElement.rawName }
  290. })
  291. }
  292. if (!isDefaultSlot && element.name !== 'template') {
  293. context.report({
  294. node,
  295. messageId: 'namedSlotMustBeOnTemplate'
  296. })
  297. }
  298. if (ownerElement === element && vSlotGroupsOnChildren.length > 0) {
  299. context.report({
  300. node,
  301. messageId: 'defaultSlotMustBeOnTemplate'
  302. })
  303. }
  304. // Verify duplication.
  305. if (vSlotsOnElement.length >= 2 && vSlotsOnElement[0] !== node) {
  306. // E.g., <my-component #one #two>
  307. context.report({
  308. node,
  309. messageId: 'disallowDuplicateSlotsOnElement'
  310. })
  311. }
  312. if (ownerElement === parentElement) {
  313. const vFor = utils.getDirective(element, 'for')
  314. const vSlotVForVar = getVSlotVForVariableIfUsingIterationVars(
  315. node,
  316. vFor
  317. )
  318. const vSlotGroupsOfSameSlot = filterSameSlot(
  319. vSlotGroupsOnChildren,
  320. node,
  321. vSlotVForVar,
  322. sourceCode,
  323. tokenStore
  324. )
  325. if (
  326. vSlotGroupsOfSameSlot.length >= 2 &&
  327. !vSlotGroupsOfSameSlot[0].includes(node)
  328. ) {
  329. // E.g., <template #one></template>
  330. // <template #one></template>
  331. context.report({
  332. node,
  333. messageId: 'disallowDuplicateSlotsOnChildren'
  334. })
  335. }
  336. if (vFor && !vSlotVForVar) {
  337. // E.g., <template v-for="x of xs" #one></template>
  338. context.report({
  339. node,
  340. messageId: 'disallowDuplicateSlotsOnChildren'
  341. })
  342. }
  343. }
  344. // Verify argument.
  345. if (isUsingScopeVar(node)) {
  346. context.report({
  347. node,
  348. messageId: 'disallowArgumentUseSlotParams'
  349. })
  350. }
  351. // Verify modifiers.
  352. if (hasInvalidModifiers(node, allowModifiers)) {
  353. // E.g., <template v-slot.foo>
  354. context.report({
  355. node,
  356. loc: {
  357. start: node.key.modifiers[0].loc.start,
  358. end: node.key.modifiers[node.key.modifiers.length - 1].loc.end
  359. },
  360. messageId: 'disallowAnyModifier'
  361. })
  362. }
  363. // Verify value.
  364. if (
  365. ownerElement === element &&
  366. isDefaultSlot &&
  367. (!node.value ||
  368. utils.isEmptyValueDirective(node, context) ||
  369. utils.isEmptyExpressionValueDirective(node, context))
  370. ) {
  371. context.report({
  372. node,
  373. messageId: 'requireAttributeValue'
  374. })
  375. }
  376. }
  377. })
  378. }
  379. }