All files / runtime-core/src/components Teleport.ts

96.41% Statements 188/195
90.9% Branches 170/187
100% Functions 19/19
96.85% Lines 185/191

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590                                                    94x   94x   8994x   94x 573x   94x 114x   94x 188x   94x 186x   94x       151x 151x 60x               60x 60x               60x     91x 4x   91x       94x                                       214x   214x 214x       214x 2x 2x     214x             106x 106x                         214x 108x 108x 108x 108x   99x 2x 97x         99x 7x           99x 79x 79x   9x 2x       214x 54x 37x 37x 37x       11x 11x 11x   37x   54x 54x     214x   114x     114x     114x 114x   114x       43x 43x     71x 16x 16x     71x     100x 100x       100x 100x 11x 11x 11x 11x   89x 89x 89x 89x 89x 100x   100x   89x       89x   19x                         19x 70x 70x                         89x 23x     7x                     16x 4x         66x 17x 17x 15x 15x             2x 2x           49x     7x                 89x                                     77x 77x 77x       77x 77x 6x 6x     77x 65x 65x       77x   77x         69x 73x 73x                             94x 94x 94x 94x                     40x   15x 15x   15x       15x   40x 40x   40x 11x           40x   37x 37x 45x                   40x 11x                                                                       25x 25x 65x 45x 20x 25x 20x 20x   20x     45x         8x                     26x       26x 26x       25x 25x 25x     7x 7x 7x 2x                     18x 18x         18x 3x     18x                     25x 1x 1x 1x 1x 1x     26x       94x                       220x 220x 41x 16x   25x                       113x 113x       113x   113x 104x 104x     113x    
import type { ComponentInternalInstance } from '../component'
import type { SuspenseBoundary } from './Suspense'
import {
  type ElementNamespace,
  MoveType,
  type RendererElement,
  type RendererInternals,
  type RendererNode,
  type RendererOptions,
  queuePostRenderEffect,
  traverseStaticChildren,
} from '../renderer'
import type { VNode, VNodeArrayChildren, VNodeProps } from '../vnode'
import { ShapeFlags, isString } from '@vue/shared'
import { warn } from '../warning'
import { isHmrUpdating } from '../hmr'
import { type SchedulerJob, SchedulerJobFlags } from '../scheduler'
 
export type TeleportVNode = VNode<RendererNode, RendererElement, TeleportProps>
 
export interface TeleportProps {
  to: string | RendererElement | null | undefined
  disabled?: boolean
  defer?: boolean
}
 
const pendingMounts = new WeakMap<VNode, SchedulerJob>()
 
export const TeleportEndKey: unique symbol = Symbol('_vte')
 
export const isTeleport = (type: any): boolean => type.__isTeleport
 
const isTeleportDisabled = (props: VNode['props']): boolean =>
  props && (props.disabled || props.disabled === '')
 
const isTeleportDeferred = (props: VNode['props']): boolean =>
  props && (props.defer || props.defer === '')
 
const isTargetSVG = (target: RendererElement): boolean =>
  typeof SVGElement !== 'undefined' && target instanceof SVGElement
 
const isTargetMathML = (target: RendererElement): boolean =>
  typeof MathMLElement === 'function' && target instanceof MathMLElement
 
const resolveTarget = <T = RendererElement>(
  props: TeleportProps | null,
  select: RendererOptions['querySelector'],
): T | null => {
  const targetSelector = props && props.to
  if (isString(targetSelector)) {
    Iif (!select) {
      __DEV__ &&
        warn(
          `Current renderer does not support string target for Teleports. ` +
            `(missing querySelector renderer option)`,
        )
      return null
    } else {
      const target = select(targetSelector)
      Iif (__DEV__ && !target && !isTeleportDisabled(props)) {
        warn(
          `Failed to locate Teleport target with selector "${targetSelector}". ` +
            `Note the target element must exist before the component is mounted - ` +
            `i.e. the target cannot be rendered by the component itself, and ` +
            `ideally should be outside of the entire Vue component tree.`,
        )
      }
      return target as T
    }
  } else {
    if (__DEV__ && !targetSelector && !isTeleportDisabled(props)) {
      warn(`Invalid Teleport target: ${targetSelector}`)
    }
    return targetSelector as T
  }
}
 
export const TeleportImpl = {
  name: 'Teleport',
  __isTeleport: true,
  process(
    n1: TeleportVNode | null,
    n2: TeleportVNode,
    container: RendererElement,
    anchor: RendererNode | null,
    parentComponent: ComponentInternalInstance | null,
    parentSuspense: SuspenseBoundary | null,
    namespace: ElementNamespace,
    slotScopeIds: string[] | null,
    optimized: boolean,
    internals: RendererInternals,
  ): void {
    const {
      mc: mountChildren,
      pc: patchChildren,
      pbc: patchBlockChildren,
      o: { insert, querySelector, createText, createComment, parentNode },
    } = internals
 
    const disabled = isTeleportDisabled(n2.props)
    let { dynamicChildren } = n2
 
    // #3302
    // HMR updated, force full diff
    if (__DEV__ && isHmrUpdating) {
      optimized = false
      dynamicChildren = null
    }
 
    const mount = (
      vnode: TeleportVNode,
      container: RendererElement,
      anchor: RendererNode,
    ) => {
      // Teleport *always* has Array children. This is enforced in both the
      // compiler and vnode children normalization.
      Eif (vnode.shapeFlag & ShapeFlags.ARRAY_CHILDREN) {
        mountChildren(
          vnode.children as VNodeArrayChildren,
          container,
          anchor,
          parentComponent,
          parentSuspense,
          namespace,
          slotScopeIds,
          optimized,
        )
      }
    }
 
    const mountToTarget = (vnode: TeleportVNode = n2) => {
      const disabled = isTeleportDisabled(vnode.props)
      const target = (vnode.target = resolveTarget(vnode.props, querySelector))
      const targetAnchor = prepareAnchor(target, vnode, createText, insert)
      if (target) {
        // #2652 we could be teleporting from a non-SVG tree into an SVG tree
        if (namespace !== 'svg' && isTargetSVG(target)) {
          namespace = 'svg'
        } else Iif (namespace !== 'mathml' && isTargetMathML(target)) {
          namespace = 'mathml'
        }
 
        // track CE teleport targets
        if (parentComponent && parentComponent.isCE) {
          ;(
            parentComponent.ce!._teleportTargets ||
            (parentComponent.ce!._teleportTargets = new Set())
          ).add(target)
        }
 
        if (!disabled) {
          mount(vnode, target, targetAnchor)
          updateCssVars(vnode, false)
        }
      } else if (__DEV__ && !disabled) {
        warn('Invalid Teleport target on mount:', target, `(${typeof target})`)
      }
    }
 
    const queuePendingMount = (vnode: TeleportVNode) => {
      const mountJob: SchedulerJob = () => {
        Iif (pendingMounts.get(vnode) !== mountJob) return
        pendingMounts.delete(vnode)
        if (isTeleportDisabled(vnode.props)) {
          // Use the current parent of the placeholder instead of the
          // captured `container`, which may be stale if Suspense has moved
          // the branch to a different container during resolve.
          const mountContainer = parentNode(vnode.el!) || container
          mount(vnode, mountContainer, vnode.anchor!)
          updateCssVars(vnode, true)
        }
        mountToTarget(vnode)
      }
      pendingMounts.set(vnode, mountJob)
      queuePostRenderEffect(mountJob, parentSuspense)
    }
 
    if (n1 == null) {
      // insert anchors in the main view
      const placeholder = (n2.el = __DEV__
        ? createComment('teleport start')
        : createText(''))
      const mainAnchor = (n2.anchor = __DEV__
        ? createComment('teleport end')
        : createText(''))
      insert(placeholder, container, anchor)
      insert(mainAnchor, container, anchor)
 
      if (
        isTeleportDeferred(n2.props) ||
        (__FEATURE_SUSPENSE__ && parentSuspense && parentSuspense.pendingBranch)
      ) {
        queuePendingMount(n2)
        return
      }
 
      if (disabled) {
        mount(n2, container, mainAnchor)
        updateCssVars(n2, true)
      }
 
      mountToTarget()
    } else {
      // update content
      n2.el = n1.el
      const mainAnchor = (n2.anchor = n1.anchor)!
      // Target mounting may still be pending because of deferred teleport or a
      // parent suspense buffering post-render effects. In that case, replace
      // the pending mount so the latest vnode goes through the mount flow.
      const pendingMount = pendingMounts.get(n1)
      if (pendingMount) {
        pendingMount.flags! |= SchedulerJobFlags.DISPOSED
        pendingMounts.delete(n1)
        queuePendingMount(n2)
        return
      }
      n2.targetStart = n1.targetStart
      const target = (n2.target = n1.target)!
      const targetAnchor = (n2.targetAnchor = n1.targetAnchor)!
      const wasDisabled = isTeleportDisabled(n1.props)
      const currentContainer = wasDisabled ? container : target
      const currentAnchor = wasDisabled ? mainAnchor : targetAnchor
 
      Iif (namespace === 'svg' || isTargetSVG(target)) {
        namespace = 'svg'
      } else Iif (namespace === 'mathml' || isTargetMathML(target)) {
        namespace = 'mathml'
      }
 
      if (dynamicChildren) {
        // fast path when the teleport happens to be a block root
        patchBlockChildren(
          n1.dynamicChildren!,
          dynamicChildren,
          currentContainer,
          parentComponent,
          parentSuspense,
          namespace,
          slotScopeIds,
        )
        // even in block tree mode we need to make sure all root-level nodes
        // in the teleport inherit previous DOM references so that they can
        // be moved in future patches.
        // in dev mode, deep traversal is necessary for HMR
        traverseStaticChildren(n1, n2, !__DEV__)
      } else Eif (!optimized) {
        patchChildren(
          n1,
          n2,
          currentContainer,
          currentAnchor,
          parentComponent,
          parentSuspense,
          namespace,
          slotScopeIds,
          false,
        )
      }
 
      if (disabled) {
        if (!wasDisabled) {
          // enabled -> disabled
          // move into main container
          moveTeleport(
            n2,
            container,
            mainAnchor,
            internals,
            TeleportMoveTypes.TOGGLE,
          )
        } else {
          // #7835
          // When `teleport` is disabled, `to` may change, making it always old,
          // to ensure the correct `to` when enabled
          if (n2.props && n1.props && n2.props.to !== n1.props.to) {
            n2.props.to = n1.props.to
          }
        }
      } else {
        // target changed
        if ((n2.props && n2.props.to) !== (n1.props && n1.props.to)) {
          const nextTarget = resolveTarget(n2.props, querySelector)
          if (nextTarget) {
            n2.target = nextTarget
            moveTeleport(
              n2,
              nextTarget,
              null,
              internals,
              TeleportMoveTypes.TARGET_CHANGE,
            )
          } else Eif (__DEV__) {
            warn(
              'Invalid Teleport target on update:',
              target,
              `(${typeof target})`,
            )
          }
        } else if (wasDisabled) {
          // disabled -> enabled
          // move into teleport target
          moveTeleport(
            n2,
            target,
            targetAnchor,
            internals,
            TeleportMoveTypes.TOGGLE,
          )
        }
      }
      updateCssVars(n2, disabled)
    }
  },
 
  remove(
    vnode: VNode,
    parentComponent: ComponentInternalInstance | null,
    parentSuspense: SuspenseBoundary | null,
    { um: unmount, o: { remove: hostRemove } }: RendererInternals,
    doRemove: boolean,
  ): void {
    const {
      shapeFlag,
      children,
      anchor,
      targetStart,
      targetAnchor,
      target,
      props,
    } = vnode
    const disabled = isTeleportDisabled(props)
    const shouldRemove = doRemove || !disabled
    // A deferred teleport inside a pending suspense may be unmounted before its
    // content is ever mounted. Clear the queued mount effect; the children
    // loop below is skipped because nothing has been mounted yet.
    const pendingMount = pendingMounts.get(vnode)
    if (pendingMount) {
      pendingMount.flags! |= SchedulerJobFlags.DISPOSED
      pendingMounts.delete(vnode)
    }
 
    if (target) {
      hostRemove(targetStart!)
      hostRemove(targetAnchor!)
    }
 
    // an unmounted teleport should always unmount its children whether it's disabled or not
    doRemove && hostRemove(anchor!)
    // #14876 don't unmount children if nothing was mounted
    if (
      !pendingMount &&
      (disabled || target) &&
      shapeFlag & ShapeFlags.ARRAY_CHILDREN
    ) {
      for (let i = 0; i < (children as VNode[]).length; i++) {
        const child = (children as VNode[])[i]
        unmount(
          child,
          parentComponent,
          parentSuspense,
          shouldRemove,
          !!child.dynamicChildren,
        )
      }
    }
  },
 
  move: moveTeleport as typeof moveTeleport,
  hydrate: hydrateTeleport as typeof hydrateTeleport,
}
 
export enum TeleportMoveTypes {
  TARGET_CHANGE,
  TOGGLE, // enable / disable
  REORDER, // moved in the main view
}
 
function moveTeleport(
  vnode: VNode,
  container: RendererElement,
  parentAnchor: RendererNode | null,
  { o: { insert }, m: move }: RendererInternals,
  moveType: TeleportMoveTypes = TeleportMoveTypes.REORDER,
): void {
  // move target anchors if this is a target change.
  if (moveType === TeleportMoveTypes.TARGET_CHANGE) {
    // targetStart is only set by hydration when the start anchor is found
    Eif (vnode.targetStart) {
      insert(vnode.targetStart, container, parentAnchor)
    }
    insert(vnode.targetAnchor!, container, parentAnchor)
    // children have to stay between the two anchors, otherwise subsequently
    // appended children are mounted before targetAnchor while the moved ones
    // sit after it
    parentAnchor = vnode.targetAnchor!
  }
  const { el, anchor, shapeFlag, children, props } = vnode
  const isReorder = moveType === TeleportMoveTypes.REORDER
  // move main view anchor if this is a re-order.
  if (isReorder) {
    insert(el!, container, parentAnchor)
  }
  // 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
  // is not a reorder, or the teleport is disabled
  // #14701 don't move children if in pending mount
  if (!pendingMounts.has(vnode) && (!isReorder || isTeleportDisabled(props))) {
    // Teleport has either Array children or no children.
    Eif (shapeFlag & ShapeFlags.ARRAY_CHILDREN) {
      for (let i = 0; i < (children as VNode[]).length; i++) {
        move(
          (children as VNode[])[i],
          container,
          parentAnchor,
          MoveType.REORDER,
        )
      }
    }
  }
  // move main view anchor if this is a re-order.
  if (isReorder) {
    insert(anchor!, container, parentAnchor)
  }
}
 
interface TeleportTargetElement extends Element {
  // last teleport target
  _lpa?: Node | null
}
 
function hydrateTeleport(
  node: Node,
  vnode: TeleportVNode,
  parentComponent: ComponentInternalInstance | null,
  parentSuspense: SuspenseBoundary | null,
  slotScopeIds: string[] | null,
  optimized: boolean,
  {
    o: { nextSibling, parentNode, querySelector, insert, createText },
  }: RendererInternals<Node, Element>,
  hydrateChildren: (
    node: Node | null,
    vnode: VNode,
    container: Element,
    parentComponent: ComponentInternalInstance | null,
    parentSuspense: SuspenseBoundary | null,
    slotScopeIds: string[] | null,
    optimized: boolean,
  ) => Node | null,
): Node | null {
  // lookahead until we find the target anchor
  // we cannot rely on return value of hydrateChildren() because there
  // could be nested teleports
  function hydrateAnchor(
    target: TeleportTargetElement,
    targetNode: Node | null,
  ) {
    let targetAnchor = targetNode
    while (targetAnchor) {
      if (targetAnchor && targetAnchor.nodeType === 8) {
        if ((targetAnchor as Comment).data === 'teleport start anchor') {
          vnode.targetStart = targetAnchor
        } else if ((targetAnchor as Comment).data === 'teleport anchor') {
          vnode.targetAnchor = targetAnchor
          target._lpa =
            vnode.targetAnchor && nextSibling(vnode.targetAnchor as Node)
          break
        }
      }
      targetAnchor = nextSibling(targetAnchor)
    }
  }
 
  function hydrateDisabledTeleport(node: Node, vnode: VNode) {
    vnode.anchor = hydrateChildren(
      nextSibling(node),
      vnode,
      parentNode(node)!,
      parentComponent,
      parentSuspense,
      slotScopeIds,
      optimized,
    )
  }
 
  const target = (vnode.target = resolveTarget<Element>(
    vnode.props,
    querySelector,
  ))
  const disabled = isTeleportDisabled(vnode.props)
  if (target) {
    // if multiple teleports rendered to the same target element, we need to
    // pick up from where the last teleport finished instead of the first node
    const targetNode =
      (target as TeleportTargetElement)._lpa || target.firstChild
    Eif (vnode.shapeFlag & ShapeFlags.ARRAY_CHILDREN) {
      if (disabled) {
        // claim this teleport's target anchors before hydrating children, as
        // SSR renders them before any nested teleport's block in the target
        hydrateAnchor(target as TeleportTargetElement, targetNode)
        hydrateDisabledTeleport(node, vnode)
        if (!vnode.targetAnchor) {
          prepareAnchor(
            target,
            vnode,
            createText,
            insert,
            // if target is the same as the main view, insert anchors before current node
            // to avoid hydrating mismatch
            parentNode(node)! === target ? node : null,
          )
        }
      } else {
        vnode.anchor = nextSibling(node)
        hydrateAnchor(target as TeleportTargetElement, targetNode)
        // #11400 if the HTML corresponding to Teleport is not embedded in the
        // correct position on the final page during SSR. the targetAnchor will
        // always be null, we need to manually add targetAnchor to ensure
        // Teleport it can properly unmount or move
        if (!vnode.targetAnchor) {
          prepareAnchor(target, vnode, createText, insert)
        }
 
        hydrateChildren(
          targetNode && nextSibling(targetNode),
          vnode,
          target,
          parentComponent,
          parentSuspense,
          slotScopeIds,
          optimized,
        )
      }
    }
    updateCssVars(vnode, disabled)
  } else Eif (disabled) {
    Eif (vnode.shapeFlag & ShapeFlags.ARRAY_CHILDREN) {
      hydrateDisabledTeleport(node, vnode)
      vnode.targetStart = node
      vnode.targetAnchor = nextSibling(node)
    }
  }
  return vnode.anchor && nextSibling(vnode.anchor as Node)
}
 
// Force-casted public typing for h and TSX props inference
export const Teleport = TeleportImpl as unknown as {
  __isTeleport: true
  new (): {
    $props: VNodeProps & TeleportProps
    $slots: {
      default(): VNode[]
    }
  }
}
 
function updateCssVars(vnode: VNode, isDisabled: boolean) {
  // presence of .ut method indicates owner component uses css vars.
  const ctx = vnode.ctx
  if (ctx && ctx.ut) {
    if (isDisabled) {
      ctx.ut(vnode.el, vnode.anchor)
    } else {
      ctx.ut(vnode.targetStart, vnode.targetAnchor)
    }
  }
}
 
function prepareAnchor(
  target: RendererElement | null,
  vnode: TeleportVNode,
  createText: RendererOptions['createText'],
  insert: RendererOptions['insert'],
  anchor: RendererNode | null = null,
) {
  const targetStart = (vnode.targetStart = createText(''))
  const targetAnchor = (vnode.targetAnchor = createText(''))
 
  // attach a special property, so we can skip teleported content in
  // renderer's nextSibling search
  targetStart[TeleportEndKey] = targetAnchor
 
  if (target) {
    insert(targetStart, target, anchor)
    insert(targetAnchor, target, anchor)
  }
 
  return targetAnchor
}