transformClass.ts 5.8 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
import {
  Expression,
  isObjectExpression,
  isArrayExpression,
  arrayExpression,
  stringLiteral,
  ArrayExpression,
  isStringLiteral,
  identifier,
  isSpreadElement,
  ObjectExpression,
  objectProperty,
  booleanLiteral,
  isObjectProperty,
  Identifier,
  isLiteral,
  isIdentifier,
  LogicalExpression,
  logicalExpression,
  StringLiteral,
fxy060608's avatar
fxy060608 已提交
21
  isTemplateLiteral,
fxy060608's avatar
fxy060608 已提交
22 23 24 25 26 27 28 29 30 31 32 33
} from '@babel/types'
import {
  DirectiveNode,
  NodeTypes,
  AttributeNode,
  createSimpleExpression,
  ExpressionNode,
  createCompoundExpression,
  SourceLocation,
} from '@vue/compiler-core'
import { parseExpr, isTrueExpr, isUndefined, parseStringLiteral } from '../ast'
import { genBabelExpr } from '../codegen'
fxy060608's avatar
fxy060608 已提交
34
import { NORMALIZE_CLASS } from '../runtimeHelpers'
fxy060608's avatar
fxy060608 已提交
35 36 37
import { TransformContext } from '../transform'
import {
  parseExprWithRewrite,
fxy060608's avatar
fxy060608 已提交
38
  parseExprWithRewriteClass,
fxy060608's avatar
fxy060608 已提交
39 40 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 76 77 78 79 80 81 82 83 84
  rewriteExpression,
  rewriteSpreadElement,
} from './utils'

export function isClassBinding({ arg, exp }: DirectiveNode) {
  return (
    arg && arg.type === NodeTypes.SIMPLE_EXPRESSION && arg.content === 'class'
  )
}

export function findStaticClassIndex(props: (AttributeNode | DirectiveNode)[]) {
  return props.findIndex((prop) => prop.name === 'class')
}

export function rewriteClass(
  index: number,
  classBindingProp: DirectiveNode,
  props: (AttributeNode | DirectiveNode)[],
  context: TransformContext
) {
  if (!classBindingProp.exp) {
    return
  }
  const expr = parseExpr(classBindingProp.exp, context)
  if (!expr) {
    return
  }
  let classBidingExpr: Expression = expr
  if (isObjectExpression(expr)) {
    classBidingExpr = createClassBindingByObjectExpression(
      rewriteClassObjectExpression(expr, classBindingProp.loc, context)
    )
  } else if (isArrayExpression(expr)) {
    classBidingExpr = createClassBindingByArrayExpression(
      rewriteClassArrayExpression(expr, context)
    )
  } else {
    classBidingExpr = parseExpr(
      rewriteClassExpression(classBindingProp.exp, context).content,
      context
    ) as Expression
  }
  const staticClassPropIndex = findStaticClassIndex(props)
  if (staticClassPropIndex > -1) {
    const staticClass = (props[staticClassPropIndex] as AttributeNode).value!
      .content
fxy060608's avatar
fxy060608 已提交
85
    if (staticClass) {
fxy060608's avatar
fxy060608 已提交
86 87 88
      if (!isArrayExpression(classBidingExpr)) {
        classBidingExpr = arrayExpression([classBidingExpr])
      }
fxy060608's avatar
fxy060608 已提交
89
      const staticClassLiterals = parseStaticClass(staticClass)
fxy060608's avatar
fxy060608 已提交
90
      if (index > staticClassPropIndex) {
fxy060608's avatar
fxy060608 已提交
91
        classBidingExpr.elements.unshift(...staticClassLiterals)
fxy060608's avatar
fxy060608 已提交
92
      } else {
fxy060608's avatar
fxy060608 已提交
93
        classBidingExpr.elements.push(...staticClassLiterals)
fxy060608's avatar
fxy060608 已提交
94 95 96 97 98 99
      }
    }
  }
  classBindingProp.exp = createSimpleExpression(genBabelExpr(classBidingExpr))
}

fxy060608's avatar
fxy060608 已提交
100 101 102 103 104
function parseStaticClass(staticClass: string): StringLiteral[] {
  // 已经在 parse 阶段格式化了多余空格等
  return staticClass.split(' ').map((clazz) => stringLiteral(clazz))
}

fxy060608's avatar
fxy060608 已提交
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 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
function rewriteClassExpression(
  expr: ExpressionNode,
  context: TransformContext
) {
  return rewriteExpression(
    createCompoundExpression([
      context.helperString(NORMALIZE_CLASS) + '(',
      expr,
      ')',
    ]),
    context
  )
}

function rewriteClassArrayExpression(
  expr: ArrayExpression,
  context: TransformContext
) {
  expr.elements.forEach((prop, index) => {
    if (!isStringLiteral(prop)) {
      const code = genBabelExpr(
        arrayExpression([isSpreadElement(prop) ? prop.argument : prop])
      )
      expr.elements[index] = identifier(
        rewriteClassExpression(
          createSimpleExpression(code.slice(1, -1), false),
          context
        ).content
      )
    }
  })
  return expr
}

function rewriteClassObjectExpression(
  expr: ObjectExpression,
  loc: SourceLocation,
  context: TransformContext
) {
  expr.properties.forEach((prop, index) => {
    if (isSpreadElement(prop)) {
      // <view :class="{...obj}"/>
      // <view class="{{[a]}}"/>
      const newExpr = rewriteSpreadElement(NORMALIZE_CLASS, prop, loc, context)
      if (newExpr) {
        expr.properties[index] = objectProperty(
          newExpr,
          booleanLiteral(true),
          true
        )
      }
    } else if (isObjectProperty(prop)) {
      const { key, value, computed } = prop
      if (computed) {
        // {[handle(computedKey)]:1} => {[a]:1}
        prop.key = parseExprWithRewrite(
          genBabelExpr(key as Expression),
          loc,
          context,
          key as Expression
        ) as Identifier
      }
fxy060608's avatar
fxy060608 已提交
167
      if (isLiteral(value) && !isTemplateLiteral(value)) {
fxy060608's avatar
fxy060608 已提交
168 169
        return
      } else {
fxy060608's avatar
fxy060608 已提交
170
        const newExpr = parseExprWithRewriteClass(
fxy060608's avatar
fxy060608 已提交
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
          genBabelExpr(value as Expression),
          loc,
          context,
          value as Expression
        )
        if (newExpr) {
          prop.value = newExpr
        }
      }
    }
  })
  return expr
}

function createClassBindingByArrayExpression(expr: ArrayExpression) {
  const elements: (StringLiteral | Identifier)[] = []
  expr.elements.forEach((prop) => {
    if (isStringLiteral(prop) || isIdentifier(prop)) {
      elements.push(prop)
    }
  })
  return arrayExpression(elements)
}

function createClassBindingByObjectExpression(expr: ObjectExpression) {
  const elements: (LogicalExpression | StringLiteral | Identifier)[] = []
  expr.properties.forEach((prop) => {
    if (isObjectProperty(prop)) {
      const { value } = prop
      if (isUndefined(value as Expression)) {
        // remove {a:undefined}
        return
      }
      if (isLiteral(value)) {
        // {a:true,b:1,c:0} => ['a','b']
        if (isTrueExpr(value)) {
          elements.push(
            prop.computed
              ? (prop.key as Identifier)
              : parseStringLiteral(prop.key)
          )
        }
        return
      }
      elements.push(
        logicalExpression(
          '&&',
          value as Expression,
          prop.computed ? prop.key : parseStringLiteral(prop.key)
        )
      )
    }
  })
  return arrayExpression(elements)
}