refactor: simplify suspense ssr + adjust behavior

This commit is contained in:
Evan You 2020-03-16 15:38:35 -04:00
parent eb5b32fead
commit 38f0269765
7 changed files with 131 additions and 223 deletions

View File

@ -9,12 +9,12 @@ describe('ssr compile: suspense', () => {
return function ssrRender(_ctx, _push, _parent) { return function ssrRender(_ctx, _push, _parent) {
const _component_foo = _resolveComponent(\\"foo\\") const _component_foo = _resolveComponent(\\"foo\\")
_push(_ssrRenderSuspense({ _ssrRenderSuspense(_push, {
default: (_push) => { default: () => {
_push(_ssrRenderComponent(_component_foo, null, null, _parent)) _push(_ssrRenderComponent(_component_foo, null, null, _parent))
}, },
_: 1 _: 1
})) })
}" }"
`) `)
}) })
@ -36,15 +36,15 @@ describe('ssr compile: suspense', () => {
return function ssrRender(_ctx, _push, _parent) { return function ssrRender(_ctx, _push, _parent) {
const _component_foo = _resolveComponent(\\"foo\\") const _component_foo = _resolveComponent(\\"foo\\")
_push(_ssrRenderSuspense({ _ssrRenderSuspense(_push, {
default: (_push) => { default: () => {
_push(_ssrRenderComponent(_component_foo, null, null, _parent)) _push(_ssrRenderComponent(_component_foo, null, null, _parent))
}, },
fallback: (_push) => { fallback: () => {
_push(\` loading... \`) _push(\` loading... \`)
}, },
_: 1 _: 1
})) })
}" }"
`) `)
}) })

View File

@ -38,7 +38,7 @@ export function ssrTransformSuspense(
wipMap.set(node, wipEntry) wipMap.set(node, wipEntry)
wipEntry.slotsExp = buildSlots(node, context, (_props, children, loc) => { wipEntry.slotsExp = buildSlots(node, context, (_props, children, loc) => {
const fn = createFunctionExpression( const fn = createFunctionExpression(
[`_push`], [],
undefined, // no return, assign body later undefined, // no return, assign body later
true, // newline true, // newline
false, // suspense slots are not treated as normal slots false, // suspense slots are not treated as normal slots
@ -71,8 +71,9 @@ export function ssrProcessSuspense(
} }
// _push(ssrRenderSuspense(slots)) // _push(ssrRenderSuspense(slots))
context.pushStatement( context.pushStatement(
createCallExpression(`_push`, [ createCallExpression(context.helper(SSR_RENDER_SUSPENSE), [
createCallExpression(context.helper(SSR_RENDER_SUSPENSE), [slotsExp]) `_push`,
slotsExp
]) ])
) )
} }

View File

@ -6,8 +6,11 @@ import {
nextTick, nextTick,
defineComponent defineComponent
} from '@vue/runtime-test' } from '@vue/runtime-test'
import { mockWarn } from '@vue/shared'
describe('renderer: component', () => { describe('renderer: component', () => {
mockWarn()
test.todo('should work') test.todo('should work')
test.todo('shouldUpdateComponent') test.todo('shouldUpdateComponent')
@ -40,6 +43,7 @@ describe('renderer: component', () => {
expect(b1).toBe(true) expect(b1).toBe(true)
expect(b2).toBe(true) expect(b2).toBe(true)
expect(b3).toBe('') expect(b3).toBe('')
expect('type check failed for prop "b1"').toHaveBeenWarned()
}) })
}) })

View File

@ -8,11 +8,11 @@ import {
ref, ref,
defineComponent defineComponent
} from 'vue' } from 'vue'
import { escapeHtml, mockError } from '@vue/shared' import { escapeHtml, mockWarn } from '@vue/shared'
import { renderToString, renderComponent } from '../src/renderToString' import { renderToString, renderComponent } from '../src/renderToString'
import { ssrRenderSlot } from '../src/helpers/ssrRenderSlot' import { ssrRenderSlot } from '../src/helpers/ssrRenderSlot'
mockError() mockWarn()
describe('ssr: renderToString', () => { describe('ssr: renderToString', () => {
test('should apply app context', async () => { test('should apply app context', async () => {

View File

@ -1,11 +1,9 @@
import { createApp, h, Suspense } from 'vue' import { createApp, h, Suspense } from 'vue'
import { renderToString } from '../src/renderToString' import { renderToString } from '../src/renderToString'
import { ssrRenderSuspense } from '../src/helpers/ssrRenderSuspense' import { mockWarn } from '@vue/shared'
import { ssrRenderComponent } from '../src'
import { mockError } from '@vue/shared'
describe('SSR Suspense', () => { describe('SSR Suspense', () => {
mockError() mockWarn()
const ResolvingAsync = { const ResolvingAsync = {
async setup() { async setup() {
@ -19,161 +17,109 @@ describe('SSR Suspense', () => {
} }
} }
describe('compiled', () => { test('content', async () => {
test('basic', async () => { const Comp = {
const app = createApp({ render() {
ssrRender(_ctx, _push) { return h(Suspense, null, {
_push( default: h(ResolvingAsync),
ssrRenderSuspense({ fallback: h('div', 'fallback')
default: _push => { })
_push('<div>async</div>') }
} }
})
)
}
})
expect(await renderToString(app)).toBe(`<!--[--><div>async</div><!--]-->`) expect(await renderToString(createApp(Comp))).toBe(`<div>async</div>`)
})
test('with async component', async () => {
const app = createApp({
ssrRender(_ctx, _push) {
_push(
ssrRenderSuspense({
default: _push => {
_push(ssrRenderComponent(ResolvingAsync))
}
})
)
}
})
expect(await renderToString(app)).toBe(`<!--[--><div>async</div><!--]-->`)
})
test('fallback', async () => {
const app = createApp({
ssrRender(_ctx, _push) {
_push(
ssrRenderSuspense({
default: _push => {
_push(ssrRenderComponent(RejectingAsync))
},
fallback: _push => {
_push('<div>fallback</div>')
}
})
)
}
})
expect(await renderToString(app)).toBe(
`<!--[--><div>fallback</div><!--]-->`
)
expect('Uncaught error in async setup').toHaveBeenWarned()
})
}) })
describe('vnode', () => { test('reject', async () => {
test('content', async () => { const Comp = {
const Comp = { render() {
render() { return h(Suspense, null, {
return h(Suspense, null, { default: h(RejectingAsync),
default: h(ResolvingAsync), fallback: h('div', 'fallback')
fallback: h('div', 'fallback') })
})
}
} }
}
expect(await renderToString(createApp(Comp))).toBe(`<div>async</div>`) expect(await renderToString(createApp(Comp))).toBe(`<!---->`)
}) expect('Uncaught error in async setup').toHaveBeenWarned()
expect('missing template').toHaveBeenWarned()
})
test('fallback', async () => { test('2 components', async () => {
const Comp = { const Comp = {
render() { render() {
return h(Suspense, null, { return h(Suspense, null, {
default: h(RejectingAsync), default: h('div', [h(ResolvingAsync), h(ResolvingAsync)]),
fallback: h('div', 'fallback') fallback: h('div', 'fallback')
}) })
}
} }
}
expect(await renderToString(createApp(Comp))).toBe(`<div>fallback</div>`) expect(await renderToString(createApp(Comp))).toBe(
expect('Uncaught error in async setup').toHaveBeenWarned() `<div><div>async</div><div>async</div></div>`
}) )
})
test('2 components', async () => { test('resolving component + rejecting component', async () => {
const Comp = { const Comp = {
render() { render() {
return h(Suspense, null, { return h(Suspense, null, {
default: h('div', [h(ResolvingAsync), h(ResolvingAsync)]), default: h('div', [h(ResolvingAsync), h(RejectingAsync)]),
fallback: h('div', 'fallback') fallback: h('div', 'fallback')
}) })
}
} }
}
expect(await renderToString(createApp(Comp))).toBe( expect(await renderToString(createApp(Comp))).toBe(
`<div><div>async</div><div>async</div></div>` `<div><div>async</div><!----></div>`
) )
}) expect('Uncaught error in async setup').toHaveBeenWarned()
expect('missing template or render function').toHaveBeenWarned()
})
test('resolving component + rejecting component', async () => { test('failing suspense in passing suspense', async () => {
const Comp = { const Comp = {
render() { render() {
return h(Suspense, null, { return h(Suspense, null, {
default: h('div', [h(ResolvingAsync), h(RejectingAsync)]), default: h('div', [
fallback: h('div', 'fallback') h(ResolvingAsync),
}) h(Suspense, null, {
} default: h('div', [h(RejectingAsync)]),
fallback: h('div', 'fallback 2')
})
]),
fallback: h('div', 'fallback 1')
})
} }
}
expect(await renderToString(createApp(Comp))).toBe(`<div>fallback</div>`) expect(await renderToString(createApp(Comp))).toBe(
expect('Uncaught error in async setup').toHaveBeenWarned() `<div><div>async</div><div><!----></div></div>`
}) )
expect('Uncaught error in async setup').toHaveBeenWarned()
expect('missing template').toHaveBeenWarned()
})
test('failing suspense in passing suspense', async () => { test('passing suspense in failing suspense', async () => {
const Comp = { const Comp = {
render() { render() {
return h(Suspense, null, { return h(Suspense, null, {
default: h('div', [ default: h('div', [
h(ResolvingAsync), h(RejectingAsync),
h(Suspense, null, { h(Suspense, null, {
default: h('div', [h(RejectingAsync)]), default: h('div', [h(ResolvingAsync)]),
fallback: h('div', 'fallback 2') fallback: h('div', 'fallback 2')
}) })
]), ]),
fallback: h('div', 'fallback 1') fallback: h('div', 'fallback 1')
}) })
}
} }
}
expect(await renderToString(createApp(Comp))).toBe( expect(await renderToString(createApp(Comp))).toBe(
`<div><div>async</div><div>fallback 2</div></div>` `<div><!----><div><div>async</div></div></div>`
) )
expect('Uncaught error in async setup').toHaveBeenWarned() expect('Uncaught error in async setup').toHaveBeenWarned()
}) expect('missing template').toHaveBeenWarned()
test('passing suspense in failing suspense', async () => {
const Comp = {
render() {
return h(Suspense, null, {
default: h('div', [
h(RejectingAsync),
h(Suspense, null, {
default: h('div', [h(ResolvingAsync)]),
fallback: h('div', 'fallback 2')
})
]),
fallback: h('div', 'fallback 1')
})
}
}
expect(await renderToString(createApp(Comp))).toBe(
`<div>fallback 1</div>`
)
expect('Uncaught error in async setup').toHaveBeenWarned()
})
}) })
}) })

View File

@ -1,30 +1,14 @@
import { PushFn, ResolvedSSRBuffer, createBuffer } from '../renderToString' import { PushFn } from '../renderToString'
type ContentRenderFn = (push: PushFn) => void export async function ssrRenderSuspense(
push: PushFn,
export async function ssrRenderSuspense({ { default: renderContent }: Record<string, (() => void) | undefined>
default: renderContent, ) {
fallback: renderFallback if (renderContent) {
}: Record<string, ContentRenderFn | undefined>): Promise<ResolvedSSRBuffer> { push(`<!--[-->`)
try { renderContent()
if (renderContent) { push(`<!--]-->`)
const { push, getBuffer } = createBuffer() } else {
push(`<!--[-->`) push(`<!---->`)
renderContent(push)
push(`<!--]-->`)
return await getBuffer()
} else {
return []
}
} catch {
if (renderFallback) {
const { push, getBuffer } = createBuffer()
push(`<!--[-->`)
renderFallback(push)
push(`<!--]-->`)
return getBuffer()
} else {
return []
}
} }
} }

View File

@ -11,7 +11,8 @@ import {
ssrUtils, ssrUtils,
Slots, Slots,
createApp, createApp,
ssrContextKey ssrContextKey,
warn
} from 'vue' } from 'vue'
import { import {
ShapeFlags, ShapeFlags,
@ -138,8 +139,6 @@ export function renderComponent(
) )
} }
export const AsyncSetupErrorMarker = Symbol('Vue async setup error')
function renderComponentVNode( function renderComponentVNode(
vnode: VNode, vnode: VNode,
parentComponent: ComponentInternalInstance | null = null parentComponent: ComponentInternalInstance | null = null
@ -153,17 +152,7 @@ function renderComponentVNode(
if (isPromise(res)) { if (isPromise(res)) {
return res return res
.catch(err => { .catch(err => {
// normalize async setup rejection warn(`[@vue/server-renderer]: Uncaught error in async setup:\n`, err)
if (!(err instanceof Error)) {
err = new Error(String(err))
}
err[AsyncSetupErrorMarker] = true
console.error(
`[@vue/server-renderer]: Uncaught error in async setup:\n`,
err
)
// rethrow for suspense
throw err
}) })
.then(() => renderComponentSubTree(instance)) .then(() => renderComponentSubTree(instance))
} else { } else {
@ -192,11 +181,12 @@ function renderComponentSubTree(
} else if (instance.render) { } else if (instance.render) {
renderVNode(push, renderComponentRoot(instance), instance) renderVNode(push, renderComponentRoot(instance), instance)
} else { } else {
throw new Error( warn(
`Component ${ `Component ${
comp.name ? `${comp.name} ` : `` comp.name ? `${comp.name} ` : ``
} is missing template or render function.` } is missing template or render function.`
) )
push(`<!---->`)
} }
} }
return getBuffer() return getBuffer()
@ -233,7 +223,7 @@ function ssrCompile(
err.loc.start.offset, err.loc.start.offset,
err.loc.end.offset err.loc.end.offset
) )
console.error(codeFrame ? `${message}\n${codeFrame}` : message) warn(codeFrame ? `${message}\n${codeFrame}` : message)
} else { } else {
throw err throw err
} }
@ -268,9 +258,13 @@ function renderVNode(
} else if (shapeFlag & ShapeFlags.PORTAL) { } else if (shapeFlag & ShapeFlags.PORTAL) {
renderPortalVNode(vnode, parentComponent) renderPortalVNode(vnode, parentComponent)
} else if (shapeFlag & ShapeFlags.SUSPENSE) { } else if (shapeFlag & ShapeFlags.SUSPENSE) {
push(renderSuspenseVNode(vnode, parentComponent)) renderVNode(
push,
normalizeSuspenseChildren(vnode).content,
parentComponent
)
} else { } else {
console.error( warn(
'[@vue/server-renderer] Invalid VNode type:', '[@vue/server-renderer] Invalid VNode type:',
type, type,
`(${typeof type})` `(${typeof type})`
@ -350,11 +344,11 @@ function renderPortalVNode(
) { ) {
const target = vnode.props && vnode.props.target const target = vnode.props && vnode.props.target
if (!target) { if (!target) {
console.error(`[@vue/server-renderer] Portal is missing target prop.`) warn(`[@vue/server-renderer] Portal is missing target prop.`)
return [] return []
} }
if (!isString(target)) { if (!isString(target)) {
console.error( warn(
`[@vue/server-renderer] Portal target must be a query selector string.` `[@vue/server-renderer] Portal target must be a query selector string.`
) )
return [] return []
@ -385,24 +379,3 @@ async function resolvePortals(context: SSRContext) {
} }
} }
} }
async function renderSuspenseVNode(
vnode: VNode,
parentComponent: ComponentInternalInstance
): Promise<ResolvedSSRBuffer> {
const { content, fallback } = normalizeSuspenseChildren(vnode)
try {
const { push, getBuffer } = createBuffer()
renderVNode(push, content, parentComponent)
// await here so error can be caught
return await getBuffer()
} catch (e) {
if (e[AsyncSetupErrorMarker]) {
const { push, getBuffer } = createBuffer()
renderVNode(push, fallback, parentComponent)
return getBuffer()
} else {
throw e
}
}
}