vModel.ts 4.7 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1
import { camelize } from '@vue/shared'
fxy060608's avatar
fxy060608 已提交
2 3 4 5 6 7 8 9 10
import {
  Property,
  transformModel as baseTransform,
  ElementTypes,
  findProp,
  NodeTypes,
  DirectiveNode,
  ElementNode,
  ExpressionNode,
fxy060608's avatar
fxy060608 已提交
11 12
  AttributeNode,
  createCompoundExpression,
fxy060608's avatar
fxy060608 已提交
13 14
  DirectiveTransform,
  TransformContext as VueTransformContext,
fxy060608's avatar
fxy060608 已提交
15 16
} from '@vue/compiler-core'
import { DOMErrorCodes, createDOMCompilerError } from '@vue/compiler-dom'
fxy060608's avatar
fxy060608 已提交
17 18 19 20 21 22

import {
  createBindDirectiveNode,
  createOnDirectiveNode,
} from '@dcloudio/uni-cli-shared'
import { V_ON } from '../runtimeHelpers'
fxy060608's avatar
fxy060608 已提交
23 24
import { genExpr } from '../codegen'
import { TransformContext } from '../transform'
fxy060608's avatar
fxy060608 已提交
25
import { DirectiveTransformResult } from './transformElement'
fxy060608's avatar
fxy060608 已提交
26 27
import { wrapperVOn } from './vOn'

fxy060608's avatar
fxy060608 已提交
28
export const transformModel: DirectiveTransform = (
fxy060608's avatar
fxy060608 已提交
29 30
  dir: DirectiveNode,
  node: ElementNode,
fxy060608's avatar
fxy060608 已提交
31
  _context: VueTransformContext
fxy060608's avatar
fxy060608 已提交
32
) => {
fxy060608's avatar
fxy060608 已提交
33 34
  const context = _context as unknown as TransformContext
  const baseResult = baseTransform(dir, node, _context)
fxy060608's avatar
fxy060608 已提交
35 36
  // base transform has errors OR component v-model (only need props)
  if (!baseResult.props.length || node.tagType === ElementTypes.COMPONENT) {
fxy060608's avatar
fxy060608 已提交
37 38 39 40
    return transformComponentVModel(
      baseResult.props,
      context
    ) as unknown as DirectiveTransformResult
fxy060608's avatar
fxy060608 已提交
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
  }

  if (dir.arg) {
    context.onError(
      createDOMCompilerError(
        DOMErrorCodes.X_V_MODEL_ARG_ON_ELEMENT,
        dir.arg.loc
      )
    )
  }

  function checkDuplicatedValue() {
    const value = findProp(node, 'value')
    if (value) {
      context.onError(
        createDOMCompilerError(
          DOMErrorCodes.X_V_MODEL_UNNECESSARY_VALUE,
          value.loc
        )
      )
    }
  }

  const { tag } = node
  if (tag === 'input' || tag === 'textarea') {
    checkDuplicatedValue()
  } else {
    context.onError(
      createDOMCompilerError(
        DOMErrorCodes.X_V_MODEL_ON_INVALID_ELEMENT,
        dir.loc
      )
    )
  }

fxy060608's avatar
fxy060608 已提交
76 77 78 79 80
  return transformElementVModel(
    baseResult.props,
    node,
    context
  ) as unknown as DirectiveTransformResult
fxy060608's avatar
fxy060608 已提交
81
}
fxy060608's avatar
fxy060608 已提交
82

fxy060608's avatar
fxy060608 已提交
83 84 85 86 87 88 89 90 91 92 93 94 95 96
function findInputDirectiveNode(props: (AttributeNode | DirectiveNode)[]) {
  return props.find(
    (prop) =>
      prop.type === NodeTypes.DIRECTIVE &&
      prop.name === 'on' &&
      prop.arg?.type === NodeTypes.SIMPLE_EXPRESSION &&
      prop.arg.content === 'input'
  ) as DirectiveNode | undefined
}

function transformElementVModel(
  props: Property[],
  node: ElementNode,
  context: TransformContext
fxy060608's avatar
fxy060608 已提交
97
) {
fxy060608's avatar
fxy060608 已提交
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
  const dirs = transformVModel(props, context, {
    binding: 'value',
    event: 'input',
    formatEventCode(code) {
      return code.replace(`= $event`, `= $event.detail.value`)
    },
  })
  if (dirs.length === 2) {
    const inputDir = findInputDirectiveNode(node.props)
    if (inputDir && inputDir.exp) {
      // 合并到已有的 input 事件中
      inputDir.exp = combineVOn(dirs[1].exp!, inputDir.exp, context)
      dirs.length = 1
    }
  }
fxy060608's avatar
fxy060608 已提交
113
  return { props: dirs }
fxy060608's avatar
fxy060608 已提交
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
}

function parseVOn(exp: ExpressionNode, context: TransformContext) {
  return genExpr(exp).slice(context.helperString(V_ON).length + 1, -1)
}

function combineVOn(
  exp1: ExpressionNode,
  exp2: ExpressionNode,
  context: TransformContext
) {
  return wrapperVOn(
    createCompoundExpression([
      `[`,
      parseVOn(exp1, context),
      ',',
      parseVOn(exp2, context),
      `]`,
    ]),
    context
  )
fxy060608's avatar
fxy060608 已提交
135 136 137 138 139
}

function transformComponentVModel(
  props: Property[],
  context: TransformContext
fxy060608's avatar
fxy060608 已提交
140 141 142 143 144 145 146 147
) {
  return {
    props: transformVModel(props, context, {
      formatEventCode(code) {
        return code
      },
    }),
  }
fxy060608's avatar
fxy060608 已提交
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
}

function transformVModel(
  props: Property[],
  context: TransformContext,
  {
    binding,
    event,
    formatEventCode,
  }: {
    binding?: string
    event?: string
    formatEventCode: (code: string) => string
  }
) {
fxy060608's avatar
fxy060608 已提交
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
  if (props.length !== 2) {
    return []
  }
  const { key: modelValueArg, value: modelValeExpr } = props[0]
  const { key: onUpdateArg, value: onUpdateExpr } = props[1]

  if (modelValueArg.type !== NodeTypes.SIMPLE_EXPRESSION) {
    return []
  }
  if (
    onUpdateArg.type !== NodeTypes.SIMPLE_EXPRESSION ||
    !onUpdateArg.content.startsWith('onUpdate:')
  ) {
    return []
  }
  const vBindModelValue = createBindDirectiveNode(
fxy060608's avatar
fxy060608 已提交
179
    binding || modelValueArg.content,
fxy060608's avatar
fxy060608 已提交
180 181 182
    genExpr(modelValeExpr as ExpressionNode)
  )
  const vOnUpdate = createOnDirectiveNode(
fxy060608's avatar
fxy060608 已提交
183 184 185 186 187 188 189 190 191 192
    event || camelize(onUpdateArg.content.replace('onUpdate:', 'update-')),
    formatEventCode(
      genExpr(
        wrapperVOn(
          // onUpdateExpr 通常是 ExpressionNode 或者被 cache 的 ExpressionNode
          (onUpdateExpr.type === NodeTypes.JS_CACHE_EXPRESSION
            ? onUpdateExpr.value
            : onUpdateExpr) as ExpressionNode,
          context
        )
fxy060608's avatar
fxy060608 已提交
193
      )
fxy060608's avatar
fxy060608 已提交
194
    )
fxy060608's avatar
fxy060608 已提交
195 196 197
  )
  return [vBindModelValue, vOnUpdate]
}