vue3-core/packages/compiler-ssr/src/transforms/ssrVIf.ts

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

79 lines
2.1 KiB
TypeScript
Raw Normal View History

2020-02-04 04:51:41 +08:00
import {
type BlockStatement,
type IfBranchNode,
2020-02-04 04:51:41 +08:00
type IfNode,
type NodeTransform,
NodeTypes,
2020-02-04 04:51:41 +08:00
createBlockStatement,
createCallExpression,
createIfStatement,
createStructuralDirectiveTransform,
2020-02-06 10:04:40 +08:00
processIf,
2020-02-04 04:51:41 +08:00
} from '@vue/compiler-dom'
import {
type SSRTransformContext,
2020-02-07 06:45:34 +08:00
processChildrenAsStatement,
2020-02-04 04:51:41 +08:00
} from '../ssrCodegenTransform'
2020-02-04 06:47:06 +08:00
// Plugin for the first transform pass, which simply constructs the AST node
export const ssrTransformIf: NodeTransform = createStructuralDirectiveTransform(
2020-02-04 04:51:41 +08:00
/^(if|else|else-if)$/,
2020-02-06 10:04:40 +08:00
processIf,
2020-02-04 04:51:41 +08:00
)
2020-05-01 21:42:58 +08:00
// This is called during the 2nd transform pass to construct the SSR-specific
2020-02-04 04:51:41 +08:00
// codegen nodes.
export function ssrProcessIf(
node: IfNode,
context: SSRTransformContext,
disableNestedFragments = false,
disableCommentAsIfAlternate = false,
): void {
2020-02-04 04:51:41 +08:00
const [rootBranch] = node.branches
const ifStatement = createIfStatement(
rootBranch.condition!,
processIfBranch(rootBranch, context, disableNestedFragments),
2020-02-04 04:51:41 +08:00
)
context.pushStatement(ifStatement)
let currentIf = ifStatement
for (let i = 1; i < node.branches.length; i++) {
const branch = node.branches[i]
const branchBlockStatement = processIfBranch(
branch,
context,
disableNestedFragments,
)
2020-02-04 04:51:41 +08:00
if (branch.condition) {
// else-if
currentIf = currentIf.alternate = createIfStatement(
branch.condition,
branchBlockStatement,
)
} else {
// else
currentIf.alternate = branchBlockStatement
}
}
if (!currentIf.alternate && !disableCommentAsIfAlternate) {
2020-02-04 04:51:41 +08:00
currentIf.alternate = createBlockStatement([
createCallExpression(`_push`, ['`<!---->`']),
])
}
}
function processIfBranch(
branch: IfBranchNode,
context: SSRTransformContext,
disableNestedFragments = false,
): BlockStatement {
const { children } = branch
const needFragmentWrapper =
!disableNestedFragments &&
(children.length !== 1 || children[0].type !== NodeTypes.ELEMENT) &&
// optimize away nested fragments when the only child is a ForNode
!(children.length === 1 && children[0].type === NodeTypes.FOR)
return processChildrenAsStatement(branch, context, needFragmentWrapper)
}