transformElement.ts 7.7 KB
Newer Older
1
import { camelize, capitalize } from '@vue/shared'
fxy060608's avatar
fxy060608 已提交
2 3 4 5 6 7 8 9 10 11
import {
  NodeTypes,
  ElementTypes,
  createCompilerError,
  ErrorCodes,
  ElementNode,
  isBindKey,
  TemplateLiteral,
  Property,
  ExpressionNode,
12 13 14 15 16
  isCoreComponent,
  BindingTypes,
  UNREF,
  toValidAssetId,
  findDir,
fxy060608's avatar
fxy060608 已提交
17 18
  locStub,
  AttributeNode,
fxy060608's avatar
fxy060608 已提交
19
  DirectiveNode,
fxy060608's avatar
fxy060608 已提交
20
  ComponentNode,
fxy060608's avatar
fxy060608 已提交
21
} from '@vue/compiler-core'
fxy060608's avatar
fxy060608 已提交
22 23
import { isComponentTag } from '@dcloudio/uni-shared'

fxy060608's avatar
fxy060608 已提交
24
import { createMPCompilerError, MPErrorCodes } from '../errors'
fxy060608's avatar
fxy060608 已提交
25

26 27
import {
  BindingComponentTypes,
fxy060608's avatar
fxy060608 已提交
28
  DirectiveTransform,
29 30 31
  NodeTransform,
  TransformContext,
} from '../transform'
fxy060608's avatar
fxy060608 已提交
32
import { createAttributeNode } from '../ast'
fxy060608's avatar
fxy060608 已提交
33
import { transformModel } from './vModel'
fxy060608's avatar
fxy060608 已提交
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52

export interface DirectiveTransformResult {
  props: Property[]
  needRuntime?: boolean | symbol
  ssrTagParts?: TemplateLiteral['elements']
}

export const transformElement: NodeTransform = (node, context) => {
  return function postTransformElement() {
    node = context.currentNode!
    if (
      !(
        node.type === NodeTypes.ELEMENT &&
        (node.tagType === ElementTypes.ELEMENT ||
          node.tagType === ElementTypes.COMPONENT)
      )
    ) {
      return
    }
fxy060608's avatar
fxy060608 已提交
53
    if (node.tagType === ElementTypes.COMPONENT) {
54 55
      processComponent(node, context)
    }
fxy060608's avatar
fxy060608 已提交
56 57 58
    if (context.scopeId) {
      addScopeId(node, context.scopeId)
    }
fxy060608's avatar
fxy060608 已提交
59 60 61 62 63 64 65
    const { props } = node
    if (props.length > 0) {
      processProps(node, context)
    }
  }
}

fxy060608's avatar
fxy060608 已提交
66
function createClassAttribute(clazz: string): AttributeNode {
fxy060608's avatar
fxy060608 已提交
67
  return createAttributeNode('class', clazz)
fxy060608's avatar
fxy060608 已提交
68
}
fxy060608's avatar
fxy060608 已提交
69

fxy060608's avatar
fxy060608 已提交
70
export function addStaticClass(node: ElementNode, clazz: string) {
fxy060608's avatar
fxy060608 已提交
71 72 73 74 75
  const classProp = node.props.find(
    (prop) => prop.type === NodeTypes.ATTRIBUTE && prop.name === 'class'
  ) as AttributeNode | undefined

  if (!classProp) {
fxy060608's avatar
fxy060608 已提交
76
    return node.props.unshift(createClassAttribute(clazz))
fxy060608's avatar
fxy060608 已提交
77 78 79
  }

  if (classProp.value) {
fxy060608's avatar
fxy060608 已提交
80
    return (classProp.value.content = classProp.value.content + ' ' + clazz)
fxy060608's avatar
fxy060608 已提交
81 82 83 84
  }
  classProp.value = {
    type: NodeTypes.TEXT,
    loc: locStub,
fxy060608's avatar
fxy060608 已提交
85
    content: clazz,
fxy060608's avatar
fxy060608 已提交
86 87 88
  }
}

fxy060608's avatar
fxy060608 已提交
89 90 91 92
function addScopeId(node: ElementNode, scopeId: string) {
  return addStaticClass(node, scopeId)
}

fxy060608's avatar
fxy060608 已提交
93
function processComponent(node: ComponentNode, context: TransformContext) {
94 95
  const { tag } = node
  if (context.bindingComponents[tag]) {
fxy060608's avatar
fxy060608 已提交
96
    return
97 98 99 100 101
  }

  // 1. dynamic component
  if (isComponentTag(tag)) {
    return context.onError(
fxy060608's avatar
fxy060608 已提交
102
      createMPCompilerError(
103
        MPErrorCodes.X_DYNAMIC_COMPONENT_NOT_SUPPORTED,
fxy060608's avatar
fxy060608 已提交
104
        node.loc
105 106 107 108 109
      )
    )
  }
  if (findDir(node, 'is')) {
    return context.onError(
fxy060608's avatar
fxy060608 已提交
110
      createMPCompilerError(MPErrorCodes.X_V_IS_NOT_SUPPORTED, node.loc)
111 112 113 114 115 116 117 118 119 120
    )
  }
  // TODO not supported
  // const isProp = findProp(node, 'is')
  // if (isProp) {
  // }
  // 2. built-in components (Teleport, Transition, KeepAlive, Suspense...)
  const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag)
  if (builtIn) {
    return context.onError(
fxy060608's avatar
fxy060608 已提交
121
      createMPCompilerError(MPErrorCodes.X_NOT_SUPPORTED, node.loc, tag)
122 123
    )
  }
fxy060608's avatar
fxy060608 已提交
124

125 126 127 128 129 130 131 132 133 134 135
  // 3. user component (from setup bindings)
  const fromSetup = resolveSetupReference(tag, context)
  if (fromSetup) {
    return (context.bindingComponents[tag] = {
      name: fromSetup,
      type: BindingComponentTypes.SETUP,
    })
  }
  const dotIndex = tag.indexOf('.')
  if (dotIndex > 0) {
    return context.onError(
fxy060608's avatar
fxy060608 已提交
136
      createMPCompilerError(MPErrorCodes.X_NOT_SUPPORTED, node.loc, tag)
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
    )
  }

  // 4. Self referencing component (inferred from filename)
  if (context.selfName && capitalize(camelize(tag)) === context.selfName) {
    return (context.bindingComponents[tag] = {
      name: toValidAssetId(tag, `component`),
      type: BindingComponentTypes.SELF,
    })
  }

  // 5. user component (resolve)
  context.bindingComponents[tag] = {
    name: toValidAssetId(tag, `component`),
    type: BindingComponentTypes.UNKNOWN,
  }
}

function resolveSetupReference(name: string, context: TransformContext) {
  const bindings = context.bindingMetadata
  if (!bindings || bindings.__isScriptSetup === false) {
    return
  }

  const camelName = camelize(name)
  const PascalName = capitalize(camelName)
  const checkType = (type: BindingTypes) => {
    if (bindings[name] === type) {
      return name
    }
    if (bindings[camelName] === type) {
      return camelName
    }
    if (bindings[PascalName] === type) {
      return PascalName
    }
  }

  const fromConst = checkType(BindingTypes.SETUP_CONST)
  if (fromConst) {
    return context.inline
      ? // in inline mode, const setup bindings (e.g. imports) can be used as-is
        fromConst
      : `$setup[${JSON.stringify(fromConst)}]`
  }

  const fromMaybeRef =
    checkType(BindingTypes.SETUP_LET) ||
    checkType(BindingTypes.SETUP_REF) ||
    checkType(BindingTypes.SETUP_MAYBE_REF)
  if (fromMaybeRef) {
    return context.inline
      ? // setup scope bindings that may be refs need to be unrefed
        `${context.helperString(UNREF)}(${fromMaybeRef})`
      : `$setup[${JSON.stringify(fromMaybeRef)}]`
  }
}

fxy060608's avatar
fxy060608 已提交
195 196 197 198 199 200
export function processProps(
  node: ElementNode,
  context: TransformContext,
  props: ElementNode['props'] = node.props
) {
  const { tag } = node
fxy060608's avatar
fxy060608 已提交
201 202 203 204
  const isComponent = node.tagType === ElementTypes.COMPONENT

  for (let i = 0; i < props.length; i++) {
    const prop = props[i]
fxy060608's avatar
fxy060608 已提交
205
    if (prop.type === NodeTypes.DIRECTIVE) {
fxy060608's avatar
fxy060608 已提交
206
      // directives
fxy060608's avatar
fxy060608 已提交
207
      const { name, arg, loc } = prop
fxy060608's avatar
fxy060608 已提交
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
      const isVBind = name === 'bind'
      const isVOn = name === 'on'
      // skip v-slot - it is handled by its dedicated transform.
      if (name === 'slot') {
        if (!isComponent) {
          context.onError(
            createCompilerError(ErrorCodes.X_V_SLOT_MISPLACED, loc)
          )
        }
        continue
      }
      // skip v-once/v-memo - they are handled by dedicated transforms.
      if (name === 'once' || name === 'memo') {
        continue
      }
      // skip v-is and :is on <component>
      if (
        name === 'is' ||
        (isVBind && isBindKey(arg, 'is') && isComponentTag(tag))
      ) {
        continue
      }

fxy060608's avatar
fxy060608 已提交
231 232 233 234 235
      if (isVBind || isVOn) {
        // v-on=""
        // v-bind=""
        if (!arg) {
          context.onError(
fxy060608's avatar
fxy060608 已提交
236
            createMPCompilerError(
fxy060608's avatar
fxy060608 已提交
237 238 239
              isVBind
                ? MPErrorCodes.X_V_BIND_NO_ARGUMENT
                : MPErrorCodes.X_V_ON_NO_ARGUMENT,
fxy060608's avatar
fxy060608 已提交
240
              loc
fxy060608's avatar
fxy060608 已提交
241
            )
fxy060608's avatar
fxy060608 已提交
242 243 244 245 246 247 248 249
          )
          continue
        }
        // v-on:[a]=""
        // v-on:[a.b]=""
        // v-bind:[a]=""
        // v-bind:[a.b]=""
        if (!(arg.type === NodeTypes.SIMPLE_EXPRESSION && arg.isStatic)) {
fxy060608's avatar
fxy060608 已提交
250
          context.onError(
fxy060608's avatar
fxy060608 已提交
251
            createMPCompilerError(
fxy060608's avatar
fxy060608 已提交
252
              isVBind
fxy060608's avatar
fxy060608 已提交
253 254
                ? MPErrorCodes.X_V_BIND_DYNAMIC_ARGUMENT
                : MPErrorCodes.X_V_ON_DYNAMIC_EVENT,
fxy060608's avatar
fxy060608 已提交
255
              loc
fxy060608's avatar
fxy060608 已提交
256 257
            )
          )
fxy060608's avatar
fxy060608 已提交
258
          continue
fxy060608's avatar
fxy060608 已提交
259
        }
fxy060608's avatar
fxy060608 已提交
260 261
      }

fxy060608's avatar
fxy060608 已提交
262
      const directiveTransform = context.directiveTransforms[name]
fxy060608's avatar
fxy060608 已提交
263
      if (name !== 'model' && directiveTransform) {
fxy060608's avatar
fxy060608 已提交
264
        const { props } = directiveTransform(prop, node, context as any)
fxy060608's avatar
fxy060608 已提交
265 266 267
        if (props.length) {
          prop.exp = props[0].value as ExpressionNode
        }
fxy060608's avatar
fxy060608 已提交
268 269 270
      }
    }
  }
fxy060608's avatar
fxy060608 已提交
271 272 273
  const transformVModel = (context.directiveTransforms.model ||
    transformModel) as unknown as DirectiveTransform
  processVModel(node, transformVModel, context)
fxy060608's avatar
fxy060608 已提交
274 275
}

fxy060608's avatar
fxy060608 已提交
276 277 278 279 280
function processVModel(
  node: ElementNode,
  transformVModel: DirectiveTransform,
  context: TransformContext
) {
fxy060608's avatar
fxy060608 已提交
281 282 283 284 285
  const { props } = node
  const dirs: DirectiveNode[] = []
  for (let i = 0; i < props.length; i++) {
    const prop = props[i]
    if (prop.type === NodeTypes.DIRECTIVE && prop.name === 'model') {
fxy060608's avatar
fxy060608 已提交
286 287 288 289
      dirs.push(
        ...(transformVModel(prop, node, context as any)
          .props as unknown as DirectiveNode[])
      )
fxy060608's avatar
fxy060608 已提交
290 291 292 293
      props.splice(i, 1)
      i--
    }
  }
fxy060608's avatar
fxy060608 已提交
294 295 296
  if (dirs.length) {
    props.push(...dirs)
  }
fxy060608's avatar
fxy060608 已提交
297
}