2019-09-22 05:42:12 +08:00
|
|
|
import { createStructuralDirectiveTransform } from '../transform'
|
2019-09-18 07:08:47 +08:00
|
|
|
import {
|
|
|
|
NodeTypes,
|
|
|
|
ElementTypes,
|
|
|
|
ElementNode,
|
|
|
|
DirectiveNode,
|
|
|
|
IfBranchNode
|
|
|
|
} from '../ast'
|
|
|
|
import { createCompilerError, ErrorCodes } from '../errors'
|
|
|
|
|
2019-09-22 05:42:12 +08:00
|
|
|
export const transformIf = createStructuralDirectiveTransform(
|
2019-09-18 07:08:47 +08:00
|
|
|
/^(if|else|else-if)$/,
|
|
|
|
(node, dir, context) => {
|
|
|
|
if (dir.name === 'if') {
|
|
|
|
context.replaceNode({
|
|
|
|
type: NodeTypes.IF,
|
|
|
|
loc: node.loc,
|
|
|
|
branches: [createIfBranch(node, dir)]
|
|
|
|
})
|
|
|
|
} else {
|
|
|
|
// locate the adjacent v-if
|
|
|
|
const siblings = context.parent.children
|
2019-09-20 03:41:17 +08:00
|
|
|
const comments = []
|
|
|
|
let i = siblings.indexOf(node)
|
|
|
|
while (i-- >= -1) {
|
2019-09-18 07:08:47 +08:00
|
|
|
const sibling = siblings[i]
|
2019-09-20 03:41:17 +08:00
|
|
|
if (__DEV__ && sibling && sibling.type === NodeTypes.COMMENT) {
|
|
|
|
context.removeNode(sibling)
|
|
|
|
comments.unshift(sibling)
|
2019-09-18 07:08:47 +08:00
|
|
|
continue
|
|
|
|
}
|
2019-09-20 03:41:17 +08:00
|
|
|
if (sibling && sibling.type === NodeTypes.IF) {
|
2019-09-18 07:08:47 +08:00
|
|
|
// move the node to the if node's branches
|
|
|
|
context.removeNode()
|
2019-09-20 03:41:17 +08:00
|
|
|
const branch = createIfBranch(node, dir)
|
|
|
|
if (__DEV__ && comments.length) {
|
|
|
|
branch.children = [...comments, ...branch.children]
|
|
|
|
}
|
|
|
|
sibling.branches.push(branch)
|
2019-09-18 07:08:47 +08:00
|
|
|
} else {
|
2019-09-22 05:42:12 +08:00
|
|
|
context.onError(
|
2019-09-18 07:08:47 +08:00
|
|
|
createCompilerError(
|
|
|
|
dir.name === 'else'
|
|
|
|
? ErrorCodes.X_ELSE_NO_ADJACENT_IF
|
|
|
|
: ErrorCodes.X_ELSE_IF_NO_ADJACENT_IF,
|
|
|
|
node.loc.start
|
|
|
|
)
|
|
|
|
)
|
|
|
|
}
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
function createIfBranch(node: ElementNode, dir: DirectiveNode): IfBranchNode {
|
|
|
|
return {
|
|
|
|
type: NodeTypes.IF_BRANCH,
|
|
|
|
loc: node.loc,
|
|
|
|
condition: dir.name === 'else' ? undefined : dir.exp,
|
|
|
|
children: node.tagType === ElementTypes.TEMPLATE ? node.children : [node]
|
|
|
|
}
|
|
|
|
}
|