refactor: rename <portal> to <teleport>

BREAKING CHANGE: `<portal>` has been renamed to `<teleport>`.

    `target` prop is also renmaed to `to`, so the new usage will be:

    ```html
    <Teleport to="#modal-layer" :disabled="isMobile">
      <div class="modal">
        hello
      </div>
    </Teleport>
    ```

    The primary reason for the renaming is to avoid potential naming
    conflict with [native portals](https://wicg.github.io/portals/).
This commit is contained in:
Evan You 2020-03-31 10:52:42 -04:00
parent 8080c38323
commit eee5095692
26 changed files with 290 additions and 283 deletions

View File

@ -11,7 +11,7 @@ import {
RESOLVE_DIRECTIVE, RESOLVE_DIRECTIVE,
TO_HANDLERS, TO_HANDLERS,
helperNameMap, helperNameMap,
PORTAL, TELEPORT,
RESOLVE_DYNAMIC_COMPONENT, RESOLVE_DYNAMIC_COMPONENT,
SUSPENSE, SUSPENSE,
KEEP_ALIVE, KEEP_ALIVE,
@ -272,16 +272,16 @@ describe('compiler: element transform', () => {
}) })
}) })
test('should handle <Portal> with normal children', () => { test('should handle <Teleport> with normal children', () => {
function assert(tag: string) { function assert(tag: string) {
const { root, node } = parseWithElementTransform( const { root, node } = parseWithElementTransform(
`<${tag} target="#foo"><span /></${tag}>` `<${tag} target="#foo"><span /></${tag}>`
) )
expect(root.components.length).toBe(0) expect(root.components.length).toBe(0)
expect(root.helpers).toContain(PORTAL) expect(root.helpers).toContain(TELEPORT)
expect(node).toMatchObject({ expect(node).toMatchObject({
tag: PORTAL, tag: TELEPORT,
props: createObjectMatcher({ props: createObjectMatcher({
target: '#foo' target: '#foo'
}), }),
@ -298,8 +298,8 @@ describe('compiler: element transform', () => {
}) })
} }
assert(`portal`) assert(`teleport`)
assert(`Portal`) assert(`Teleport`)
}) })
test('should handle <Suspense>', () => { test('should handle <Suspense>', () => {

View File

@ -1,5 +1,5 @@
export const FRAGMENT = Symbol(__DEV__ ? `Fragment` : ``) export const FRAGMENT = Symbol(__DEV__ ? `Fragment` : ``)
export const PORTAL = Symbol(__DEV__ ? `Portal` : ``) export const TELEPORT = Symbol(__DEV__ ? `Teleport` : ``)
export const SUSPENSE = Symbol(__DEV__ ? `Suspense` : ``) export const SUSPENSE = Symbol(__DEV__ ? `Suspense` : ``)
export const KEEP_ALIVE = Symbol(__DEV__ ? `KeepAlive` : ``) export const KEEP_ALIVE = Symbol(__DEV__ ? `KeepAlive` : ``)
export const BASE_TRANSITION = Symbol(__DEV__ ? `BaseTransition` : ``) export const BASE_TRANSITION = Symbol(__DEV__ ? `BaseTransition` : ``)
@ -33,7 +33,7 @@ export const WITH_CTX = Symbol(__DEV__ ? `withCtx` : ``)
// Using `any` here because TS doesn't allow symbols as index type. // Using `any` here because TS doesn't allow symbols as index type.
export const helperNameMap: any = { export const helperNameMap: any = {
[FRAGMENT]: `Fragment`, [FRAGMENT]: `Fragment`,
[PORTAL]: `Portal`, [TELEPORT]: `Teleport`,
[SUSPENSE]: `Suspense`, [SUSPENSE]: `Suspense`,
[KEEP_ALIVE]: `KeepAlive`, [KEEP_ALIVE]: `KeepAlive`,
[BASE_TRANSITION]: `BaseTransition`, [BASE_TRANSITION]: `BaseTransition`,

View File

@ -28,7 +28,7 @@ import {
RESOLVE_DYNAMIC_COMPONENT, RESOLVE_DYNAMIC_COMPONENT,
MERGE_PROPS, MERGE_PROPS,
TO_HANDLERS, TO_HANDLERS,
PORTAL, TELEPORT,
KEEP_ALIVE KEEP_ALIVE
} from '../runtimeHelpers' } from '../runtimeHelpers'
import { import {
@ -124,8 +124,8 @@ export const transformElement: NodeTransform = (node, context) => {
const shouldBuildAsSlots = const shouldBuildAsSlots =
isComponent && isComponent &&
// Portal is not a real component and has dedicated runtime handling // Teleport is not a real component and has dedicated runtime handling
vnodeTag !== PORTAL && vnodeTag !== TELEPORT &&
// explained above. // explained above.
vnodeTag !== KEEP_ALIVE vnodeTag !== KEEP_ALIVE
@ -135,7 +135,7 @@ export const transformElement: NodeTransform = (node, context) => {
if (hasDynamicSlots) { if (hasDynamicSlots) {
patchFlag |= PatchFlags.DYNAMIC_SLOTS patchFlag |= PatchFlags.DYNAMIC_SLOTS
} }
} else if (node.children.length === 1 && vnodeTag !== PORTAL) { } else if (node.children.length === 1 && vnodeTag !== TELEPORT) {
const child = node.children[0] const child = node.children[0]
const type = child.type const type = child.type
// check for dynamic text children // check for dynamic text children
@ -217,7 +217,7 @@ export function resolveComponentType(
} }
} }
// 2. built-in components (Portal, Transition, KeepAlive, Suspense...) // 2. built-in components (Teleport, Transition, KeepAlive, Suspense...)
const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag) const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag)
if (builtIn) { if (builtIn) {
// built-ins are simply fallthroughs / have special handling during ssr // built-ins are simply fallthroughs / have special handling during ssr

View File

@ -27,7 +27,7 @@ import {
FRAGMENT, FRAGMENT,
CREATE_COMMENT, CREATE_COMMENT,
OPEN_BLOCK, OPEN_BLOCK,
PORTAL TELEPORT
} from '../runtimeHelpers' } from '../runtimeHelpers'
import { injectProp } from '../utils' import { injectProp } from '../utils'
import { PatchFlags, PatchFlagNames } from '@vue/shared' import { PatchFlags, PatchFlagNames } from '@vue/shared'
@ -218,8 +218,8 @@ function createChildrenCodegenNode(
// component vnodes are always tracked and its children are // component vnodes are always tracked and its children are
// compiled into slots so no need to make it a block // compiled into slots so no need to make it a block
((firstChild as ElementNode).tagType !== ElementTypes.COMPONENT || ((firstChild as ElementNode).tagType !== ElementTypes.COMPONENT ||
// portal has component type but isn't always tracked // teleport has component type but isn't always tracked
vnodeCall.tag === PORTAL) vnodeCall.tag === TELEPORT)
) { ) {
vnodeCall.isBlock = true vnodeCall.isBlock = true
helper(OPEN_BLOCK) helper(OPEN_BLOCK)

View File

@ -25,7 +25,7 @@ import {
import { TransformContext } from './transform' import { TransformContext } from './transform'
import { import {
MERGE_PROPS, MERGE_PROPS,
PORTAL, TELEPORT,
SUSPENSE, SUSPENSE,
KEEP_ALIVE, KEEP_ALIVE,
BASE_TRANSITION BASE_TRANSITION
@ -38,8 +38,8 @@ export const isBuiltInType = (tag: string, expected: string): boolean =>
tag === expected || tag === hyphenate(expected) tag === expected || tag === hyphenate(expected)
export function isCoreComponent(tag: string): symbol | void { export function isCoreComponent(tag: string): symbol | void {
if (isBuiltInType(tag, 'Portal')) { if (isBuiltInType(tag, 'Teleport')) {
return PORTAL return TELEPORT
} else if (isBuiltInType(tag, 'Suspense')) { } else if (isBuiltInType(tag, 'Suspense')) {
return SUSPENSE return SUSPENSE
} else if (isBuiltInType(tag, 'KeepAlive')) { } else if (isBuiltInType(tag, 'KeepAlive')) {

View File

@ -1,13 +1,13 @@
import { compile } from '../src' import { compile } from '../src'
describe('ssr compile: portal', () => { describe('ssr compile: teleport', () => {
test('should work', () => { test('should work', () => {
expect(compile(`<portal :target="target"><div/></portal>`).code) expect(compile(`<teleport :target="target"><div/></teleport>`).code)
.toMatchInlineSnapshot(` .toMatchInlineSnapshot(`
"const { ssrRenderPortal: _ssrRenderPortal } = require(\\"@vue/server-renderer\\") "const { ssrRenderTeleport: _ssrRenderTeleport } = require(\\"@vue/server-renderer\\")
return function ssrRender(_ctx, _push, _parent) { return function ssrRender(_ctx, _push, _parent) {
_ssrRenderPortal(_push, (_push) => { _ssrRenderTeleport(_push, (_push) => {
_push(\`<div></div>\`) _push(\`<div></div>\`)
}, _ctx.target, false, _parent) }, _ctx.target, false, _parent)
}" }"
@ -15,24 +15,26 @@ describe('ssr compile: portal', () => {
}) })
test('disabled prop handling', () => { test('disabled prop handling', () => {
expect(compile(`<portal :target="target" disabled><div/></portal>`).code) expect(
.toMatchInlineSnapshot(` compile(`<teleport :target="target" disabled><div/></teleport>`).code
"const { ssrRenderPortal: _ssrRenderPortal } = require(\\"@vue/server-renderer\\") ).toMatchInlineSnapshot(`
"const { ssrRenderTeleport: _ssrRenderTeleport } = require(\\"@vue/server-renderer\\")
return function ssrRender(_ctx, _push, _parent) { return function ssrRender(_ctx, _push, _parent) {
_ssrRenderPortal(_push, (_push) => { _ssrRenderTeleport(_push, (_push) => {
_push(\`<div></div>\`) _push(\`<div></div>\`)
}, _ctx.target, true, _parent) }, _ctx.target, true, _parent)
}" }"
`) `)
expect( expect(
compile(`<portal :target="target" :disabled="foo"><div/></portal>`).code compile(`<teleport :target="target" :disabled="foo"><div/></teleport>`)
.code
).toMatchInlineSnapshot(` ).toMatchInlineSnapshot(`
"const { ssrRenderPortal: _ssrRenderPortal } = require(\\"@vue/server-renderer\\") "const { ssrRenderTeleport: _ssrRenderTeleport } = require(\\"@vue/server-renderer\\")
return function ssrRender(_ctx, _push, _parent) { return function ssrRender(_ctx, _push, _parent) {
_ssrRenderPortal(_push, (_push) => { _ssrRenderTeleport(_push, (_push) => {
_push(\`<div></div>\`) _push(\`<div></div>\`)
}, _ctx.target, _ctx.foo, _parent) }, _ctx.target, _ctx.foo, _parent)
}" }"

View File

@ -19,11 +19,11 @@ export function createSSRCompilerError(
export const enum SSRErrorCodes { export const enum SSRErrorCodes {
X_SSR_CUSTOM_DIRECTIVE_NO_TRANSFORM = DOMErrorCodes.__EXTEND_POINT__, X_SSR_CUSTOM_DIRECTIVE_NO_TRANSFORM = DOMErrorCodes.__EXTEND_POINT__,
X_SSR_UNSAFE_ATTR_NAME, X_SSR_UNSAFE_ATTR_NAME,
X_SSR_NO_PORTAL_TARGET X_SSR_NO_TELEPORT_TARGET
} }
export const SSRErrorMessages: { [code: number]: string } = { export const SSRErrorMessages: { [code: number]: string } = {
[SSRErrorCodes.X_SSR_CUSTOM_DIRECTIVE_NO_TRANSFORM]: `Custom directive is missing corresponding SSR transform and will be ignored.`, [SSRErrorCodes.X_SSR_CUSTOM_DIRECTIVE_NO_TRANSFORM]: `Custom directive is missing corresponding SSR transform and will be ignored.`,
[SSRErrorCodes.X_SSR_UNSAFE_ATTR_NAME]: `Unsafe attribute name for SSR.`, [SSRErrorCodes.X_SSR_UNSAFE_ATTR_NAME]: `Unsafe attribute name for SSR.`,
[SSRErrorCodes.X_SSR_NO_PORTAL_TARGET]: `No target prop on portal element.` [SSRErrorCodes.X_SSR_NO_TELEPORT_TARGET]: `No target prop on teleport element.`
} }

View File

@ -13,7 +13,7 @@ export const SSR_LOOSE_EQUAL = Symbol(`ssrLooseEqual`)
export const SSR_LOOSE_CONTAIN = Symbol(`ssrLooseContain`) export const SSR_LOOSE_CONTAIN = Symbol(`ssrLooseContain`)
export const SSR_RENDER_DYNAMIC_MODEL = Symbol(`ssrRenderDynamicModel`) export const SSR_RENDER_DYNAMIC_MODEL = Symbol(`ssrRenderDynamicModel`)
export const SSR_GET_DYNAMIC_MODEL_PROPS = Symbol(`ssrGetDynamicModelProps`) export const SSR_GET_DYNAMIC_MODEL_PROPS = Symbol(`ssrGetDynamicModelProps`)
export const SSR_RENDER_PORTAL = Symbol(`ssrRenderPortal`) export const SSR_RENDER_TELEPORT = Symbol(`ssrRenderTeleport`)
export const SSR_RENDER_SUSPENSE = Symbol(`ssrRenderSuspense`) export const SSR_RENDER_SUSPENSE = Symbol(`ssrRenderSuspense`)
export const ssrHelpers = { export const ssrHelpers = {
@ -30,7 +30,7 @@ export const ssrHelpers = {
[SSR_LOOSE_CONTAIN]: `ssrLooseContain`, [SSR_LOOSE_CONTAIN]: `ssrLooseContain`,
[SSR_RENDER_DYNAMIC_MODEL]: `ssrRenderDynamicModel`, [SSR_RENDER_DYNAMIC_MODEL]: `ssrRenderDynamicModel`,
[SSR_GET_DYNAMIC_MODEL_PROPS]: `ssrGetDynamicModelProps`, [SSR_GET_DYNAMIC_MODEL_PROPS]: `ssrGetDynamicModelProps`,
[SSR_RENDER_PORTAL]: `ssrRenderPortal`, [SSR_RENDER_TELEPORT]: `ssrRenderTeleport`,
[SSR_RENDER_SUSPENSE]: `ssrRenderSuspense` [SSR_RENDER_SUSPENSE]: `ssrRenderSuspense`
} }

View File

@ -11,7 +11,7 @@ import {
buildSlots, buildSlots,
FunctionExpression, FunctionExpression,
TemplateChildNode, TemplateChildNode,
PORTAL, TELEPORT,
createIfStatement, createIfStatement,
createSimpleExpression, createSimpleExpression,
getBaseTransformPreset, getBaseTransformPreset,
@ -39,7 +39,7 @@ import {
processChildren, processChildren,
processChildrenAsStatement processChildrenAsStatement
} from '../ssrCodegenTransform' } from '../ssrCodegenTransform'
import { ssrProcessPortal } from './ssrTransformPortal' import { ssrProcessTeleport } from './ssrTransformTeleport'
import { import {
ssrProcessSuspense, ssrProcessSuspense,
ssrTransformSuspense ssrTransformSuspense
@ -146,8 +146,8 @@ export function ssrProcessComponent(
if (!node.ssrCodegenNode) { if (!node.ssrCodegenNode) {
// this is a built-in component that fell-through. // this is a built-in component that fell-through.
const component = componentTypeMap.get(node)! const component = componentTypeMap.get(node)!
if (component === PORTAL) { if (component === TELEPORT) {
return ssrProcessPortal(node, context) return ssrProcessTeleport(node, context)
} else if (component === SUSPENSE) { } else if (component === SUSPENSE) {
return ssrProcessSuspense(node, context) return ssrProcessSuspense(node, context)
} else { } else {

View File

@ -12,17 +12,17 @@ import {
processChildrenAsStatement processChildrenAsStatement
} from '../ssrCodegenTransform' } from '../ssrCodegenTransform'
import { createSSRCompilerError, SSRErrorCodes } from '../errors' import { createSSRCompilerError, SSRErrorCodes } from '../errors'
import { SSR_RENDER_PORTAL } from '../runtimeHelpers' import { SSR_RENDER_TELEPORT } from '../runtimeHelpers'
// Note: this is a 2nd-pass codegen transform. // Note: this is a 2nd-pass codegen transform.
export function ssrProcessPortal( export function ssrProcessTeleport(
node: ComponentNode, node: ComponentNode,
context: SSRTransformContext context: SSRTransformContext
) { ) {
const targetProp = findProp(node, 'target') const targetProp = findProp(node, 'target')
if (!targetProp) { if (!targetProp) {
context.onError( context.onError(
createSSRCompilerError(SSRErrorCodes.X_SSR_NO_PORTAL_TARGET, node.loc) createSSRCompilerError(SSRErrorCodes.X_SSR_NO_TELEPORT_TARGET, node.loc)
) )
return return
} }
@ -37,7 +37,7 @@ export function ssrProcessPortal(
if (!target) { if (!target) {
context.onError( context.onError(
createSSRCompilerError( createSSRCompilerError(
SSRErrorCodes.X_SSR_NO_PORTAL_TARGET, SSRErrorCodes.X_SSR_NO_TELEPORT_TARGET,
targetProp.loc targetProp.loc
) )
) )
@ -60,7 +60,7 @@ export function ssrProcessPortal(
) )
contentRenderFn.body = processChildrenAsStatement(node.children, context) contentRenderFn.body = processChildrenAsStatement(node.children, context)
context.pushStatement( context.pushStatement(
createCallExpression(context.helper(SSR_RENDER_PORTAL), [ createCallExpression(context.helper(SSR_RENDER_TELEPORT), [
`_push`, `_push`,
contentRenderFn, contentRenderFn,
target, target,

View File

@ -731,5 +731,5 @@ describe('Suspense', () => {
expect(serializeInner(root)).toBe(`<div>Child A</div><div>Child B</div>`) expect(serializeInner(root)).toBe(`<div>Child A</div><div>Child B</div>`)
}) })
test.todo('portal inside suspense') test.todo('teleport inside suspense')
}) })

View File

@ -3,28 +3,28 @@ import {
serializeInner, serializeInner,
render, render,
h, h,
Portal, Teleport,
Text, Text,
ref, ref,
nextTick nextTick
} from '@vue/runtime-test' } from '@vue/runtime-test'
import { createVNode, Fragment } from '../../src/vnode' import { createVNode, Fragment } from '../../src/vnode'
describe('renderer: portal', () => { describe('renderer: teleport', () => {
test('should work', () => { test('should work', () => {
const target = nodeOps.createElement('div') const target = nodeOps.createElement('div')
const root = nodeOps.createElement('div') const root = nodeOps.createElement('div')
render( render(
h(() => [ h(() => [
h(Portal, { target }, h('div', 'teleported')), h(Teleport, { to: target }, h('div', 'teleported')),
h('div', 'root') h('div', 'root')
]), ]),
root root
) )
expect(serializeInner(root)).toMatchInlineSnapshot( expect(serializeInner(root)).toMatchInlineSnapshot(
`"<!--portal start--><!--portal end--><div>root</div>"` `"<!--teleport start--><!--teleport end--><div>root</div>"`
) )
expect(serializeInner(target)).toMatchInlineSnapshot( expect(serializeInner(target)).toMatchInlineSnapshot(
`"<div>teleported</div>"` `"<div>teleported</div>"`
@ -39,14 +39,14 @@ describe('renderer: portal', () => {
render( render(
h(() => [ h(() => [
h(Portal, { target: target.value }, h('div', 'teleported')), h(Teleport, { to: target.value }, h('div', 'teleported')),
h('div', 'root') h('div', 'root')
]), ]),
root root
) )
expect(serializeInner(root)).toMatchInlineSnapshot( expect(serializeInner(root)).toMatchInlineSnapshot(
`"<!--portal start--><!--portal end--><div>root</div>"` `"<!--teleport start--><!--teleport end--><div>root</div>"`
) )
expect(serializeInner(targetA)).toMatchInlineSnapshot( expect(serializeInner(targetA)).toMatchInlineSnapshot(
`"<div>teleported</div>"` `"<div>teleported</div>"`
@ -57,7 +57,7 @@ describe('renderer: portal', () => {
await nextTick() await nextTick()
expect(serializeInner(root)).toMatchInlineSnapshot( expect(serializeInner(root)).toMatchInlineSnapshot(
`"<!--portal start--><!--portal end--><div>root</div>"` `"<!--teleport start--><!--teleport end--><div>root</div>"`
) )
expect(serializeInner(targetA)).toMatchInlineSnapshot(`""`) expect(serializeInner(targetA)).toMatchInlineSnapshot(`""`)
expect(serializeInner(targetB)).toMatchInlineSnapshot( expect(serializeInner(targetB)).toMatchInlineSnapshot(
@ -70,7 +70,7 @@ describe('renderer: portal', () => {
const root = nodeOps.createElement('div') const root = nodeOps.createElement('div')
const children = ref([h('div', 'teleported')]) const children = ref([h('div', 'teleported')])
render(h(Portal, { target }, children.value), root) render(h(Teleport, { to: target }, children.value), root)
expect(serializeInner(target)).toMatchInlineSnapshot( expect(serializeInner(target)).toMatchInlineSnapshot(
`"<div>teleported</div>"` `"<div>teleported</div>"`
) )
@ -96,7 +96,7 @@ describe('renderer: portal', () => {
render( render(
h(() => [ h(() => [
h(Portal, { target }, h('div', 'teleported')), h(Teleport, { to: target }, h('div', 'teleported')),
h('div', 'root') h('div', 'root')
]), ]),
root root
@ -109,28 +109,28 @@ describe('renderer: portal', () => {
expect(serializeInner(target)).toBe('') expect(serializeInner(target)).toBe('')
}) })
test('multiple portal with same target', () => { test('multiple teleport with same target', () => {
const target = nodeOps.createElement('div') const target = nodeOps.createElement('div')
const root = nodeOps.createElement('div') const root = nodeOps.createElement('div')
render( render(
h('div', [ h('div', [
h(Portal, { target }, h('div', 'one')), h(Teleport, { to: target }, h('div', 'one')),
h(Portal, { target }, 'two') h(Teleport, { to: target }, 'two')
]), ]),
root root
) )
expect(serializeInner(root)).toMatchInlineSnapshot( expect(serializeInner(root)).toMatchInlineSnapshot(
`"<div><!--portal start--><!--portal end--><!--portal start--><!--portal end--></div>"` `"<div><!--teleport start--><!--teleport end--><!--teleport start--><!--teleport end--></div>"`
) )
expect(serializeInner(target)).toMatchInlineSnapshot(`"<div>one</div>two"`) expect(serializeInner(target)).toMatchInlineSnapshot(`"<div>one</div>two"`)
// update existing content // update existing content
render( render(
h('div', [ h('div', [
h(Portal, { target }, [h('div', 'one'), h('div', 'two')]), h(Teleport, { to: target }, [h('div', 'one'), h('div', 'two')]),
h(Portal, { target }, 'three') h(Teleport, { to: target }, 'three')
]), ]),
root root
) )
@ -139,38 +139,38 @@ describe('renderer: portal', () => {
) )
// toggling // toggling
render(h('div', [null, h(Portal, { target }, 'three')]), root) render(h('div', [null, h(Teleport, { to: target }, 'three')]), root)
expect(serializeInner(root)).toMatchInlineSnapshot( expect(serializeInner(root)).toMatchInlineSnapshot(
`"<div><!----><!--portal start--><!--portal end--></div>"` `"<div><!----><!--teleport start--><!--teleport end--></div>"`
) )
expect(serializeInner(target)).toMatchInlineSnapshot(`"three"`) expect(serializeInner(target)).toMatchInlineSnapshot(`"three"`)
// toggle back // toggle back
render( render(
h('div', [ h('div', [
h(Portal, { target }, [h('div', 'one'), h('div', 'two')]), h(Teleport, { to: target }, [h('div', 'one'), h('div', 'two')]),
h(Portal, { target }, 'three') h(Teleport, { to: target }, 'three')
]), ]),
root root
) )
expect(serializeInner(root)).toMatchInlineSnapshot( expect(serializeInner(root)).toMatchInlineSnapshot(
`"<div><!--portal start--><!--portal end--><!--portal start--><!--portal end--></div>"` `"<div><!--teleport start--><!--teleport end--><!--teleport start--><!--teleport end--></div>"`
) )
// should append // should append
expect(serializeInner(target)).toMatchInlineSnapshot( expect(serializeInner(target)).toMatchInlineSnapshot(
`"three<div>one</div><div>two</div>"` `"three<div>one</div><div>two</div>"`
) )
// toggle the other portal // toggle the other teleport
render( render(
h('div', [ h('div', [
h(Portal, { target }, [h('div', 'one'), h('div', 'two')]), h(Teleport, { to: target }, [h('div', 'one'), h('div', 'two')]),
null null
]), ]),
root root
) )
expect(serializeInner(root)).toMatchInlineSnapshot( expect(serializeInner(root)).toMatchInlineSnapshot(
`"<div><!--portal start--><!--portal end--><!----></div>"` `"<div><!--teleport start--><!--teleport end--><!----></div>"`
) )
expect(serializeInner(target)).toMatchInlineSnapshot( expect(serializeInner(target)).toMatchInlineSnapshot(
`"<div>one</div><div>two</div>"` `"<div>one</div><div>two</div>"`
@ -183,14 +183,14 @@ describe('renderer: portal', () => {
const renderWithDisabled = (disabled: boolean) => { const renderWithDisabled = (disabled: boolean) => {
return h(Fragment, [ return h(Fragment, [
h(Portal, { target, disabled }, h('div', 'teleported')), h(Teleport, { to: target, disabled }, h('div', 'teleported')),
h('div', 'root') h('div', 'root')
]) ])
} }
render(renderWithDisabled(false), root) render(renderWithDisabled(false), root)
expect(serializeInner(root)).toMatchInlineSnapshot( expect(serializeInner(root)).toMatchInlineSnapshot(
`"<!--portal start--><!--portal end--><div>root</div>"` `"<!--teleport start--><!--teleport end--><div>root</div>"`
) )
expect(serializeInner(target)).toMatchInlineSnapshot( expect(serializeInner(target)).toMatchInlineSnapshot(
`"<div>teleported</div>"` `"<div>teleported</div>"`
@ -198,33 +198,33 @@ describe('renderer: portal', () => {
render(renderWithDisabled(true), root) render(renderWithDisabled(true), root)
expect(serializeInner(root)).toMatchInlineSnapshot( expect(serializeInner(root)).toMatchInlineSnapshot(
`"<!--portal start--><div>teleported</div><!--portal end--><div>root</div>"` `"<!--teleport start--><div>teleported</div><!--teleport end--><div>root</div>"`
) )
expect(serializeInner(target)).toBe(``) expect(serializeInner(target)).toBe(``)
// toggle back // toggle back
render(renderWithDisabled(false), root) render(renderWithDisabled(false), root)
expect(serializeInner(root)).toMatchInlineSnapshot( expect(serializeInner(root)).toMatchInlineSnapshot(
`"<!--portal start--><!--portal end--><div>root</div>"` `"<!--teleport start--><!--teleport end--><div>root</div>"`
) )
expect(serializeInner(target)).toMatchInlineSnapshot( expect(serializeInner(target)).toMatchInlineSnapshot(
`"<div>teleported</div>"` `"<div>teleported</div>"`
) )
}) })
test('moving portal while enabled', () => { test('moving teleport while enabled', () => {
const target = nodeOps.createElement('div') const target = nodeOps.createElement('div')
const root = nodeOps.createElement('div') const root = nodeOps.createElement('div')
render( render(
h(Fragment, [ h(Fragment, [
h(Portal, { target }, h('div', 'teleported')), h(Teleport, { to: target }, h('div', 'teleported')),
h('div', 'root') h('div', 'root')
]), ]),
root root
) )
expect(serializeInner(root)).toMatchInlineSnapshot( expect(serializeInner(root)).toMatchInlineSnapshot(
`"<!--portal start--><!--portal end--><div>root</div>"` `"<!--teleport start--><!--teleport end--><div>root</div>"`
) )
expect(serializeInner(target)).toMatchInlineSnapshot( expect(serializeInner(target)).toMatchInlineSnapshot(
`"<div>teleported</div>"` `"<div>teleported</div>"`
@ -233,12 +233,12 @@ describe('renderer: portal', () => {
render( render(
h(Fragment, [ h(Fragment, [
h('div', 'root'), h('div', 'root'),
h(Portal, { target }, h('div', 'teleported')) h(Teleport, { to: target }, h('div', 'teleported'))
]), ]),
root root
) )
expect(serializeInner(root)).toMatchInlineSnapshot( expect(serializeInner(root)).toMatchInlineSnapshot(
`"<div>root</div><!--portal start--><!--portal end-->"` `"<div>root</div><!--teleport start--><!--teleport end-->"`
) )
expect(serializeInner(target)).toMatchInlineSnapshot( expect(serializeInner(target)).toMatchInlineSnapshot(
`"<div>teleported</div>"` `"<div>teleported</div>"`
@ -246,56 +246,56 @@ describe('renderer: portal', () => {
render( render(
h(Fragment, [ h(Fragment, [
h(Portal, { target }, h('div', 'teleported')), h(Teleport, { to: target }, h('div', 'teleported')),
h('div', 'root') h('div', 'root')
]), ]),
root root
) )
expect(serializeInner(root)).toMatchInlineSnapshot( expect(serializeInner(root)).toMatchInlineSnapshot(
`"<!--portal start--><!--portal end--><div>root</div>"` `"<!--teleport start--><!--teleport end--><div>root</div>"`
) )
expect(serializeInner(target)).toMatchInlineSnapshot( expect(serializeInner(target)).toMatchInlineSnapshot(
`"<div>teleported</div>"` `"<div>teleported</div>"`
) )
}) })
test('moving portal while disabled', () => { test('moving teleport while disabled', () => {
const target = nodeOps.createElement('div') const target = nodeOps.createElement('div')
const root = nodeOps.createElement('div') const root = nodeOps.createElement('div')
render( render(
h(Fragment, [ h(Fragment, [
h(Portal, { target, disabled: true }, h('div', 'teleported')), h(Teleport, { to: target, disabled: true }, h('div', 'teleported')),
h('div', 'root') h('div', 'root')
]), ]),
root root
) )
expect(serializeInner(root)).toMatchInlineSnapshot( expect(serializeInner(root)).toMatchInlineSnapshot(
`"<!--portal start--><div>teleported</div><!--portal end--><div>root</div>"` `"<!--teleport start--><div>teleported</div><!--teleport end--><div>root</div>"`
) )
expect(serializeInner(target)).toBe('') expect(serializeInner(target)).toBe('')
render( render(
h(Fragment, [ h(Fragment, [
h('div', 'root'), h('div', 'root'),
h(Portal, { target, disabled: true }, h('div', 'teleported')) h(Teleport, { to: target, disabled: true }, h('div', 'teleported'))
]), ]),
root root
) )
expect(serializeInner(root)).toMatchInlineSnapshot( expect(serializeInner(root)).toMatchInlineSnapshot(
`"<div>root</div><!--portal start--><div>teleported</div><!--portal end-->"` `"<div>root</div><!--teleport start--><div>teleported</div><!--teleport end-->"`
) )
expect(serializeInner(target)).toBe('') expect(serializeInner(target)).toBe('')
render( render(
h(Fragment, [ h(Fragment, [
h(Portal, { target, disabled: true }, h('div', 'teleported')), h(Teleport, { to: target, disabled: true }, h('div', 'teleported')),
h('div', 'root') h('div', 'root')
]), ]),
root root
) )
expect(serializeInner(root)).toMatchInlineSnapshot( expect(serializeInner(root)).toMatchInlineSnapshot(
`"<!--portal start--><div>teleported</div><!--portal end--><div>root</div>"` `"<!--teleport start--><div>teleported</div><!--teleport end--><div>root</div>"`
) )
expect(serializeInner(target)).toBe('') expect(serializeInner(target)).toBe('')
}) })

View File

@ -4,7 +4,7 @@ import {
ref, ref,
nextTick, nextTick,
VNode, VNode,
Portal, Teleport,
createStaticVNode, createStaticVNode,
Suspense, Suspense,
onMounted, onMounted,
@ -153,18 +153,18 @@ describe('SSR hydration', () => {
) )
}) })
test('Portal', async () => { test('Teleport', async () => {
const msg = ref('foo') const msg = ref('foo')
const fn = jest.fn() const fn = jest.fn()
const portalContainer = document.createElement('div') const teleportContainer = document.createElement('div')
portalContainer.id = 'portal' teleportContainer.id = 'teleport'
portalContainer.innerHTML = `<span>foo</span><span class="foo"></span><!---->` teleportContainer.innerHTML = `<span>foo</span><span class="foo"></span><!---->`
document.body.appendChild(portalContainer) document.body.appendChild(teleportContainer)
const { vnode, container } = mountWithHydration( const { vnode, container } = mountWithHydration(
'<!--portal start--><!--portal end-->', '<!--teleport start--><!--teleport end-->',
() => () =>
h(Portal, { target: '#portal' }, [ h(Teleport, { to: '#teleport' }, [
h('span', msg.value), h('span', msg.value),
h('span', { class: msg.value, onClick: fn }) h('span', { class: msg.value, onClick: fn })
]) ])
@ -173,120 +173,120 @@ describe('SSR hydration', () => {
expect(vnode.el).toBe(container.firstChild) expect(vnode.el).toBe(container.firstChild)
expect(vnode.anchor).toBe(container.lastChild) expect(vnode.anchor).toBe(container.lastChild)
expect(vnode.target).toBe(portalContainer) expect(vnode.target).toBe(teleportContainer)
expect((vnode.children as VNode[])[0].el).toBe( expect((vnode.children as VNode[])[0].el).toBe(
portalContainer.childNodes[0] teleportContainer.childNodes[0]
) )
expect((vnode.children as VNode[])[1].el).toBe( expect((vnode.children as VNode[])[1].el).toBe(
portalContainer.childNodes[1] teleportContainer.childNodes[1]
) )
expect(vnode.targetAnchor).toBe(portalContainer.childNodes[2]) expect(vnode.targetAnchor).toBe(teleportContainer.childNodes[2])
// event handler // event handler
triggerEvent('click', portalContainer.querySelector('.foo')!) triggerEvent('click', teleportContainer.querySelector('.foo')!)
expect(fn).toHaveBeenCalled() expect(fn).toHaveBeenCalled()
msg.value = 'bar' msg.value = 'bar'
await nextTick() await nextTick()
expect(portalContainer.innerHTML).toBe( expect(teleportContainer.innerHTML).toBe(
`<span>bar</span><span class="bar"></span><!---->` `<span>bar</span><span class="bar"></span><!---->`
) )
}) })
test('Portal (multiple + integration)', async () => { test('Teleport (multiple + integration)', async () => {
const msg = ref('foo') const msg = ref('foo')
const fn1 = jest.fn() const fn1 = jest.fn()
const fn2 = jest.fn() const fn2 = jest.fn()
const Comp = () => [ const Comp = () => [
h(Portal, { target: '#portal2' }, [ h(Teleport, { to: '#teleport2' }, [
h('span', msg.value), h('span', msg.value),
h('span', { class: msg.value, onClick: fn1 }) h('span', { class: msg.value, onClick: fn1 })
]), ]),
h(Portal, { target: '#portal2' }, [ h(Teleport, { to: '#teleport2' }, [
h('span', msg.value + '2'), h('span', msg.value + '2'),
h('span', { class: msg.value + '2', onClick: fn2 }) h('span', { class: msg.value + '2', onClick: fn2 })
]) ])
] ]
const portalContainer = document.createElement('div') const teleportContainer = document.createElement('div')
portalContainer.id = 'portal2' teleportContainer.id = 'teleport2'
const ctx: SSRContext = {} const ctx: SSRContext = {}
const mainHtml = await renderToString(h(Comp), ctx) const mainHtml = await renderToString(h(Comp), ctx)
expect(mainHtml).toMatchInlineSnapshot( expect(mainHtml).toMatchInlineSnapshot(
`"<!--[--><!--portal start--><!--portal end--><!--portal start--><!--portal end--><!--]-->"` `"<!--[--><!--teleport start--><!--teleport end--><!--teleport start--><!--teleport end--><!--]-->"`
) )
const portalHtml = ctx.portals!['#portal2'] const teleportHtml = ctx.teleports!['#teleport2']
expect(portalHtml).toMatchInlineSnapshot( expect(teleportHtml).toMatchInlineSnapshot(
`"<span>foo</span><span class=\\"foo\\"></span><!----><span>foo2</span><span class=\\"foo2\\"></span><!---->"` `"<span>foo</span><span class=\\"foo\\"></span><!----><span>foo2</span><span class=\\"foo2\\"></span><!---->"`
) )
portalContainer.innerHTML = portalHtml teleportContainer.innerHTML = teleportHtml
document.body.appendChild(portalContainer) document.body.appendChild(teleportContainer)
const { vnode, container } = mountWithHydration(mainHtml, Comp) const { vnode, container } = mountWithHydration(mainHtml, Comp)
expect(vnode.el).toBe(container.firstChild) expect(vnode.el).toBe(container.firstChild)
const portalVnode1 = (vnode.children as VNode[])[0] const teleportVnode1 = (vnode.children as VNode[])[0]
const portalVnode2 = (vnode.children as VNode[])[1] const teleportVnode2 = (vnode.children as VNode[])[1]
expect(portalVnode1.el).toBe(container.childNodes[1]) expect(teleportVnode1.el).toBe(container.childNodes[1])
expect(portalVnode1.anchor).toBe(container.childNodes[2]) expect(teleportVnode1.anchor).toBe(container.childNodes[2])
expect(portalVnode2.el).toBe(container.childNodes[3]) expect(teleportVnode2.el).toBe(container.childNodes[3])
expect(portalVnode2.anchor).toBe(container.childNodes[4]) expect(teleportVnode2.anchor).toBe(container.childNodes[4])
expect(portalVnode1.target).toBe(portalContainer) expect(teleportVnode1.target).toBe(teleportContainer)
expect((portalVnode1 as any).children[0].el).toBe( expect((teleportVnode1 as any).children[0].el).toBe(
portalContainer.childNodes[0] teleportContainer.childNodes[0]
) )
expect(portalVnode1.targetAnchor).toBe(portalContainer.childNodes[2]) expect(teleportVnode1.targetAnchor).toBe(teleportContainer.childNodes[2])
expect(portalVnode2.target).toBe(portalContainer) expect(teleportVnode2.target).toBe(teleportContainer)
expect((portalVnode2 as any).children[0].el).toBe( expect((teleportVnode2 as any).children[0].el).toBe(
portalContainer.childNodes[3] teleportContainer.childNodes[3]
) )
expect(portalVnode2.targetAnchor).toBe(portalContainer.childNodes[5]) expect(teleportVnode2.targetAnchor).toBe(teleportContainer.childNodes[5])
// // event handler // // event handler
triggerEvent('click', portalContainer.querySelector('.foo')!) triggerEvent('click', teleportContainer.querySelector('.foo')!)
expect(fn1).toHaveBeenCalled() expect(fn1).toHaveBeenCalled()
triggerEvent('click', portalContainer.querySelector('.foo2')!) triggerEvent('click', teleportContainer.querySelector('.foo2')!)
expect(fn2).toHaveBeenCalled() expect(fn2).toHaveBeenCalled()
msg.value = 'bar' msg.value = 'bar'
await nextTick() await nextTick()
expect(portalContainer.innerHTML).toMatchInlineSnapshot( expect(teleportContainer.innerHTML).toMatchInlineSnapshot(
`"<span>bar</span><span class=\\"bar\\"></span><!----><span>bar2</span><span class=\\"bar2\\"></span><!---->"` `"<span>bar</span><span class=\\"bar\\"></span><!----><span>bar2</span><span class=\\"bar2\\"></span><!---->"`
) )
}) })
test('Portal (disabled)', async () => { test('Teleport (disabled)', async () => {
const msg = ref('foo') const msg = ref('foo')
const fn1 = jest.fn() const fn1 = jest.fn()
const fn2 = jest.fn() const fn2 = jest.fn()
const Comp = () => [ const Comp = () => [
h('div', 'foo'), h('div', 'foo'),
h(Portal, { target: '#portal3', disabled: true }, [ h(Teleport, { to: '#teleport3', disabled: true }, [
h('span', msg.value), h('span', msg.value),
h('span', { class: msg.value, onClick: fn1 }) h('span', { class: msg.value, onClick: fn1 })
]), ]),
h('div', { class: msg.value + '2', onClick: fn2 }, 'bar') h('div', { class: msg.value + '2', onClick: fn2 }, 'bar')
] ]
const portalContainer = document.createElement('div') const teleportContainer = document.createElement('div')
portalContainer.id = 'portal3' teleportContainer.id = 'teleport3'
const ctx: SSRContext = {} const ctx: SSRContext = {}
const mainHtml = await renderToString(h(Comp), ctx) const mainHtml = await renderToString(h(Comp), ctx)
expect(mainHtml).toMatchInlineSnapshot( expect(mainHtml).toMatchInlineSnapshot(
`"<!--[--><div>foo</div><!--portal start--><span>foo</span><span class=\\"foo\\"></span><!--portal end--><div class=\\"foo2\\">bar</div><!--]-->"` `"<!--[--><div>foo</div><!--teleport start--><span>foo</span><span class=\\"foo\\"></span><!--teleport end--><div class=\\"foo2\\">bar</div><!--]-->"`
) )
const portalHtml = ctx.portals!['#portal3'] const teleportHtml = ctx.teleports!['#teleport3']
expect(portalHtml).toMatchInlineSnapshot(`"<!---->"`) expect(teleportHtml).toMatchInlineSnapshot(`"<!---->"`)
portalContainer.innerHTML = portalHtml teleportContainer.innerHTML = teleportHtml
document.body.appendChild(portalContainer) document.body.appendChild(teleportContainer)
const { vnode, container } = mountWithHydration(mainHtml, Comp) const { vnode, container } = mountWithHydration(mainHtml, Comp)
expect(vnode.el).toBe(container.firstChild) expect(vnode.el).toBe(container.firstChild)
@ -294,19 +294,19 @@ describe('SSR hydration', () => {
expect(children[0].el).toBe(container.childNodes[1]) expect(children[0].el).toBe(container.childNodes[1])
const portalVnode = children[1] const teleportVnode = children[1]
expect(portalVnode.el).toBe(container.childNodes[2]) expect(teleportVnode.el).toBe(container.childNodes[2])
expect((portalVnode.children as VNode[])[0].el).toBe( expect((teleportVnode.children as VNode[])[0].el).toBe(
container.childNodes[3] container.childNodes[3]
) )
expect((portalVnode.children as VNode[])[1].el).toBe( expect((teleportVnode.children as VNode[])[1].el).toBe(
container.childNodes[4] container.childNodes[4]
) )
expect(portalVnode.anchor).toBe(container.childNodes[5]) expect(teleportVnode.anchor).toBe(container.childNodes[5])
expect(children[2].el).toBe(container.childNodes[6]) expect(children[2].el).toBe(container.childNodes[6])
expect(portalVnode.target).toBe(portalContainer) expect(teleportVnode.target).toBe(teleportContainer)
expect(portalVnode.targetAnchor).toBe(portalContainer.childNodes[0]) expect(teleportVnode.targetAnchor).toBe(teleportContainer.childNodes[0])
// // event handler // // event handler
triggerEvent('click', container.querySelector('.foo')!) triggerEvent('click', container.querySelector('.foo')!)
@ -318,7 +318,7 @@ describe('SSR hydration', () => {
msg.value = 'bar' msg.value = 'bar'
await nextTick() await nextTick()
expect(container.innerHTML).toMatchInlineSnapshot( expect(container.innerHTML).toMatchInlineSnapshot(
`"<!--[--><div>foo</div><!--portal start--><span>bar</span><span class=\\"bar\\"></span><!--portal end--><div class=\\"bar2\\">bar</div><!--]-->"` `"<!--[--><div>foo</div><!--teleport start--><span>bar</span><span class=\\"bar\\"></span><!--teleport end--><div class=\\"bar2\\">bar</div><!--]-->"`
) )
}) })

View File

@ -88,7 +88,7 @@ export interface ComponentOptionsBase<
call?: never call?: never
// type-only differentiators for built-in Vnode types // type-only differentiators for built-in Vnode types
__isFragment?: never __isFragment?: never
__isPortal?: never __isTeleport?: never
__isSuspense?: never __isSuspense?: never
} }

View File

@ -11,26 +11,26 @@ import { VNode, VNodeArrayChildren, VNodeProps } from '../vnode'
import { isString, ShapeFlags } from '@vue/shared' import { isString, ShapeFlags } from '@vue/shared'
import { warn } from '../warning' import { warn } from '../warning'
export interface PortalProps { export interface TeleportProps {
target: string | RendererElement to: string | RendererElement
disabled?: boolean disabled?: boolean
} }
export const isPortal = (type: any): boolean => type.__isPortal export const isTeleport = (type: any): boolean => type.__isTeleport
const isPortalDisabled = (props: VNode['props']): boolean => const isTeleportDisabled = (props: VNode['props']): boolean =>
props && (props.disabled || props.disabled === '') props && (props.disabled || props.disabled === '')
const resolveTarget = <T = RendererElement>( const resolveTarget = <T = RendererElement>(
props: PortalProps | null, props: TeleportProps | null,
select: RendererOptions['querySelector'] select: RendererOptions['querySelector']
): T | null => { ): T | null => {
const targetSelector = props && props.target const targetSelector = props && props.to
if (isString(targetSelector)) { if (isString(targetSelector)) {
if (!select) { if (!select) {
__DEV__ && __DEV__ &&
warn( warn(
`Current renderer does not support string target for Portals. ` + `Current renderer does not support string target for Teleports. ` +
`(missing querySelector renderer option)` `(missing querySelector renderer option)`
) )
return null return null
@ -39,21 +39,21 @@ const resolveTarget = <T = RendererElement>(
if (!target) { if (!target) {
__DEV__ && __DEV__ &&
warn( warn(
`Failed to locate Portal target with selector "${targetSelector}".` `Failed to locate Teleport target with selector "${targetSelector}".`
) )
} }
return target as any return target as any
} }
} else { } else {
if (__DEV__ && !targetSelector) { if (__DEV__ && !targetSelector) {
warn(`Invalid Portal target: ${targetSelector}`) warn(`Invalid Teleport target: ${targetSelector}`)
} }
return targetSelector as any return targetSelector as any
} }
} }
export const PortalImpl = { export const TeleportImpl = {
__isPortal: true, __isTeleport: true,
process( process(
n1: VNode | null, n1: VNode | null,
n2: VNode, n2: VNode,
@ -72,32 +72,32 @@ export const PortalImpl = {
o: { insert, querySelector, createText, createComment } o: { insert, querySelector, createText, createComment }
} = internals } = internals
const disabled = isPortalDisabled(n2.props) const disabled = isTeleportDisabled(n2.props)
const { shapeFlag, children } = n2 const { shapeFlag, children } = n2
if (n1 == null) { if (n1 == null) {
// insert anchors in the main view // insert anchors in the main view
const placeholder = (n2.el = __DEV__ const placeholder = (n2.el = __DEV__
? createComment('portal start') ? createComment('teleport start')
: createText('')) : createText(''))
const mainAnchor = (n2.anchor = __DEV__ const mainAnchor = (n2.anchor = __DEV__
? createComment('portal end') ? createComment('teleport end')
: createText('')) : createText(''))
insert(placeholder, container, anchor) insert(placeholder, container, anchor)
insert(mainAnchor, container, anchor) insert(mainAnchor, container, anchor)
const target = (n2.target = resolveTarget( const target = (n2.target = resolveTarget(
n2.props as PortalProps, n2.props as TeleportProps,
querySelector querySelector
)) ))
const targetAnchor = (n2.targetAnchor = createText('')) const targetAnchor = (n2.targetAnchor = createText(''))
if (target) { if (target) {
insert(targetAnchor, target) insert(targetAnchor, target)
} else if (__DEV__) { } else if (__DEV__) {
warn('Invalid Portal target on mount:', target, `(${typeof target})`) warn('Invalid Teleport target on mount:', target, `(${typeof target})`)
} }
const mount = (container: RendererElement, anchor: RendererNode) => { const mount = (container: RendererElement, anchor: RendererNode) => {
// Portal *always* has Array children. This is enforced in both the // Teleport *always* has Array children. This is enforced in both the
// compiler and vnode children normalization. // compiler and vnode children normalization.
if (shapeFlag & ShapeFlags.ARRAY_CHILDREN) { if (shapeFlag & ShapeFlags.ARRAY_CHILDREN) {
mountChildren( mountChildren(
@ -123,12 +123,12 @@ export const PortalImpl = {
const mainAnchor = (n2.anchor = n1.anchor)! const mainAnchor = (n2.anchor = n1.anchor)!
const target = (n2.target = n1.target)! const target = (n2.target = n1.target)!
const targetAnchor = (n2.targetAnchor = n1.targetAnchor)! const targetAnchor = (n2.targetAnchor = n1.targetAnchor)!
const wasDisabled = isPortalDisabled(n1.props) const wasDisabled = isTeleportDisabled(n1.props)
const currentContainer = wasDisabled ? container : target const currentContainer = wasDisabled ? container : target
const currentAnchor = wasDisabled ? mainAnchor : targetAnchor const currentAnchor = wasDisabled ? mainAnchor : targetAnchor
if (n2.dynamicChildren) { if (n2.dynamicChildren) {
// fast path when the portal happens to be a block root // fast path when the teleport happens to be a block root
patchBlockChildren( patchBlockChildren(
n1.dynamicChildren!, n1.dynamicChildren!,
n2.dynamicChildren, n2.dynamicChildren,
@ -153,45 +153,45 @@ export const PortalImpl = {
if (!wasDisabled) { if (!wasDisabled) {
// enabled -> disabled // enabled -> disabled
// move into main container // move into main container
movePortal( moveTeleport(
n2, n2,
container, container,
mainAnchor, mainAnchor,
internals, internals,
PortalMoveTypes.TOGGLE TeleportMoveTypes.TOGGLE
) )
} }
} else { } else {
// target changed // target changed
if ((n2.props && n2.props.target) !== (n1.props && n1.props.target)) { if ((n2.props && n2.props.to) !== (n1.props && n1.props.to)) {
const nextTarget = (n2.target = resolveTarget( const nextTarget = (n2.target = resolveTarget(
n2.props as PortalProps, n2.props as TeleportProps,
querySelector querySelector
)) ))
if (nextTarget) { if (nextTarget) {
movePortal( moveTeleport(
n2, n2,
nextTarget, nextTarget,
null, null,
internals, internals,
PortalMoveTypes.TARGET_CHANGE TeleportMoveTypes.TARGET_CHANGE
) )
} else if (__DEV__) { } else if (__DEV__) {
warn( warn(
'Invalid Portal target on update:', 'Invalid Teleport target on update:',
target, target,
`(${typeof target})` `(${typeof target})`
) )
} }
} else if (wasDisabled) { } else if (wasDisabled) {
// disabled -> enabled // disabled -> enabled
// move into portal target // move into teleport target
movePortal( moveTeleport(
n2, n2,
target, target,
targetAnchor, targetAnchor,
internals, internals,
PortalMoveTypes.TOGGLE TeleportMoveTypes.TOGGLE
) )
} }
} }
@ -211,38 +211,38 @@ export const PortalImpl = {
} }
}, },
move: movePortal, move: moveTeleport,
hydrate: hydratePortal hydrate: hydrateTeleport
} }
export const enum PortalMoveTypes { export const enum TeleportMoveTypes {
TARGET_CHANGE, TARGET_CHANGE,
TOGGLE, // enable / disable TOGGLE, // enable / disable
REORDER // moved in the main view REORDER // moved in the main view
} }
function movePortal( function moveTeleport(
vnode: VNode, vnode: VNode,
container: RendererElement, container: RendererElement,
parentAnchor: RendererNode | null, parentAnchor: RendererNode | null,
{ o: { insert }, m: move }: RendererInternals, { o: { insert }, m: move }: RendererInternals,
moveType: PortalMoveTypes = PortalMoveTypes.REORDER moveType: TeleportMoveTypes = TeleportMoveTypes.REORDER
) { ) {
// move target anchor if this is a target change. // move target anchor if this is a target change.
if (moveType === PortalMoveTypes.TARGET_CHANGE) { if (moveType === TeleportMoveTypes.TARGET_CHANGE) {
insert(vnode.targetAnchor!, container, parentAnchor) insert(vnode.targetAnchor!, container, parentAnchor)
} }
const { el, anchor, shapeFlag, children, props } = vnode const { el, anchor, shapeFlag, children, props } = vnode
const isReorder = moveType === PortalMoveTypes.REORDER const isReorder = moveType === TeleportMoveTypes.REORDER
// move main view anchor if this is a re-order. // move main view anchor if this is a re-order.
if (isReorder) { if (isReorder) {
insert(el!, container, parentAnchor) insert(el!, container, parentAnchor)
} }
// if this is a re-order and portal is enabled (content is in target) // if this is a re-order and teleport is enabled (content is in target)
// do not move children. So the opposite is: only move children if this // do not move children. So the opposite is: only move children if this
// is not a reorder, or the portal is disabled // is not a reorder, or the teleport is disabled
if (!isReorder || isPortalDisabled(props)) { if (!isReorder || isTeleportDisabled(props)) {
// Portal has either Array children or no children. // Teleport has either Array children or no children.
if (shapeFlag & ShapeFlags.ARRAY_CHILDREN) { if (shapeFlag & ShapeFlags.ARRAY_CHILDREN) {
for (let i = 0; i < (children as VNode[]).length; i++) { for (let i = 0; i < (children as VNode[]).length; i++) {
move( move(
@ -260,12 +260,12 @@ function movePortal(
} }
} }
interface PortalTargetElement extends Element { interface TeleportTargetElement extends Element {
// last portal target // last teleport target
_lpa?: Node | null _lpa?: Node | null
} }
function hydratePortal( function hydrateTeleport(
node: Node, node: Node,
vnode: VNode, vnode: VNode,
parentComponent: ComponentInternalInstance | null, parentComponent: ComponentInternalInstance | null,
@ -284,15 +284,16 @@ function hydratePortal(
) => Node | null ) => Node | null
): Node | null { ): Node | null {
const target = (vnode.target = resolveTarget<Element>( const target = (vnode.target = resolveTarget<Element>(
vnode.props as PortalProps, vnode.props as TeleportProps,
querySelector querySelector
)) ))
if (target) { if (target) {
// if multiple portals rendered to the same target element, we need to // if multiple teleports rendered to the same target element, we need to
// pick up from where the last portal finished instead of the first node // pick up from where the last teleport finished instead of the first node
const targetNode = (target as PortalTargetElement)._lpa || target.firstChild const targetNode =
(target as TeleportTargetElement)._lpa || target.firstChild
if (vnode.shapeFlag & ShapeFlags.ARRAY_CHILDREN) { if (vnode.shapeFlag & ShapeFlags.ARRAY_CHILDREN) {
if (isPortalDisabled(vnode.props)) { if (isTeleportDisabled(vnode.props)) {
vnode.anchor = hydrateChildren( vnode.anchor = hydrateChildren(
nextSibling(node), nextSibling(node),
vnode, vnode,
@ -313,7 +314,7 @@ function hydratePortal(
optimized optimized
) )
} }
;(target as PortalTargetElement)._lpa = nextSibling( ;(target as TeleportTargetElement)._lpa = nextSibling(
vnode.targetAnchor as Node vnode.targetAnchor as Node
) )
} }
@ -322,7 +323,7 @@ function hydratePortal(
} }
// Force-casted public typing for h and TSX props inference // Force-casted public typing for h and TSX props inference
export const Portal = (PortalImpl as any) as { export const Teleport = (TeleportImpl as any) as {
__isPortal: true __isTeleport: true
new (): { $props: VNodeProps & PortalProps } new (): { $props: VNodeProps & TeleportProps }
} }

View File

@ -6,7 +6,7 @@ import {
Fragment, Fragment,
isVNode isVNode
} from './vnode' } from './vnode'
import { Portal, PortalProps } from './components/Portal' import { Teleport, TeleportProps } from './components/Teleport'
import { Suspense, SuspenseProps } from './components/Suspense' import { Suspense, SuspenseProps } from './components/Suspense'
import { isObject, isArray } from '@vue/shared' import { isObject, isArray } from '@vue/shared'
import { RawSlots } from './componentSlots' import { RawSlots } from './componentSlots'
@ -68,7 +68,7 @@ type RawChildren =
// fake constructor type returned from `defineComponent` // fake constructor type returned from `defineComponent`
interface Constructor<P = any> { interface Constructor<P = any> {
__isFragment?: never __isFragment?: never
__isPortal?: never __isTeleport?: never
__isSuspense?: never __isSuspense?: never
new (): { $props: P } new (): { $props: P }
} }
@ -92,10 +92,10 @@ export function h(
children?: VNodeArrayChildren children?: VNodeArrayChildren
): VNode ): VNode
// portal (target prop is required) // teleport (target prop is required)
export function h( export function h(
type: typeof Portal, type: typeof Teleport,
props: RawProps & PortalProps, props: RawProps & TeleportProps,
children: RawChildren children: RawChildren
): VNode ): VNode

View File

@ -18,7 +18,7 @@ import {
SuspenseBoundary, SuspenseBoundary,
queueEffectWithSuspense queueEffectWithSuspense
} from './components/Suspense' } from './components/Suspense'
import { PortalImpl } from './components/Portal' import { TeleportImpl } from './components/Teleport'
export type RootHydrateFunction = ( export type RootHydrateFunction = (
vnode: VNode<Node, Element>, vnode: VNode<Node, Element>,
@ -172,11 +172,11 @@ export function createHydrationFunctions(
return isFragmentStart return isFragmentStart
? locateClosingAsyncAnchor(node) ? locateClosingAsyncAnchor(node)
: nextSibling(node) : nextSibling(node)
} else if (shapeFlag & ShapeFlags.PORTAL) { } else if (shapeFlag & ShapeFlags.TELEPORT) {
if (domType !== DOMNodeTypes.COMMENT) { if (domType !== DOMNodeTypes.COMMENT) {
return onMismatch() return onMismatch()
} }
return (vnode.type as typeof PortalImpl).hydrate( return (vnode.type as typeof TeleportImpl).hydrate(
node, node,
vnode, vnode,
parentComponent, parentComponent,

View File

@ -53,7 +53,7 @@ export {
} from './vnode' } from './vnode'
// Internal Components // Internal Components
export { Text, Comment, Fragment } from './vnode' export { Text, Comment, Fragment } from './vnode'
export { Portal, PortalProps } from './components/Portal' export { Teleport, TeleportProps } from './components/Teleport'
export { Suspense, SuspenseProps } from './components/Suspense' export { Suspense, SuspenseProps } from './components/Suspense'
export { KeepAlive, KeepAliveProps } from './components/KeepAlive' export { KeepAlive, KeepAliveProps } from './components/KeepAlive'
export { export {

View File

@ -58,7 +58,7 @@ import {
queueEffectWithSuspense, queueEffectWithSuspense,
SuspenseImpl SuspenseImpl
} from './components/Suspense' } from './components/Suspense'
import { PortalImpl } from './components/Portal' import { TeleportImpl } from './components/Teleport'
import { KeepAliveSink, isKeepAlive } from './components/KeepAlive' import { KeepAliveSink, isKeepAlive } from './components/KeepAlive'
import { registerHMR, unregisterHMR } from './hmr' import { registerHMR, unregisterHMR } from './hmr'
import { import {
@ -412,8 +412,8 @@ function baseCreateRenderer(
isSVG, isSVG,
optimized optimized
) )
} else if (shapeFlag & ShapeFlags.PORTAL) { } else if (shapeFlag & ShapeFlags.TELEPORT) {
;(type as typeof PortalImpl).process( ;(type as typeof TeleportImpl).process(
n1, n1,
n2, n2,
container, container,
@ -1207,7 +1207,7 @@ function baseCreateRenderer(
patch( patch(
prevTree, prevTree,
nextTree, nextTree,
// parent may have changed if it's in a portal // parent may have changed if it's in a teleport
hostParentNode(prevTree.el!)!, hostParentNode(prevTree.el!)!,
// anchor may have changed if it's in a fragment // anchor may have changed if it's in a fragment
getNextHostNode(prevTree), getNextHostNode(prevTree),
@ -1653,8 +1653,8 @@ function baseCreateRenderer(
return return
} }
if (shapeFlag & ShapeFlags.PORTAL) { if (shapeFlag & ShapeFlags.TELEPORT) {
;(type as typeof PortalImpl).move(vnode, container, anchor, internals) ;(type as typeof TeleportImpl).move(vnode, container, anchor, internals)
return return
} }
@ -1739,9 +1739,9 @@ function baseCreateRenderer(
unmountChildren(children as VNode[], parentComponent, parentSuspense) unmountChildren(children as VNode[], parentComponent, parentSuspense)
} }
// an unmounted portal should always remove its children // an unmounted teleport should always remove its children
if (shapeFlag & ShapeFlags.PORTAL) { if (shapeFlag & ShapeFlags.TELEPORT) {
;(vnode.type as typeof PortalImpl).remove(vnode, internals) ;(vnode.type as typeof TeleportImpl).remove(vnode, internals)
} }
if (doRemove) { if (doRemove) {

View File

@ -29,7 +29,7 @@ import { DirectiveBinding } from './directives'
import { TransitionHooks } from './components/BaseTransition' import { TransitionHooks } from './components/BaseTransition'
import { warn } from './warning' import { warn } from './warning'
import { currentScopeId } from './helpers/scopeId' import { currentScopeId } from './helpers/scopeId'
import { PortalImpl, isPortal } from './components/Portal' import { TeleportImpl, isTeleport } from './components/Teleport'
import { currentRenderingInstance } from './componentRenderUtils' import { currentRenderingInstance } from './componentRenderUtils'
import { RendererNode, RendererElement } from './renderer' import { RendererNode, RendererElement } from './renderer'
@ -50,7 +50,7 @@ export type VNodeTypes =
| typeof Static | typeof Static
| typeof Comment | typeof Comment
| typeof Fragment | typeof Fragment
| typeof PortalImpl | typeof TeleportImpl
| typeof SuspenseImpl | typeof SuspenseImpl
export type VNodeRef = export type VNodeRef =
@ -113,8 +113,8 @@ export interface VNode<HostNode = RendererNode, HostElement = RendererElement> {
// DOM // DOM
el: HostNode | null el: HostNode | null
anchor: HostNode | null // fragment anchor anchor: HostNode | null // fragment anchor
target: HostElement | null // portal target target: HostElement | null // teleport target
targetAnchor: HostNode | null // portal target anchor targetAnchor: HostNode | null // teleport target anchor
// optimization only // optimization only
shapeFlag: number shapeFlag: number
@ -283,8 +283,8 @@ function _createVNode(
? ShapeFlags.ELEMENT ? ShapeFlags.ELEMENT
: __FEATURE_SUSPENSE__ && isSuspense(type) : __FEATURE_SUSPENSE__ && isSuspense(type)
? ShapeFlags.SUSPENSE ? ShapeFlags.SUSPENSE
: isPortal(type) : isTeleport(type)
? ShapeFlags.PORTAL ? ShapeFlags.TELEPORT
: isObject(type) : isObject(type)
? ShapeFlags.STATEFUL_COMPONENT ? ShapeFlags.STATEFUL_COMPONENT
: isFunction(type) : isFunction(type)
@ -430,7 +430,7 @@ export function normalizeChildren(vnode: VNode, children: unknown) {
} else if (typeof children === 'object') { } else if (typeof children === 'object') {
// Normalize slot to plain children // Normalize slot to plain children
if ( if (
(shapeFlag & ShapeFlags.ELEMENT || shapeFlag & ShapeFlags.PORTAL) && (shapeFlag & ShapeFlags.ELEMENT || shapeFlag & ShapeFlags.TELEPORT) &&
(children as any).default (children as any).default
) { ) {
normalizeChildren(vnode, (children as any).default()) normalizeChildren(vnode, (children as any).default())
@ -446,8 +446,8 @@ export function normalizeChildren(vnode: VNode, children: unknown) {
type = ShapeFlags.SLOTS_CHILDREN type = ShapeFlags.SLOTS_CHILDREN
} else { } else {
children = String(children) children = String(children)
// force portal children to array so it can be moved around // force teleport children to array so it can be moved around
if (shapeFlag & ShapeFlags.PORTAL) { if (shapeFlag & ShapeFlags.TELEPORT) {
type = ShapeFlags.ARRAY_CHILDREN type = ShapeFlags.ARRAY_CHILDREN
children = [createTextVNode(children as string)] children = [createTextVNode(children as string)]
} else { } else {

View File

@ -1,9 +1,9 @@
import { createApp, h, Portal } from 'vue' import { createApp, h, Teleport } from 'vue'
import { renderToString, SSRContext } from '../src/renderToString' import { renderToString, SSRContext } from '../src/renderToString'
import { ssrRenderPortal } from '../src/helpers/ssrRenderPortal' import { ssrRenderTeleport } from '../src/helpers/ssrRenderTeleport'
describe('ssrRenderPortal', () => { describe('ssrRenderTeleport', () => {
test('portal rendering (compiled)', async () => { test('teleport rendering (compiled)', async () => {
const ctx: SSRContext = {} const ctx: SSRContext = {}
const html = await renderToString( const html = await renderToString(
createApp({ createApp({
@ -11,7 +11,7 @@ describe('ssrRenderPortal', () => {
return { msg: 'hello' } return { msg: 'hello' }
}, },
ssrRender(_ctx, _push, _parent) { ssrRender(_ctx, _push, _parent) {
ssrRenderPortal( ssrRenderTeleport(
_push, _push,
_push => { _push => {
_push(`<div>content</div>`) _push(`<div>content</div>`)
@ -24,11 +24,11 @@ describe('ssrRenderPortal', () => {
}), }),
ctx ctx
) )
expect(html).toBe('<!--portal start--><!--portal end-->') expect(html).toBe('<!--teleport start--><!--teleport end-->')
expect(ctx.portals!['#target']).toBe(`<div>content</div><!---->`) expect(ctx.teleports!['#target']).toBe(`<div>content</div><!---->`)
}) })
test('portal rendering (compiled + disabled)', async () => { test('teleport rendering (compiled + disabled)', async () => {
const ctx: SSRContext = {} const ctx: SSRContext = {}
const html = await renderToString( const html = await renderToString(
createApp({ createApp({
@ -36,7 +36,7 @@ describe('ssrRenderPortal', () => {
return { msg: 'hello' } return { msg: 'hello' }
}, },
ssrRender(_ctx, _push, _parent) { ssrRender(_ctx, _push, _parent) {
ssrRenderPortal( ssrRenderTeleport(
_push, _push,
_push => { _push => {
_push(`<div>content</div>`) _push(`<div>content</div>`)
@ -49,62 +49,66 @@ describe('ssrRenderPortal', () => {
}), }),
ctx ctx
) )
expect(html).toBe('<!--portal start--><div>content</div><!--portal end-->') expect(html).toBe(
expect(ctx.portals!['#target']).toBe(`<!---->`) '<!--teleport start--><div>content</div><!--teleport end-->'
)
expect(ctx.teleports!['#target']).toBe(`<!---->`)
}) })
test('portal rendering (vnode)', async () => { test('teleport rendering (vnode)', async () => {
const ctx: SSRContext = {} const ctx: SSRContext = {}
const html = await renderToString( const html = await renderToString(
h( h(
Portal, Teleport,
{ {
target: `#target` to: `#target`
}, },
h('span', 'hello') h('span', 'hello')
), ),
ctx ctx
) )
expect(html).toBe('<!--portal start--><!--portal end-->') expect(html).toBe('<!--teleport start--><!--teleport end-->')
expect(ctx.portals!['#target']).toBe('<span>hello</span><!---->') expect(ctx.teleports!['#target']).toBe('<span>hello</span><!---->')
}) })
test('portal rendering (vnode + disabled)', async () => { test('teleport rendering (vnode + disabled)', async () => {
const ctx: SSRContext = {} const ctx: SSRContext = {}
const html = await renderToString( const html = await renderToString(
h( h(
Portal, Teleport,
{ {
target: `#target`, to: `#target`,
disabled: true disabled: true
}, },
h('span', 'hello') h('span', 'hello')
), ),
ctx ctx
) )
expect(html).toBe('<!--portal start--><span>hello</span><!--portal end-->') expect(html).toBe(
expect(ctx.portals!['#target']).toBe(`<!---->`) '<!--teleport start--><span>hello</span><!--teleport end-->'
)
expect(ctx.teleports!['#target']).toBe(`<!---->`)
}) })
test('multiple portals with same target', async () => { test('multiple teleports with same target', async () => {
const ctx: SSRContext = {} const ctx: SSRContext = {}
const html = await renderToString( const html = await renderToString(
h('div', [ h('div', [
h( h(
Portal, Teleport,
{ {
target: `#target` to: `#target`
}, },
h('span', 'hello') h('span', 'hello')
), ),
h(Portal, { target: `#target` }, 'world') h(Teleport, { to: `#target` }, 'world')
]), ]),
ctx ctx
) )
expect(html).toBe( expect(html).toBe(
'<div><!--portal start--><!--portal end--><!--portal start--><!--portal end--></div>' '<div><!--teleport start--><!--teleport end--><!--teleport start--><!--teleport end--></div>'
) )
expect(ctx.portals!['#target']).toBe( expect(ctx.teleports!['#target']).toBe(
'<span>hello</span><!---->world<!---->' '<span>hello</span><!---->world<!---->'
) )
}) })

View File

@ -6,37 +6,37 @@ import {
SSRBufferItem SSRBufferItem
} from '../renderToString' } from '../renderToString'
export function ssrRenderPortal( export function ssrRenderTeleport(
parentPush: PushFn, parentPush: PushFn,
contentRenderFn: (push: PushFn) => void, contentRenderFn: (push: PushFn) => void,
target: string, target: string,
disabled: boolean, disabled: boolean,
parentComponent: ComponentInternalInstance parentComponent: ComponentInternalInstance
) { ) {
parentPush('<!--portal start-->') parentPush('<!--teleport start-->')
let portalContent: SSRBufferItem let teleportContent: SSRBufferItem
if (disabled) { if (disabled) {
contentRenderFn(parentPush) contentRenderFn(parentPush)
portalContent = `<!---->` teleportContent = `<!---->`
} else { } else {
const { getBuffer, push } = createBuffer() const { getBuffer, push } = createBuffer()
contentRenderFn(push) contentRenderFn(push)
push(`<!---->`) // portal end anchor push(`<!---->`) // teleport end anchor
portalContent = getBuffer() teleportContent = getBuffer()
} }
const context = parentComponent.appContext.provides[ const context = parentComponent.appContext.provides[
ssrContextKey as any ssrContextKey as any
] as SSRContext ] as SSRContext
const portalBuffers = const teleportBuffers =
context.__portalBuffers || (context.__portalBuffers = {}) context.__teleportBuffers || (context.__teleportBuffers = {})
if (portalBuffers[target]) { if (teleportBuffers[target]) {
portalBuffers[target].push(portalContent) teleportBuffers[target].push(teleportContent)
} else { } else {
portalBuffers[target] = [portalContent] teleportBuffers[target] = [teleportContent]
} }
parentPush('<!--portal end-->') parentPush('<!--teleport end-->')
} }

View File

@ -13,7 +13,7 @@ export {
} from './helpers/ssrRenderAttrs' } from './helpers/ssrRenderAttrs'
export { ssrInterpolate } from './helpers/ssrInterpolate' export { ssrInterpolate } from './helpers/ssrInterpolate'
export { ssrRenderList } from './helpers/ssrRenderList' export { ssrRenderList } from './helpers/ssrRenderList'
export { ssrRenderPortal } from './helpers/ssrRenderPortal' export { ssrRenderTeleport } from './helpers/ssrRenderTeleport'
export { ssrRenderSuspense } from './helpers/ssrRenderSuspense' export { ssrRenderSuspense } from './helpers/ssrRenderSuspense'
// v-model helpers // v-model helpers

View File

@ -32,7 +32,7 @@ import { compile } from '@vue/compiler-ssr'
import { ssrRenderAttrs } from './helpers/ssrRenderAttrs' import { ssrRenderAttrs } from './helpers/ssrRenderAttrs'
import { SSRSlots } from './helpers/ssrRenderSlot' import { SSRSlots } from './helpers/ssrRenderSlot'
import { CompilerError } from '@vue/compiler-dom' import { CompilerError } from '@vue/compiler-dom'
import { ssrRenderPortal } from './helpers/ssrRenderPortal' import { ssrRenderTeleport } from './helpers/ssrRenderTeleport'
const { const {
isVNode, isVNode,
@ -63,8 +63,8 @@ export type Props = Record<string, unknown>
export type SSRContext = { export type SSRContext = {
[key: string]: any [key: string]: any
portals?: Record<string, string> teleports?: Record<string, string>
__portalBuffers?: Record<string, SSRBuffer> __teleportBuffers?: Record<string, SSRBuffer>
} }
export function createBuffer() { export function createBuffer() {
@ -123,7 +123,7 @@ export async function renderToString(
input.provide(ssrContextKey, context) input.provide(ssrContextKey, context)
const buffer = await renderComponentVNode(vnode) const buffer = await renderComponentVNode(vnode)
await resolvePortals(context) await resolveTeleports(context)
return unrollBuffer(buffer) return unrollBuffer(buffer)
} }
@ -256,8 +256,8 @@ function renderVNode(
renderElementVNode(push, vnode, parentComponent) renderElementVNode(push, vnode, parentComponent)
} else if (shapeFlag & ShapeFlags.COMPONENT) { } else if (shapeFlag & ShapeFlags.COMPONENT) {
push(renderComponentVNode(vnode, parentComponent)) push(renderComponentVNode(vnode, parentComponent))
} else if (shapeFlag & ShapeFlags.PORTAL) { } else if (shapeFlag & ShapeFlags.TELEPORT) {
renderPortalVNode(push, vnode, parentComponent) renderTeleportVNode(push, vnode, parentComponent)
} else if (shapeFlag & ShapeFlags.SUSPENSE) { } else if (shapeFlag & ShapeFlags.SUSPENSE) {
renderVNode( renderVNode(
push, push,
@ -360,24 +360,24 @@ function applySSRDirectives(
return mergeProps(rawProps || {}, ...toMerge) return mergeProps(rawProps || {}, ...toMerge)
} }
function renderPortalVNode( function renderTeleportVNode(
push: PushFn, push: PushFn,
vnode: VNode, vnode: VNode,
parentComponent: ComponentInternalInstance parentComponent: ComponentInternalInstance
) { ) {
const target = vnode.props && vnode.props.target const target = vnode.props && vnode.props.to
const disabled = vnode.props && vnode.props.disabled const disabled = vnode.props && vnode.props.disabled
if (!target) { if (!target) {
warn(`[@vue/server-renderer] Portal is missing target prop.`) warn(`[@vue/server-renderer] Teleport is missing target prop.`)
return [] return []
} }
if (!isString(target)) { if (!isString(target)) {
warn( warn(
`[@vue/server-renderer] Portal target must be a query selector string.` `[@vue/server-renderer] Teleport target must be a query selector string.`
) )
return [] return []
} }
ssrRenderPortal( ssrRenderTeleport(
push, push,
push => { push => {
renderVNodeChildren( renderVNodeChildren(
@ -392,14 +392,14 @@ function renderPortalVNode(
) )
} }
async function resolvePortals(context: SSRContext) { async function resolveTeleports(context: SSRContext) {
if (context.__portalBuffers) { if (context.__teleportBuffers) {
context.portals = context.portals || {} context.teleports = context.teleports || {}
for (const key in context.__portalBuffers) { for (const key in context.__teleportBuffers) {
// note: it's OK to await sequentially here because the Promises were // note: it's OK to await sequentially here because the Promises were
// created eagerly in parallel. // created eagerly in parallel.
context.portals[key] = unrollBuffer( context.teleports[key] = unrollBuffer(
await Promise.all(context.__portalBuffers[key]) await Promise.all(context.__teleportBuffers[key])
) )
} }
} }

View File

@ -5,7 +5,7 @@ export const enum ShapeFlags {
TEXT_CHILDREN = 1 << 3, TEXT_CHILDREN = 1 << 3,
ARRAY_CHILDREN = 1 << 4, ARRAY_CHILDREN = 1 << 4,
SLOTS_CHILDREN = 1 << 5, SLOTS_CHILDREN = 1 << 5,
PORTAL = 1 << 6, TELEPORT = 1 << 6,
SUSPENSE = 1 << 7, SUSPENSE = 1 << 7,
COMPONENT_SHOULD_KEEP_ALIVE = 1 << 8, COMPONENT_SHOULD_KEEP_ALIVE = 1 << 8,
COMPONENT_KEPT_ALIVE = 1 << 9, COMPONENT_KEPT_ALIVE = 1 << 9,

View File

@ -45,14 +45,14 @@ const Modal = {
<!-- app --> <!-- app -->
<div id="app"> <div id="app">
<button id="show-modal" @click="showModal = true">Show Modal</button> <button id="show-modal" @click="showModal = true">Show Modal</button>
<portal target="#modal-container"> <teleport to="#modal-container">
<!-- use the modal component, pass in the prop --> <!-- use the modal component, pass in the prop -->
<modal :show="showModal" @close="showModal = false"> <modal :show="showModal" @close="showModal = false">
<template #header> <template #header>
<h3>custom header</h3> <h3>custom header</h3>
</template> </template>
</modal> </modal>
</portal> </teleport>
</div> </div>
<script> <script>