All files / compiler/src/transforms vOn.ts

100% Statements 49/49
80% Branches 4/5
100% Functions 2/2
100% Lines 49/49

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 501x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x  
import {
  transformOn as baseTransform,
  DirectiveTransform,
  createObjectProperty,
  createSimpleExpression,
  createCompoundExpression,
  isStaticExp
} from '@vue/compiler-core'
import { capitalize, makeMap } from '@vue/shared'
 
// todo: simplify - we only support `once` - no need to use makeMap
const isEventOptionModifier = /*#__PURE__*/ makeMap(`once,capture`)
 
// todo: remove - no need to loop through modifiers as only `once` is supported
const generateOptionModifiers = (modifiers: string[]) => {
  const eventOptionModifiers = []
 
  for (let i = 0; i < modifiers.length; i++) {
    const modifier = modifiers[i]
 
    if (isEventOptionModifier(modifier)) {
      // eventOptionModifiers: modifiers for addEventListener() options, e.g. .once
      eventOptionModifiers.push(modifier)
    }
  }
 
  return eventOptionModifiers
}
 
export const transformOn: DirectiveTransform = (dir, node, context) => {
  return baseTransform(dir, node, context, baseResult => {
    const { modifiers } = dir
    if (!modifiers.length) return baseResult
 
    let { key, value: handlerExp } = baseResult.props[0]
    const eventOptionModifiers = generateOptionModifiers(modifiers)
 
    if (eventOptionModifiers.length) {
      const modifierPostfix = eventOptionModifiers.map(capitalize).join('')
      key = isStaticExp(key)
        ? createSimpleExpression(`${key.content}${modifierPostfix}`, true)
        : createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`])
    }
 
    return {
      props: [createObjectProperty(key, handlerExp)]
    }
  })
}