const msg = ref('foo')
const fn = jest.fn()
const { vnode, container } = mountWithHydration(
- '<div><span>foo</span><span class="foo"></span></div>',
+ '<div><!----><span>foo</span><!----><span class="foo"></span><!----><!----></div>',
() =>
h('div', [
[h('span', msg.value), [h('span', { class: msg.value, onClick: fn })]]
msg.value = 'bar'
await nextTick()
- expect(vnode.el.innerHTML).toBe(`<span>bar</span><span class="bar"></span>`)
+ expect(vnode.el.innerHTML).toBe(
+ `<!----><span>bar</span><!----><span class="bar"></span><!----><!---->`
+ )
})
test('portal', async () => {
foo: ({ list }, _push, _parent, _scopeId) => {
if (_push) {
if (_ctx.ok) {
- _push(\`<div\${_scopeId}>\`)
+ _push(\`<div\${_scopeId}><!--1-->\`)
_ssrRenderList(list, (i) => {
_push(\`<span\${_scopeId}></span>\`)
})
- _push(\`</div>\`)
+ _push(\`<!--0--></div>\`)
} else {
_push(\`<!---->\`)
}
bar: ({ ok }, _push, _parent, _scopeId) => {
if (_push) {
if (ok) {
- _push(\`<div\${_scopeId}>\`)
+ _push(\`<div\${_scopeId}><!--1-->\`)
_ssrRenderList(_ctx.list, (i) => {
_push(\`<span\${_scopeId}></span>\`)
})
- _push(\`</div>\`)
+ _push(\`<!--0--></div>\`)
} else {
_push(\`<!---->\`)
}
.toMatchInlineSnapshot(`
"
return function ssrRender(_ctx, _push, _parent) {
- _push(\`<div></div>\`)
+ _push(\`<!--1--><div></div><!--0-->\`)
}"
`)
"const { ssrRenderList: _ssrRenderList } = require(\\"@vue/server-renderer\\")
return function ssrRender(_ctx, _push, _parent) {
+ _push(\`<!--1-->\`)
_ssrRenderList(_ctx.list, (i) => {
_push(\`<div></div>\`)
})
+ _push(\`<!--0-->\`)
}"
`)
})
"const { ssrRenderList: _ssrRenderList } = require(\\"@vue/server-renderer\\")
return function ssrRender(_ctx, _push, _parent) {
+ _push(\`<!--1-->\`)
_ssrRenderList(_ctx.list, (i) => {
_push(\`<div>foo<span>bar</span></div>\`)
})
+ _push(\`<!--0-->\`)
}"
`)
})
"const { ssrInterpolate: _ssrInterpolate, ssrRenderList: _ssrRenderList } = require(\\"@vue/server-renderer\\")
return function ssrRender(_ctx, _push, _parent) {
+ _push(\`<!--1-->\`)
_ssrRenderList(_ctx.list, (row, i) => {
- _push(\`<div>\`)
+ _push(\`<div><!--1-->\`)
_ssrRenderList(row, (j) => {
_push(\`<div>\${
_ssrInterpolate(i)
_ssrInterpolate(j)
}</div>\`)
})
- _push(\`</div>\`)
+ _push(\`<!--0--></div>\`)
})
+ _push(\`<!--0-->\`)
}"
`)
})
"const { ssrInterpolate: _ssrInterpolate, ssrRenderList: _ssrRenderList } = require(\\"@vue/server-renderer\\")
return function ssrRender(_ctx, _push, _parent) {
+ _push(\`<!--1-->\`)
_ssrRenderList(_ctx.list, (i) => {
- _push(\`\${_ssrInterpolate(i)}\`)
+ _push(\`<!--1-->\${_ssrInterpolate(i)}<!--0-->\`)
})
+ _push(\`<!--0-->\`)
}"
`)
})
"const { ssrInterpolate: _ssrInterpolate, ssrRenderList: _ssrRenderList } = require(\\"@vue/server-renderer\\")
return function ssrRender(_ctx, _push, _parent) {
+ _push(\`<!--1-->\`)
_ssrRenderList(_ctx.list, (i) => {
_push(\`<span>\${_ssrInterpolate(i)}</span>\`)
})
+ _push(\`<!--0-->\`)
}"
`)
})
"const { ssrInterpolate: _ssrInterpolate, ssrRenderList: _ssrRenderList } = require(\\"@vue/server-renderer\\")
return function ssrRender(_ctx, _push, _parent) {
+ _push(\`<!--1-->\`)
_ssrRenderList(_ctx.list, (i) => {
- _push(\`<span>\${
+ _push(\`<!--1--><span>\${
_ssrInterpolate(i)
}</span><span>\${
_ssrInterpolate(i + 1)
- }</span>\`)
+ }</span><!--0-->\`)
})
+ _push(\`<!--0-->\`)
}"
`)
})
"const { ssrInterpolate: _ssrInterpolate, ssrRenderList: _ssrRenderList } = require(\\"@vue/server-renderer\\")
return function ssrRender(_ctx, _push, _parent) {
+ _push(\`<!--1-->\`)
_ssrRenderList(_ctx.list, ({ foo }, index) => {
_push(\`<div>\${_ssrInterpolate(foo + _ctx.bar + index)}</div>\`)
})
+ _push(\`<!--0-->\`)
}"
`)
})
"
return function ssrRender(_ctx, _push, _parent) {
if (_ctx.foo) {
- _push(\`hello\`)
+ _push(\`<!--1-->hello<!--0-->\`)
} else {
_push(\`<!---->\`)
}
"
return function ssrRender(_ctx, _push, _parent) {
if (_ctx.foo) {
- _push(\`<div>hi</div><div>ho</div>\`)
+ _push(\`<!--1--><div>hi</div><div>ho</div><!--0-->\`)
} else {
_push(\`<!---->\`)
}
return function ssrRender(_ctx, _push, _parent) {
if (_ctx.foo) {
+ _push(\`<!--1-->\`)
_ssrRenderList(_ctx.list, (i) => {
_push(\`<div></div>\`)
})
+ _push(\`<!--0-->\`)
} else {
_push(\`<!---->\`)
}
"
return function ssrRender(_ctx, _push, _parent) {
if (_ctx.foo) {
- _push(\`<div>hi</div><div>ho</div>\`)
+ _push(\`<!--1--><div>hi</div><div>ho</div><!--0-->\`)
} else {
_push(\`<div></div>\`)
}
createBlockStatement,
CompilerOptions,
IfStatement,
- CallExpression
+ CallExpression,
+ isText
} from '@vue/compiler-dom'
import { isString, escapeHtml } from '@vue/shared'
import { SSR_INTERPOLATE, ssrHelpers } from './runtimeHelpers'
export function ssrCodegenTransform(ast: RootNode, options: CompilerOptions) {
const context = createSSRTransformContext(ast, options)
- processChildren(ast.children, context)
+ const isFragment =
+ ast.children.length > 1 && ast.children.some(c => !isText(c))
+ processChildren(ast.children, context, isFragment)
ast.codegenNode = createBlockStatement(context.body)
// Finalize helpers.
export function processChildren(
children: TemplateChildNode[],
- context: SSRTransformContext
+ context: SSRTransformContext,
+ asFragment = false
) {
+ if (asFragment) {
+ context.pushStringPart(`<!--1-->`)
+ }
for (let i = 0; i < children.length; i++) {
const child = children[i]
if (child.type === NodeTypes.ELEMENT) {
ssrProcessFor(child, context)
}
}
+ if (asFragment) {
+ context.pushStringPart(`<!--0-->`)
+ }
}
export function processChildrenAsStatement(
children: TemplateChildNode[],
parentContext: SSRTransformContext,
+ asFragment = false,
withSlotScopeId = parentContext.withSlotScopeId
): BlockStatement {
const childContext = createChildContext(parentContext, withSlotScopeId)
- processChildren(children, childContext)
+ processChildren(children, childContext, asFragment)
return createBlockStatement(childContext.body)
}
traverseNode,
ExpressionNode,
TemplateNode,
- SUSPENSE
+ SUSPENSE,
+ TRANSITION_GROUP
} from '@vue/compiler-dom'
import { SSR_RENDER_COMPONENT } from '../runtimeHelpers'
import {
return ssrProcessSuspense(node, context)
} else {
// real fall-through (e.g. KeepAlive): just render its children.
- processChildren(node.children, context)
+ processChildren(node.children, context, component === TRANSITION_GROUP)
}
} else {
// finish up slot function expressions from the 1st pass.
processChildrenAsStatement(
children,
context,
+ false,
true /* withSlotScopeId */
),
vnodeBranch
processFor,
createCallExpression,
createFunctionExpression,
- createForLoopParams
+ createForLoopParams,
+ NodeTypes
} from '@vue/compiler-dom'
import {
SSRTransformContext,
// This is called during the 2nd transform pass to construct the SSR-sepcific
// codegen nodes.
export function ssrProcessFor(node: ForNode, context: SSRTransformContext) {
+ const needFragmentWrapper =
+ node.children.length !== 1 || node.children[0].type !== NodeTypes.ELEMENT
const renderLoop = createFunctionExpression(
createForLoopParams(node.parseResult)
)
- renderLoop.body = processChildrenAsStatement(node.children, context)
+ renderLoop.body = processChildrenAsStatement(
+ node.children,
+ context,
+ needFragmentWrapper
+ )
+ // v-for always renders a fragment
+ context.pushStringPart(`<!--1-->`)
context.pushStatement(
createCallExpression(context.helper(SSR_RENDER_LIST), [
node.source,
renderLoop
])
)
+ context.pushStringPart(`<!--0-->`)
}
IfNode,
createIfStatement,
createBlockStatement,
- createCallExpression
+ createCallExpression,
+ IfBranchNode,
+ BlockStatement,
+ NodeTypes
} from '@vue/compiler-dom'
import {
SSRTransformContext,
const [rootBranch] = node.branches
const ifStatement = createIfStatement(
rootBranch.condition!,
- processChildrenAsStatement(rootBranch.children, context)
+ processIfBranch(rootBranch, context)
)
context.pushStatement(ifStatement)
let currentIf = ifStatement
for (let i = 1; i < node.branches.length; i++) {
const branch = node.branches[i]
- const branchBlockStatement = processChildrenAsStatement(
- branch.children,
- context
- )
+ const branchBlockStatement = processIfBranch(branch, context)
if (branch.condition) {
// else-if
currentIf = currentIf.alternate = createIfStatement(
])
}
}
+
+function processIfBranch(
+ branch: IfBranchNode,
+ context: SSRTransformContext
+): BlockStatement {
+ const { children } = branch
+ const needFragmentWrapper =
+ (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(children, context, needFragmentWrapper)
+}
// suspense related
asyncDep: Promise<any> | null
- asyncResult: unknown
asyncResolved: boolean
// storage for any extra properties
// async dependency management
asyncDep: null,
- asyncResult: null,
asyncResolved: false,
// user namespace for storing whatever the user assigns to `this`
if (isPromise(setupResult)) {
if (isSSR) {
// return the promise so server-renderer can wait on it
- return setupResult.then(resolvedResult => {
+ return setupResult.then((resolvedResult: unknown) => {
handleSetupResult(instance, resolvedResult, parentSuspense, isSSR)
})
} else if (__FEATURE_SUSPENSE__) {
import { RendererInternals, MoveType, SetupRenderEffectFn } from '../renderer'
import { queuePostFlushCb, queueJob } from '../scheduler'
import { updateHOCHostEl } from '../componentRenderUtils'
-import { handleError, ErrorCodes } from '../errorHandling'
import { pushWarningContext, popWarningContext } from '../warning'
+import { handleError, ErrorCodes } from '../errorHandling'
export interface SuspenseProps {
onResolve?: () => void
rendererInternals
)
}
- }
+ },
+ hydrate: hydrateSuspense
}
// Force-casted public typing for h and TSX props inference
rendererInternals
))
- const { content, fallback } = normalizeSuspenseChildren(n2)
- suspense.subTree = content
- suspense.fallbackTree = fallback
-
// start mounting the content subtree in an off-dom container
patch(
null,
- content,
+ suspense.subTree,
hiddenContainer,
null,
parentComponent,
// mount the fallback tree
patch(
null,
- fallback,
+ suspense.fallbackTree,
container,
anchor,
parentComponent,
isSVG,
optimized
)
- n2.el = fallback.el
+ n2.el = suspense.fallbackTree.el
} else {
// Suspense has no async deps. Just resolve.
suspense.resolve()
subTree: HostVNode
fallbackTree: HostVNode
deps: number
+ isHydrating: boolean
isResolved: boolean
isUnmounted: boolean
effects: Function[]
anchor: HostNode | null,
isSVG: boolean,
optimized: boolean,
- rendererInternals: RendererInternals<HostNode, HostElement>
+ rendererInternals: RendererInternals<HostNode, HostElement>,
+ isHydrating = false
): SuspenseBoundary<HostNode, HostElement> {
const {
p: patch,
o: { parentNode }
} = rendererInternals
+ const getCurrentTree = () =>
+ suspense.isResolved || suspense.isHydrating
+ ? suspense.subTree
+ : suspense.fallbackTree
+
+ const { content, fallback } = normalizeSuspenseChildren(vnode)
const suspense: SuspenseBoundary<HostNode, HostElement> = {
vnode,
parent,
hiddenContainer,
anchor,
deps: 0,
- subTree: (null as unknown) as VNode, // will be set immediately after creation
- fallbackTree: (null as unknown) as VNode, // will be set immediately after creation
+ subTree: content,
+ fallbackTree: fallback,
+ isHydrating,
isResolved: false,
isUnmounted: false,
effects: [],
container
} = suspense
- // this is initial anchor on mount
- let { anchor } = suspense
- // unmount fallback tree
- if (fallbackTree.el) {
- // if the fallback tree was mounted, it may have been moved
- // as part of a parent suspense. get the latest anchor for insertion
- anchor = next(fallbackTree)
- unmount(fallbackTree, parentComponent, suspense, true)
+ if (suspense.isHydrating) {
+ suspense.isHydrating = false
+ } else {
+ // this is initial anchor on mount
+ let { anchor } = suspense
+ // unmount fallback tree
+ if (fallbackTree.el) {
+ // if the fallback tree was mounted, it may have been moved
+ // as part of a parent suspense. get the latest anchor for insertion
+ anchor = next(fallbackTree)
+ unmount(fallbackTree, parentComponent, suspense, true)
+ }
+ // move content from off-dom container to actual container
+ move(subTree, container, anchor, MoveType.ENTER)
}
- // move content from off-dom container to actual container
- move(subTree, container, anchor, MoveType.ENTER)
+
const el = (vnode.el = subTree.el!)
// suspense as the root node of a component...
if (parentComponent && parentComponent.subTree === vnode) {
},
move(container, anchor, type) {
- move(
- suspense.isResolved ? suspense.subTree : suspense.fallbackTree,
- container,
- anchor,
- type
- )
+ move(getCurrentTree(), container, anchor, type)
suspense.container = container
},
next() {
- return next(
- suspense.isResolved ? suspense.subTree : suspense.fallbackTree
- )
+ return next(getCurrentTree())
},
registerDep(instance, setupRenderEffect) {
})
}
+ const hydratedEl = instance.vnode.el
suspense.deps++
instance
.asyncDep!.catch(err => {
pushWarningContext(vnode)
}
handleSetupResult(instance, asyncSetupResult, suspense, false)
- // unset placeholder, otherwise this will be treated as a hydration mount
- vnode.el = null
+ if (hydratedEl) {
+ // vnode may have been replaced if an update happened before the
+ // async dep is reoslved.
+ vnode.el = hydratedEl
+ }
setupRenderEffect(
instance,
vnode,
- // component may have been moved before resolve
- parentNode(instance.subTree.el)!,
- next(instance.subTree),
+ // component may have been moved before resolve.
+ // if this is not a hydration, instance.subTree will be the comment
+ // placeholder.
+ hydratedEl
+ ? parentNode(hydratedEl)!
+ : parentNode(instance.subTree.el)!,
+ // anchor will not be used if this is hydration, so only need to
+ // consider the comment placeholder case.
+ hydratedEl ? null : next(instance.subTree),
suspense,
isSVG
)
return suspense
}
+function hydrateSuspense(
+ node: Node,
+ vnode: VNode,
+ parentComponent: ComponentInternalInstance | null,
+ parentSuspense: SuspenseBoundary | null,
+ isSVG: boolean,
+ optimized: boolean,
+ rendererInternals: RendererInternals,
+ hydrateNode: (
+ node: Node,
+ vnode: VNode,
+ parentComponent: ComponentInternalInstance | null,
+ parentSuspense: SuspenseBoundary | null,
+ optimized: boolean
+ ) => Node | null
+): Node | null {
+ const suspense = (vnode.suspense = createSuspenseBoundary(
+ vnode,
+ parentSuspense,
+ parentComponent,
+ node.parentNode,
+ document.createElement('div'),
+ null,
+ isSVG,
+ optimized,
+ rendererInternals,
+ true /* hydrating */
+ ))
+ // there are two possible scenarios for server-rendered suspense:
+ // - success: ssr content should be fully resolved
+ // - failure: ssr content should be the fallback branch.
+ // however, on the client we don't really know if it has failed or not
+ // attempt to hydrate the DOM assuming it has succeeded, but we still
+ // need to construct a suspense boundary first
+ const result = hydrateNode(
+ node,
+ suspense.subTree,
+ parentComponent,
+ suspense,
+ optimized
+ )
+ if (suspense.deps === 0) {
+ suspense.resolve()
+ }
+ return result
+}
+
export function normalizeSuspenseChildren(
vnode: VNode
): {
import { VNode, normalizeVNode, Text, Comment, Static, Fragment } from './vnode'
-import { queuePostFlushCb, flushPostFlushCbs } from './scheduler'
+import { flushPostFlushCbs } from './scheduler'
import { ComponentInternalInstance } from './component'
import { invokeDirectiveHook } from './directives'
import { warn } from './warning'
isString
} from '@vue/shared'
import { RendererInternals } from './renderer'
+import {
+ SuspenseImpl,
+ SuspenseBoundary,
+ queueEffectWithSuspense
+} from './components/Suspense'
export type RootHydrateFunction = (
vnode: VNode<Node, Element>,
let hasMismatch = false
+const isSVGContainer = (container: Element) =>
+ /svg/.test(container.namespaceURI!) && container.tagName !== 'foreignObject'
+
+const isComment = (node: Node): node is Comment =>
+ node.nodeType === DOMNodeTypes.COMMENT
+
// Note: hydration is DOM-specific
// But we have to place it in core due to tight coupling with core - splitting
// it out creates a ton of unnecessary complexity.
// Hydration also depends on some renderer internal logic which needs to be
// passed in via arguments.
-export function createHydrationFunctions({
- mt: mountComponent,
- p: patch,
- o: { patchProp, createText }
-}: RendererInternals<Node, Element>) {
+export function createHydrationFunctions(
+ rendererInternals: RendererInternals<Node, Element>
+) {
+ const {
+ mt: mountComponent,
+ p: patch,
+ n: next,
+ o: { patchProp, nextSibling, parentNode }
+ } = rendererInternals
+
const hydrate: RootHydrateFunction = (vnode, container) => {
if (__DEV__ && !container.hasChildNodes()) {
warn(
return
}
hasMismatch = false
- hydrateNode(container.firstChild!, vnode)
+ hydrateNode(container.firstChild!, vnode, null, null)
flushPostFlushCbs()
if (hasMismatch && !__TEST__) {
// this error should show up in production
const hydrateNode = (
node: Node,
vnode: VNode,
- parentComponent: ComponentInternalInstance | null = null,
+ parentComponent: ComponentInternalInstance | null,
+ parentSuspense: SuspenseBoundary | null,
optimized = false
): Node | null => {
const { type, shapeFlag } = vnode
switch (type) {
case Text:
if (domType !== DOMNodeTypes.TEXT) {
- return handleMismtach(node, vnode, parentComponent)
+ return handleMismtach(node, vnode, parentComponent, parentSuspense)
}
if ((node as Text).data !== vnode.children) {
hasMismatch = true
)
;(node as Text).data = vnode.children as string
}
- return node.nextSibling
+ return nextSibling(node)
case Comment:
if (domType !== DOMNodeTypes.COMMENT) {
- return handleMismtach(node, vnode, parentComponent)
+ return handleMismtach(node, vnode, parentComponent, parentSuspense)
}
- return node.nextSibling
+ return nextSibling(node)
case Static:
if (domType !== DOMNodeTypes.ELEMENT) {
- return handleMismtach(node, vnode, parentComponent)
+ return handleMismtach(node, vnode, parentComponent, parentSuspense)
}
- return node.nextSibling
+ return nextSibling(node)
case Fragment:
- return hydrateFragment(node, vnode, parentComponent, optimized)
+ if (domType !== DOMNodeTypes.COMMENT) {
+ return handleMismtach(node, vnode, parentComponent, parentSuspense)
+ }
+ return hydrateFragment(
+ node as Comment,
+ vnode,
+ parentComponent,
+ parentSuspense,
+ optimized
+ )
default:
if (shapeFlag & ShapeFlags.ELEMENT) {
if (
domType !== DOMNodeTypes.ELEMENT ||
vnode.type !== (node as Element).tagName.toLowerCase()
) {
- return handleMismtach(node, vnode, parentComponent)
+ return handleMismtach(node, vnode, parentComponent, parentSuspense)
}
return hydrateElement(
node as Element,
vnode,
parentComponent,
+ parentSuspense,
optimized
)
} else if (shapeFlag & ShapeFlags.COMPONENT) {
// when setting up the render effect, if the initial vnode already
// has .el set, the component will perform hydration instead of mount
// on its sub-tree.
- mountComponent(vnode, null, null, parentComponent, null, false)
+ const container = parentNode(node)!
+ mountComponent(
+ vnode,
+ container,
+ null,
+ parentComponent,
+ parentSuspense,
+ isSVGContainer(container)
+ )
const subTree = vnode.component!.subTree
- return (subTree.anchor || subTree.el).nextSibling
+ if (subTree) {
+ return next(subTree)
+ } else {
+ // no subTree means this is an async component
+ // try to locate the ending node
+ return isComment(node) && node.data === '1'
+ ? locateClosingAsyncAnchor(node)
+ : nextSibling(node)
+ }
} else if (shapeFlag & ShapeFlags.PORTAL) {
if (domType !== DOMNodeTypes.COMMENT) {
- return handleMismtach(node, vnode, parentComponent)
+ return handleMismtach(node, vnode, parentComponent, parentSuspense)
}
- hydratePortal(vnode, parentComponent, optimized)
- return node.nextSibling
+ hydratePortal(vnode, parentComponent, parentSuspense, optimized)
+ return nextSibling(node)
} else if (__FEATURE_SUSPENSE__ && shapeFlag & ShapeFlags.SUSPENSE) {
- // TODO Suspense
+ return (vnode.type as typeof SuspenseImpl).hydrate(
+ node,
+ vnode,
+ parentComponent,
+ parentSuspense,
+ isSVGContainer(parentNode(node)!),
+ optimized,
+ rendererInternals,
+ hydrateNode
+ )
} else if (__DEV__) {
warn('Invalid HostVNode type:', type, `(${typeof type})`)
}
el: Element,
vnode: VNode,
parentComponent: ComponentInternalInstance | null,
+ parentSuspense: SuspenseBoundary | null,
optimized: boolean
) => {
optimized = optimized || vnode.dynamicChildren !== null
invokeDirectiveHook(onVnodeBeforeMount, parentComponent, vnode)
}
if (onVnodeMounted != null) {
- queuePostFlushCb(() => {
+ queueEffectWithSuspense(() => {
invokeDirectiveHook(onVnodeMounted, parentComponent, vnode)
- })
+ }, parentSuspense)
}
}
// children
vnode,
el,
parentComponent,
+ parentSuspense,
optimized
)
let hasWarned = false
vnode: VNode,
container: Element,
parentComponent: ComponentInternalInstance | null,
+ parentSuspense: SuspenseBoundary | null,
optimized: boolean
): Node | null => {
optimized = optimized || vnode.dynamicChildren !== null
? children[i]
: (children[i] = normalizeVNode(children[i]))
if (node) {
- node = hydrateNode(node, vnode, parentComponent, optimized)
+ node = hydrateNode(
+ node,
+ vnode,
+ parentComponent,
+ parentSuspense,
+ optimized
+ )
} else {
hasMismatch = true
if (__DEV__ && !hasWarned) {
hasWarned = true
}
// the SSRed DOM didn't contain enough nodes. Mount the missing ones.
- patch(null, vnode, container)
+ patch(
+ null,
+ vnode,
+ container,
+ null,
+ parentComponent,
+ parentSuspense,
+ isSVGContainer(container)
+ )
}
}
return node
}
const hydrateFragment = (
- node: Node,
+ node: Comment,
vnode: VNode,
parentComponent: ComponentInternalInstance | null,
+ parentSuspense: SuspenseBoundary | null,
optimized: boolean
) => {
- const parent = node.parentNode as Element
- parent.insertBefore((vnode.el = createText('')), node)
- const next = hydrateChildren(
- node,
- vnode,
- parent,
- parentComponent,
- optimized
+ return nextSibling(
+ (vnode.anchor = hydrateChildren(
+ nextSibling(node)!,
+ vnode,
+ parentNode(node)!,
+ parentComponent,
+ parentSuspense,
+ optimized
+ )!)
)
- parent.insertBefore((vnode.anchor = createText('')), next)
- return next
}
const hydratePortal = (
vnode: VNode,
parentComponent: ComponentInternalInstance | null,
+ parentSuspense: SuspenseBoundary | null,
optimized: boolean
) => {
const targetSelector = vnode.props && vnode.props.target
vnode,
target,
parentComponent,
+ parentSuspense,
optimized
)
} else if (__DEV__) {
const handleMismtach = (
node: Node,
vnode: VNode,
- parentComponent: ComponentInternalInstance | null
+ parentComponent: ComponentInternalInstance | null,
+ parentSuspense: SuspenseBoundary | null
) => {
hasMismatch = true
__DEV__ &&
`Hydration node mismatch:\n- Client vnode:`,
vnode.type,
`\n- Server rendered DOM:`,
- node
+ node,
+ node.nodeType === DOMNodeTypes.TEXT ? `(text)` : ``
)
vnode.el = null
- const next = node.nextSibling
- const container = node.parentNode as Element
+ const next = nextSibling(node)
+ const container = parentNode(node)!
container.removeChild(node)
- // TODO Suspense and SVG
- patch(null, vnode, container, next, parentComponent)
+ // TODO Suspense
+ patch(
+ null,
+ vnode,
+ container,
+ next,
+ parentComponent,
+ parentSuspense,
+ isSVGContainer(container)
+ )
return next
}
+ const locateClosingAsyncAnchor = (node: Node | null): Node | null => {
+ let match = 0
+ while (node) {
+ node = nextSibling(node)
+ if (node && isComment(node)) {
+ if (node.data === '1') match++
+ if (node.data === '0') {
+ if (match === 0) {
+ return nextSibling(node)
+ } else {
+ match--
+ }
+ }
+ }
+ }
+ return node
+ }
+
return [hydrate, hydrateNode] as const
}
export type MountComponentFn<HostNode, HostElement> = (
initialVNode: VNode<HostNode, HostElement>,
- container: HostElement | null, // only null during hydration
+ container: HostElement,
anchor: HostNode | null,
parentComponent: ComponentInternalInstance | null,
parentSuspense: SuspenseBoundary<HostNode, HostElement> | null,
export type SetupRenderEffectFn<HostNode, HostElement> = (
instance: ComponentInternalInstance,
initialVNode: VNode<HostNode, HostElement>,
- container: HostElement | null, // only null during hydration
+ container: HostElement,
anchor: HostNode | null,
parentSuspense: SuspenseBoundary<HostNode, HostElement> | null,
isSVG: boolean
const mountComponent: MountComponentFn<HostNode, HostElement> = (
initialVNode,
- container, // only null during hydration
+ container,
anchor,
parentComponent,
parentSuspense,
parentSuspense.registerDep(instance, setupRenderEffect)
// Give it a placeholder if this is not hydration
- const placeholder = (instance.subTree = createVNode(Comment))
- processCommentNode(null, placeholder, container!, anchor)
- initialVNode.el = placeholder.el
+ if (!initialVNode.el) {
+ const placeholder = (instance.subTree = createVNode(Comment))
+ processCommentNode(null, placeholder, container!, anchor)
+ }
return
}
}
if (initialVNode.el && hydrateNode) {
// vnode has adopted host node - perform hydration instead of mount.
- hydrateNode(initialVNode.el as Node, subTree, instance)
+ hydrateNode(
+ initialVNode.el as Node,
+ subTree,
+ instance,
+ parentSuspense
+ )
} else {
patch(
null,
subTree,
- container!, // container is only null during hydration
+ container,
anchor,
instance,
parentSuspense,
): VNode {
if (!type) {
if (__DEV__) {
- warn(`Invalid vnode type when creating vnode: ${type}.`)
+ debugger
+ warn(`fsef Invalid vnode type when creating vnode: ${type}.`)
}
type = Comment
}
)
).toBe(
`<div>parent<div class="child">` +
- `<span>from slot</span>` +
+ `<!--1--><span>from slot</span><!--0-->` +
`</div></div>`
)
}
})
)
- ).toBe(`<div>parent<div class="child">fallback</div></div>`)
+ ).toBe(
+ `<div>parent<div class="child"><!--1-->fallback<!--0--></div></div>`
+ )
})
test('nested components with vnode slots', async () => {
)
).toBe(
`<div>parent<div class="child">` +
- `<span>from slot</span>` +
+ `<!--1--><span>from slot</span><!--0-->` +
`</div></div>`
)
})
}
const app = createApp({
+ components: { Child },
template: `<div>parent<Child v-slot="{ msg }"><span>{{ msg }}</span></Child></div>`
})
- app.component('Child', Child)
expect(await renderToString(app)).toBe(
`<div>parent<div class="child">` +
- `<span>from slot</span>` +
+ `<!--1--><span>from slot</span><!--0-->` +
`</div></div>`
)
})
expect(await renderToString(app)).toBe(
`<div>parent<div class="child">` +
+ // no comment anchors because slot is used directly as element children
`<span>from slot</span>` +
`</div></div>`
)
createCommentVNode('qux')
])
)
- ).toBe(`<div>foo<span>bar</span><span>baz</span><!--qux--></div>`)
+ ).toBe(
+ `<div>foo<span>bar</span><!--1--><span>baz</span><!--0--><!--qux--></div>`
+ )
})
test('void elements', async () => {
}
})
- expect(await renderToString(app)).toBe(`<div>async</div>`)
+ expect(await renderToString(app)).toBe(`<!--1--><div>async</div><!--0-->`)
})
test('with async component', async () => {
}
})
- expect(await renderToString(app)).toBe(`<div>async</div>`)
+ expect(await renderToString(app)).toBe(`<!--1--><div>async</div><!--0-->`)
})
test('fallback', async () => {
}
})
- expect(await renderToString(app)).toBe(`<div>fallback</div>`)
+ expect(await renderToString(app)).toBe(
+ `<!--1--><div>fallback</div><!--0-->`
+ )
expect('Uncaught error in async setup').toHaveBeenWarned()
})
})
push: PushFn,
parentComponent: ComponentInternalInstance
) {
+ // template-compiled slots are always rendered as fragments
+ push(`<!--1-->`)
const slotFn = slots[slotName]
if (slotFn) {
if (slotFn.length > 1) {
} else if (fallbackRenderFn) {
fallbackRenderFn()
}
+ push(`<!--0-->`)
}
import { PushFn, ResolvedSSRBuffer, createBuffer } from '../renderToString'
-import { NOOP } from '@vue/shared'
type ContentRenderFn = (push: PushFn) => void
export async function ssrRenderSuspense({
- default: renderContent = NOOP,
- fallback: renderFallback = NOOP
+ default: renderContent,
+ fallback: renderFallback
}: Record<string, ContentRenderFn | undefined>): Promise<ResolvedSSRBuffer> {
try {
- const { push, getBuffer } = createBuffer()
- renderContent(push)
- return await getBuffer()
+ if (renderContent) {
+ const { push, getBuffer } = createBuffer()
+ push(`<!--1-->`)
+ renderContent(push)
+ push(`<!--0-->`)
+ return await getBuffer()
+ } else {
+ return []
+ }
} catch {
- const { push, getBuffer } = createBuffer()
- renderFallback(push)
- return getBuffer()
+ if (renderFallback) {
+ const { push, getBuffer } = createBuffer()
+ push(`<!--1-->`)
+ renderFallback(push)
+ push(`<!--0-->`)
+ return getBuffer()
+ } else {
+ return []
+ }
}
}
push(children ? `<!--${children}-->` : `<!---->`)
break
case Fragment:
+ push(`<!--1-->`) // open
renderVNodeChildren(push, children as VNodeArrayChildren, parentComponent)
+ push(`<!--0-->`) // close
break
default:
if (shapeFlag & ShapeFlags.ELEMENT) {
format === 'esm-bundler-runtime' ? `src/runtime.ts` : `src/index.ts`
const external =
- isGlobalBuild || isRawESMBuild ? [] : Object.keys(pkg.dependencies || {})
+ isGlobalBuild || isRawESMBuild
+ ? []
+ : [
+ ...Object.keys(pkg.dependencies || {}),
+ ...Object.keys(pkg.peerDependencies || {})
+ ]
const nodePlugins = packageOptions.enableNonBrowserBranches
? [