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 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 | 94x 94x 94x 94x 94x 94x 31x 31x 94x 344x 94x 344x 94x 344x 344x 344x 344x 94x 999x 5x 5x 173x 173x 173x 173x 5x 618x 618x 618x 17x 618x 618x 618x 618x 594x 594x 618x 4x 4x 618x 618x 14x 1x 1x 1x 13x 1x 1x 1x 13x 14x 10x 2x 2x 8x 5x 3x 10x 5x 1x 1x 5x 5x 5x 5x 10x 6x 10x 5x 10x 5x 21x 21x 21x 568x 237x 12x 225x 331x 279x 279x 279x 26x 253x 9x 244x 279x 279x 34x 5x 5x 29x 34x 34x 52x 14x 14x 38x 38x 613x 2x 613x 5x 225x 225x 225x 225x 225x 225x 9x 225x 225x 6x 6x 6x 5x 5x 5x 6x 6x 225x 65x 65x 3x 3x 65x 8x 8x 8x 160x 80x 80x 2x 80x 80x 4x 2x 2x 4x 225x 105x 104x 104x 104x 125x 9x 125x 38x 1x 37x 1x 1x 1x 225x 225x 9x 225x 13x 13x 13x 13x 225x 5x 100x 100x 100x 100x 100x 162x 162x 162x 150x 12x 5x 5x 150x 12x 2x 10x 6x 6x 5x 5x 10x 100x 5x 21x 21x 21x 21x 21x 17x 4x 4x 4x 5x 17x 7x 7x 17x 17x 2x 2x 8x 8x 6x 2x 17x 17x 17x 17x 17x 17x 17x 17x 5x 37x 37x 98x 98x 55x 55x 39x 37x 2x 5x 8x 8x 8x 8x 8x 24x 24x 24x 5x 253x 5x 94x 38x 36x 2x 112x 24x 1x 1x 23x 24x 24x 2x 2x 88x 14x 14x 14x 14x 14x 3x 3x 3x 14x 14x 14x 4x 4x 74x 38x 12x 12x 26x 5x 5x 21x 4x 4x 17x 11x 6x 3x 3x 17x 38x 9x 9x 112x 9x 18x 9x 9x 9x 9x 9x 103x 24x 3x 21x 13x 8x 48x 24x 2x 22x 27x 22x 28x 28x 56x 56x 56x 56x 34x 28x 14x 2x 12x 18x 2x 10x 16x 16x 3x 3x 3x 3x 16x 2x 94x 94x 47x 32x 41x 47x 54x 32x 22x 4x 18x 18x 1x 17x 17x 10x 8x 8x | import {
Fragment,
Static,
Text,
Comment as VComment,
type VNode,
type VNodeHook,
createTextVNode,
createVNode,
invokeVNodeHook,
normalizeVNode,
} from './vnode'
import { flushPostFlushCbs } from './scheduler'
import type { ComponentInternalInstance } from './component'
import { invokeDirectiveHook } from './directives'
import { warn } from './warning'
import {
PatchFlags,
ShapeFlags,
def,
getEscapedCssVarName,
includeBooleanAttr,
isBooleanAttr,
isKnownHtmlAttr,
isKnownSvgAttr,
isOn,
isRenderableAttrValue,
isReservedProp,
isString,
normalizeClass,
normalizeCssVarValue,
normalizeStyle,
stringifyStyle,
} from '@vue/shared'
import { type RendererInternals, needTransition } from './renderer'
import { setRef } from './rendererTemplateRef'
import {
type SuspenseBoundary,
type SuspenseImpl,
queueEffectWithSuspense,
} from './components/Suspense'
import type { TeleportImpl, TeleportVNode } from './components/Teleport'
import { isAsyncWrapper } from './apiAsyncComponent'
import { isReactive } from '@vue/reactivity'
import { updateHOCHostEl } from './componentRenderUtils'
export type RootHydrateFunction = (
vnode: VNode<Node, Element>,
container: (Element | ShadowRoot) & { _vnode?: VNode },
) => void
export enum DOMNodeTypes {
ELEMENT = 1,
TEXT = 3,
COMMENT = 8,
}
let hasLoggedMismatchError = false
const logMismatchError = () => {
Eif (__TEST__ || hasLoggedMismatchError) {
return
}
// this error should show up in production
console.error('Hydration completed but contains mismatches.')
hasLoggedMismatchError = true
}
const isSVGContainer = (container: Element) =>
container.namespaceURI!.includes('svg') &&
container.tagName !== 'foreignObject'
const isMathMLContainer = (container: Element) =>
container.namespaceURI!.includes('MathML')
const getContainerType = (
container: Element | ShadowRoot,
): 'svg' | 'mathml' | undefined => {
Iif (container.nodeType !== DOMNodeTypes.ELEMENT) return undefined
Iif (isSVGContainer(container as Element)) return 'svg'
Iif (isMathMLContainer(container as Element)) return 'mathml'
return undefined
}
export const isComment = (node: Node): node is Comment =>
node.nodeType === DOMNodeTypes.COMMENT
// Note: hydration is DOM-specific
// But we have to place it in core due to tight coupling with core - splitting
// it out creates a ton of unnecessary complexity.
// Hydration also depends on some renderer internal logic which needs to be
// passed in via arguments.
export function createHydrationFunctions(
rendererInternals: RendererInternals<Node, Element>,
): [
RootHydrateFunction,
(
node: Node,
vnode: VNode,
parentComponent: ComponentInternalInstance | null,
parentSuspense: SuspenseBoundary | null,
slotScopeIds: string[] | null,
optimized?: boolean,
) => Node | null,
] {
const {
mt: mountComponent,
p: patch,
o: {
patchProp,
createText,
nextSibling,
parentNode,
remove,
insert,
createComment,
},
} = rendererInternals
const hydrate: RootHydrateFunction = (vnode, container) => {
Iif (!container.hasChildNodes()) {
;(__DEV__ || __FEATURE_PROD_HYDRATION_MISMATCH_DETAILS__) &&
warn(
`Attempting to hydrate existing markup but container is empty. ` +
`Performing full mount instead.`,
)
patch(null, vnode, container)
flushPostFlushCbs()
container._vnode = vnode
return
}
hydrateNode(container.firstChild!, vnode, null, null, null)
flushPostFlushCbs()
container._vnode = vnode
}
const hydrateNode = (
node: Node,
vnode: VNode,
parentComponent: ComponentInternalInstance | null,
parentSuspense: SuspenseBoundary | null,
slotScopeIds: string[] | null,
optimized = false,
): Node | null => {
optimized = optimized || !!vnode.dynamicChildren
const isFragmentStart = isComment(node) && node.data === '['
const onMismatch = () =>
handleMismatch(
node,
vnode,
parentComponent,
parentSuspense,
slotScopeIds,
isFragmentStart,
)
const { type, ref, shapeFlag, patchFlag } = vnode
let domType = node.nodeType
vnode.el = node
if (__DEV__ || __FEATURE_PROD_DEVTOOLS__) {
def(node, '__vnode', vnode, true)
def(node, '__vueParentComponent', parentComponent, true)
}
if (patchFlag === PatchFlags.BAIL) {
optimized = false
vnode.dynamicChildren = null
}
let nextNode: Node | null = null
switch (type) {
case Text:
if (domType !== DOMNodeTypes.TEXT) {
// #5728 empty text node inside a slot can cause hydration failure
// because the server rendered HTML won't contain a text node
if (vnode.children === '') {
insert((vnode.el = createText('')), parentNode(node)!, node)
nextNode = node
} else E{
nextNode = onMismatch()
}
} else {
if ((node as Text).data !== vnode.children) {
;(__DEV__ || __FEATURE_PROD_HYDRATION_MISMATCH_DETAILS__) &&
warn(
`Hydration text mismatch in`,
node.parentNode,
`\n - rendered on server: ${JSON.stringify(
(node as Text).data,
)}` +
`\n - expected on client: ${JSON.stringify(vnode.children)}`,
)
logMismatchError()
;(node as Text).data = vnode.children as string
}
nextNode = nextSibling(node)
}
break
case VComment:
if (isTemplateNode(node)) {
nextNode = nextSibling(node)
// wrapped <transition appear>
// replace <template> node with inner child
replaceNode(
(vnode.el = node.content.firstChild!),
node,
parentComponent,
)
} else if (domType !== DOMNodeTypes.COMMENT || isFragmentStart) {
nextNode = onMismatch()
} else {
nextNode = nextSibling(node)
}
break
case Static:
if (isFragmentStart) {
// entire template is static but SSRed as a fragment
node = nextSibling(node)!
domType = node.nodeType
}
if (domType === DOMNodeTypes.ELEMENT || domType === DOMNodeTypes.TEXT) {
// determine anchor, adopt content
nextNode = node
// if the static vnode has its content stripped during build,
// adopt it from the server-rendered HTML.
const needToAdoptContent = !(vnode.children as string).length
for (let i = 0; i < vnode.staticCount!; i++) {
if (needToAdoptContent)
vnode.children +=
nextNode.nodeType === DOMNodeTypes.ELEMENT
? (nextNode as Element).outerHTML
: (nextNode as Text).data
if (i === vnode.staticCount! - 1) {
vnode.anchor = nextNode
}
nextNode = nextSibling(nextNode)!
}
return isFragmentStart ? nextSibling(nextNode) : nextNode
} else E{
onMismatch()
}
break
case Fragment:
Iif (!isFragmentStart) {
nextNode = onMismatch()
} else {
nextNode = hydrateFragment(
node as Comment,
vnode,
parentComponent,
parentSuspense,
slotScopeIds,
optimized,
)
}
break
default:
if (shapeFlag & ShapeFlags.ELEMENT) {
if (
(domType !== DOMNodeTypes.ELEMENT ||
(vnode.type as string).toLowerCase() !==
(node as Element).tagName.toLowerCase()) &&
!isTemplateNode(node)
) {
nextNode = onMismatch()
} else {
nextNode = hydrateElement(
node as Element,
vnode,
parentComponent,
parentSuspense,
slotScopeIds,
optimized,
)
}
} else if (shapeFlag & ShapeFlags.COMPONENT) {
// when setting up the render effect, if the initial vnode already
// has .el set, the component will perform hydration instead of mount
// on its sub-tree.
vnode.slotScopeIds = slotScopeIds
const container = parentNode(node)!
// Locate the next node.
if (isFragmentStart) {
// If it's a fragment: since components may be async, we cannot rely
// on component's rendered output to determine the end of the
// fragment. Instead, we do a lookahead to find the end anchor node.
nextNode = locateClosingAnchor(node)
} else if (isComment(node) && node.data === 'teleport start') {
// #4293 #6152
// If a teleport is at component root, look ahead for teleport end.
nextNode = locateClosingAnchor(node, node.data, 'teleport end')
} else {
nextNode = nextSibling(node)
}
mountComponent(
vnode,
container,
null,
parentComponent,
parentSuspense,
getContainerType(container),
optimized,
)
// #3787
// if component is async, it may get moved / unmounted before its
// inner component is loaded, so we need to give it a placeholder
// vnode that matches its adopted DOM.
//
// This covers three cases, all of which leave subTree unset:
// - the component has not resolved yet
// - the component has resolved, but uses a lazy hydration strategy
// that has not fired yet, so hydrating its subtree was deferred
// - the component's own async setup() has not resolved yet
if (
(isAsyncWrapper(vnode) || vnode.component!.asyncDep) &&
!vnode.component!.subTree
) {
let subTree
if (isFragmentStart) {
// the async component has no child vnodes yet, so represent its
// adopted DOM as an opaque range that can be moved or removed
subTree = createVNode(Static)
subTree.anchor = nextNode
? nextNode.previousSibling
: container.lastChild
} else {
// mirror the adopted node's type so the placeholder behaves like
// the rendered root would (transition hooks assume an element)
subTree =
node.nodeType === DOMNodeTypes.TEXT
? createTextVNode('')
: createVNode(
node.nodeType === DOMNodeTypes.COMMENT ? VComment : 'div',
)
}
subTree.el = node
vnode.component!.subTree = subTree
}
} else if (shapeFlag & ShapeFlags.TELEPORT) {
Iif (domType !== DOMNodeTypes.COMMENT) {
nextNode = onMismatch()
} else {
nextNode = (vnode.type as typeof TeleportImpl).hydrate(
node,
vnode as TeleportVNode,
parentComponent,
parentSuspense,
slotScopeIds,
optimized,
rendererInternals,
hydrateChildren,
)
}
} else if (__FEATURE_SUSPENSE__ && shapeFlag & ShapeFlags.SUSPENSE) {
nextNode = (vnode.type as typeof SuspenseImpl).hydrate(
node,
vnode,
parentComponent,
parentSuspense,
getContainerType(parentNode(node)!),
slotScopeIds,
optimized,
rendererInternals,
hydrateNode,
)
} else Eif (__DEV__ || __FEATURE_PROD_HYDRATION_MISMATCH_DETAILS__) {
warn('Invalid HostVNode type:', type, `(${typeof type})`)
}
}
if (ref != null) {
setRef(ref, null, parentSuspense, vnode)
}
return nextNode
}
const hydrateElement = (
el: Element,
vnode: VNode,
parentComponent: ComponentInternalInstance | null,
parentSuspense: SuspenseBoundary | null,
slotScopeIds: string[] | null,
optimized: boolean,
) => {
optimized = optimized || !!vnode.dynamicChildren
const {
type,
dynamicProps,
props,
patchFlag,
shapeFlag,
dirs,
transition,
} = vnode
// #4006 for form elements with non-string v-model value bindings
// e.g. <option :value="obj">, <input type="checkbox" :true-value="1">
// #7476 <input indeterminate>
const forcePatch = type === 'input' || type === 'option'
// #9033 force hydrate dynamic props.
// Keep separate from forcePatch, which also patches value-like keys.
const hasDynamicProps = !!dynamicProps
// skip props & children if this is hoisted static nodes
// #5405 in dev, always hydrate children for HMR
Eif (
__DEV__ ||
forcePatch ||
hasDynamicProps ||
patchFlag !== PatchFlags.CACHED
) {
if (dirs) {
invokeDirectiveHook(vnode, null, parentComponent, 'created')
}
// handle appear transition
let needCallTransitionHooks = false
if (isTemplateNode(el)) {
needCallTransitionHooks =
needTransition(
null, // no need check parentSuspense in hydration
transition,
) &&
parentComponent &&
parentComponent.vnode.props &&
parentComponent.vnode.props.appear
const content = (el as HTMLTemplateElement).content
.firstChild as Element & { $cls?: string }
if (needCallTransitionHooks) {
const cls = content.getAttribute('class')
if (cls) content.$cls = cls
transition!.beforeEnter(content)
}
// replace <template> node with inner children
replaceNode(content, el, parentComponent)
vnode.el = el = content
}
// children
if (
shapeFlag & ShapeFlags.ARRAY_CHILDREN &&
// skip if element has innerHTML / textContent
!(props && (props.innerHTML || props.textContent))
) {
let next = hydrateChildren(
el.firstChild,
vnode,
el,
parentComponent,
parentSuspense,
slotScopeIds,
optimized,
)
if (next && !isMismatchAllowed(el, MismatchTypes.CHILDREN)) {
;(__DEV__ || __FEATURE_PROD_HYDRATION_MISMATCH_DETAILS__) &&
warn(
`Hydration children mismatch on`,
el,
`\nServer rendered element contains more child nodes than client vdom.`,
)
logMismatchError()
}
while (next) {
// The SSRed DOM contains more nodes than it should. Remove them.
const cur = next
next = next.nextSibling
remove(cur)
}
} else if (shapeFlag & ShapeFlags.TEXT_CHILDREN) {
// #11873 the HTML parser will "eat" the first newline when parsing
// <pre> and <textarea>, so if the client value starts with a newline,
// we need to remove it before comparing
let clientText = vnode.children as string
if (
clientText[0] === '\n' &&
(el.tagName === 'PRE' || el.tagName === 'TEXTAREA')
) {
clientText = clientText.slice(1)
}
const { textContent } = el
if (
textContent !== clientText &&
// innerHTML normalize \r\n or \r into a single \n in the DOM
textContent !== clientText.replace(/\r\n|\r/g, '\n')
) {
if (!isMismatchAllowed(el, MismatchTypes.TEXT)) {
;(__DEV__ || __FEATURE_PROD_HYDRATION_MISMATCH_DETAILS__) &&
warn(
`Hydration text content mismatch on`,
el,
`\n - rendered on server: ${textContent}` +
`\n - expected on client: ${clientText}`,
)
logMismatchError()
}
el.textContent = vnode.children as string
}
}
// props
if (props) {
if (
__DEV__ ||
__FEATURE_PROD_HYDRATION_MISMATCH_DETAILS__ ||
forcePatch ||
hasDynamicProps ||
!optimized ||
patchFlag & (PatchFlags.FULL_PROPS | PatchFlags.NEED_HYDRATION)
) {
const isCustomElement = el.tagName.includes('-')
const namespace = el.namespaceURI!.includes('svg')
? 'svg'
: el.namespaceURI!.includes('MathML')
? 'mathml'
: undefined
for (const key in props) {
// check hydration mismatch
if (
(__DEV__ || __FEATURE_PROD_HYDRATION_MISMATCH_DETAILS__) &&
// #11189 skip if this node has directives that have created hooks
// as it could have mutated the DOM in any possible way
!(dirs && dirs.some(d => d.dir.created)) &&
propHasMismatch(el, key, props[key], vnode, parentComponent)
) {
logMismatchError()
}
if (
(forcePatch &&
(key.endsWith('value') || key === 'indeterminate')) ||
(isOn(key) && !isReservedProp(key)) ||
// force hydrate v-bind with .prop modifiers
key[0] === '.' ||
(isCustomElement && !isReservedProp(key)) ||
(dynamicProps && dynamicProps.includes(key))
) {
if (isUnchangedResourceProp(el, key, props[key])) {
continue
}
patchProp(el, key, null, props[key], namespace, parentComponent)
}
}
} else Iif (props.onClick) {
// Fast path for click listeners (which is most often) to avoid
// iterating through props.
patchProp(
el,
'onClick',
null,
props.onClick,
undefined,
parentComponent,
)
} else Eif (patchFlag & PatchFlags.STYLE && isReactive(props.style)) {
// #11372: object style values are iterated during patch instead of
// render/normalization phase, but style patch is skipped during
// hydration, so we need to force iterate the object to track deps
for (const key in props.style) props.style[key]
}
}
// vnode / directive hooks
let vnodeHooks: VNodeHook | null | undefined
Iif ((vnodeHooks = props && props.onVnodeBeforeMount)) {
invokeVNodeHook(vnodeHooks, parentComponent, vnode)
}
if (dirs) {
invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount')
}
if (
(vnodeHooks = props && props.onVnodeMounted) ||
dirs ||
needCallTransitionHooks
) {
queueEffectWithSuspense(() => {
vnodeHooks && invokeVNodeHook(vnodeHooks, parentComponent, vnode)
needCallTransitionHooks && transition!.enter(el)
dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted')
}, parentSuspense)
}
}
return el.nextSibling
}
const hydrateChildren = (
node: Node | null,
parentVNode: VNode,
container: Element,
parentComponent: ComponentInternalInstance | null,
parentSuspense: SuspenseBoundary | null,
slotScopeIds: string[] | null,
optimized: boolean,
): Node | null => {
optimized = optimized || !!parentVNode.dynamicChildren
const children = parentVNode.children as VNode[]
const l = children.length
let hasCheckedMismatch = false
for (let i = 0; i < l; i++) {
const vnode = optimized
? children[i]
: (children[i] = normalizeVNode(children[i]))
const isText = vnode.type === Text
if (node) {
if (isText && !optimized) {
// #7285 possible consecutive text vnodes from manual render fns or
// JSX-compiled fns, but on the client the browser parses only 1 text
// node.
// look ahead for next possible text vnode
if (i + 1 < l && normalizeVNode(children[i + 1]).type === Text) {
// create an extra TextNode on the client for the next vnode to
// adopt
insert(
createText(
(node as Text).data.slice((vnode.children as string).length),
),
container,
nextSibling(node),
)
;(node as Text).data = vnode.children as string
}
}
node = hydrateNode(
node,
vnode,
parentComponent,
parentSuspense,
slotScopeIds,
optimized,
)
} else if (isText && !vnode.children) {
// #7215 create a TextNode for empty text node
// because server rendered HTML won't contain a text node
insert((vnode.el = createText('')), container)
} else {
if (!hasCheckedMismatch) {
hasCheckedMismatch = true
if (!isMismatchAllowed(container, MismatchTypes.CHILDREN)) {
;(__DEV__ || __FEATURE_PROD_HYDRATION_MISMATCH_DETAILS__) &&
warn(
`Hydration children mismatch on`,
container,
`\nServer rendered element contains fewer child nodes than client vdom.`,
)
logMismatchError()
}
}
// the SSRed DOM didn't contain enough nodes. Mount the missing ones.
patch(
null,
vnode,
container,
null,
parentComponent,
parentSuspense,
getContainerType(container),
slotScopeIds,
)
}
}
return node
}
const hydrateFragment = (
node: Comment,
vnode: VNode,
parentComponent: ComponentInternalInstance | null,
parentSuspense: SuspenseBoundary | null,
slotScopeIds: string[] | null,
optimized: boolean,
) => {
const { slotScopeIds: fragmentSlotScopeIds } = vnode
Iif (fragmentSlotScopeIds) {
slotScopeIds = slotScopeIds
? slotScopeIds.concat(fragmentSlotScopeIds)
: fragmentSlotScopeIds
}
const container = parentNode(node)!
const next = hydrateChildren(
nextSibling(node)!,
vnode,
container,
parentComponent,
parentSuspense,
slotScopeIds,
optimized,
)
if (next && isComment(next) && next.data === ']') {
return nextSibling((vnode.anchor = next))
} else {
// fragment didn't hydrate successfully, since we didn't get a end anchor
// back. This should have led to node/children mismatch warnings.
logMismatchError()
// since the anchor is missing, we need to create one and insert it
insert((vnode.anchor = createComment(`]`)), container, next)
return next
}
}
const handleMismatch = (
node: Node,
vnode: VNode,
parentComponent: ComponentInternalInstance | null,
parentSuspense: SuspenseBoundary | null,
slotScopeIds: string[] | null,
isFragment: boolean,
): Node | null => {
if (!isNodeMismatchAllowed(node, vnode)) {
;(__DEV__ || __FEATURE_PROD_HYDRATION_MISMATCH_DETAILS__) &&
warn(
`Hydration node mismatch:\n- rendered on server:`,
node,
node.nodeType === DOMNodeTypes.TEXT
? `(text)`
: isComment(node) && node.data === '['
? `(start of fragment)`
: ``,
`\n- expected on client:`,
vnode.type,
)
logMismatchError()
}
vnode.el = null
if (isFragment) {
// remove excessive fragment nodes
const end = locateClosingAnchor(node)
while (true) {
const next = nextSibling(node)
if (next && next !== end) {
remove(next)
} else {
break
}
}
}
const next = nextSibling(node)
const container = parentNode(node)!
remove(node)
patch(
null,
vnode,
container,
next,
parentComponent,
parentSuspense,
getContainerType(container),
slotScopeIds,
)
// the component vnode's el should be updated when a mismatch occurs.
Eif (parentComponent) {
parentComponent.vnode.el = vnode.el
updateHOCHostEl(parentComponent, vnode.el)
}
return next
}
// looks ahead for a start and closing comment node
const locateClosingAnchor = (
node: Node | null,
open = '[',
close = ']',
): Node | null => {
let match = 0
while (node) {
node = nextSibling(node)
if (node && isComment(node)) {
if (node.data === open) match++
if (node.data === close) {
if (match === 0) {
return nextSibling(node)
} else {
match--
}
}
}
}
return node
}
const replaceNode = (
newNode: Node,
oldNode: Node,
parentComponent: ComponentInternalInstance | null,
): void => {
// replace node
const parentNode = oldNode.parentNode
Eif (parentNode) {
parentNode.replaceChild(newNode, oldNode)
}
// update vnode
let parent = parentComponent
while (parent) {
Eif (parent.vnode.el === oldNode) {
parent.vnode.el = parent.subTree.el = newNode
}
parent = parent.parent
}
}
const isTemplateNode = (node: Node): node is HTMLTemplateElement => {
return (
node.nodeType === DOMNodeTypes.ELEMENT &&
(node as Element).tagName === 'TEMPLATE'
)
}
return [hydrate, hydrateNode]
}
/**
* Dev only
*/
// attributes whose assignment triggers a (re)fetch of a resource
const resourceProps = /*@__PURE__*/ new Set(['src', 'srcset', 'href', 'poster'])
function isUnchangedResourceProp(
el: Element,
key: string,
clientValue: any,
): boolean {
if (!resourceProps.has(key)) {
return false
}
// compare against the rendered attribute rather than the reflected DOM
// property, which normalizes URLs to absolute form.
return (
el.getAttribute(key) === (clientValue == null ? null : `${clientValue}`)
)
}
function propHasMismatch(
el: Element & { $cls?: string },
key: string,
clientValue: any,
vnode: VNode,
instance: ComponentInternalInstance | null,
): boolean {
let mismatchType: MismatchTypes | undefined
let mismatchKey: string | undefined
let actual: string | boolean | null | undefined
let expected: string | boolean | null | undefined
if (key === 'class') {
// classes might be in different order, but that doesn't affect cascade
// so we just need to check if the class lists contain the same classes.
if (el.$cls) {
actual = el.$cls
delete el.$cls
} else {
actual = el.getAttribute('class')
}
expected = normalizeClass(clientValue)
if (!isSetEqual(toClassSet(actual || ''), toClassSet(expected))) {
mismatchType = MismatchTypes.CLASS
mismatchKey = `class`
}
} else if (key === 'style') {
// style might be in different order, but that doesn't affect cascade
actual = el.getAttribute('style') || ''
expected = isString(clientValue)
? clientValue
: stringifyStyle(normalizeStyle(clientValue))
const actualMap = toStyleMap(actual)
const expectedMap = toStyleMap(expected)
// If `v-show=false`, `display: 'none'` should be added to expected
if (vnode.dirs) {
for (const { dir, value } of vnode.dirs) {
// @ts-expect-error only vShow has this internal name
Eif (dir.name === 'show' && !value) {
expectedMap.set('display', 'none')
}
}
}
Eif (instance) {
resolveCssVars(instance, vnode, expectedMap)
}
if (!isMapEqual(actualMap, expectedMap)) {
mismatchType = MismatchTypes.STYLE
mismatchKey = 'style'
}
} else if (
(el instanceof SVGElement && isKnownSvgAttr(key)) ||
(el instanceof HTMLElement && (isBooleanAttr(key) || isKnownHtmlAttr(key)))
) {
if (key === 'hidden') {
actual = normalizeHiddenValue(el.getAttribute(key))
expected = normalizeHiddenValue(clientValue)
} else if (isBooleanAttr(key)) {
actual = el.hasAttribute(key)
expected = includeBooleanAttr(clientValue)
} else if (clientValue == null) {
actual = el.hasAttribute(key)
expected = false
} else {
if (el.hasAttribute(key)) {
actual = el.getAttribute(key)
} else if (key === 'value' && el.tagName === 'TEXTAREA') {
// #10000 textarea.value can't be retrieved by `hasAttribute`
actual = (el as HTMLTextAreaElement).value
} else {
actual = false
}
expected = isRenderableAttrValue(clientValue)
? String(clientValue)
: false
}
if (actual !== expected) {
mismatchType = MismatchTypes.ATTRIBUTE
mismatchKey = key
}
}
if (mismatchType != null && !isMismatchAllowed(el, mismatchType)) {
const format = (v: any) =>
v === false ? `(not rendered)` : `${mismatchKey}="${v}"`
const preSegment = `Hydration ${MismatchTypeString[mismatchType]} mismatch on`
const postSegment =
`\n - rendered on server: ${format(actual)}` +
`\n - expected on client: ${format(expected)}` +
`\n Note: this mismatch is check-only. The DOM will not be rectified ` +
`in production due to performance overhead.` +
`\n You should fix the source of the mismatch.`
if (__TEST__) {
// during tests, log the full message in one single string for easier
// debugging.
warn(`${preSegment} ${el.tagName}${postSegment}`)
} else E{
warn(preSegment, el, postSegment)
}
return true
}
return false
}
function normalizeHiddenValue(value: unknown): false | '' | 'until-found' {
if (!isRenderableAttrValue(value)) {
return false
}
if (isString(value)) {
// Attribute values from the DOM are strings, while numeric client values
// follow the `hidden` property setter, where 0 and NaN remove the attribute.
return value.toLowerCase() === 'until-found' ? 'until-found' : ''
}
return includeBooleanAttr(value) ? '' : false
}
function toClassSet(str: string): Set<string> {
return new Set(str.trim().split(/\s+/))
}
function isSetEqual(a: Set<string>, b: Set<string>): boolean {
if (a.size !== b.size) {
return false
}
for (const s of a) {
Iif (!b.has(s)) {
return false
}
}
return true
}
function toStyleMap(str: string): Map<string, string> {
const styleMap: Map<string, string> = new Map()
for (const item of str.split(';')) {
let [key, value] = item.split(':')
key = key.trim()
value = value && value.trim()
if (key && value) {
styleMap.set(key, value)
}
}
return styleMap
}
function isMapEqual(a: Map<string, string>, b: Map<string, string>): boolean {
if (a.size !== b.size) {
return false
}
for (const [key, value] of a) {
if (value !== b.get(key)) {
return false
}
}
return true
}
function resolveCssVars(
instance: ComponentInternalInstance,
vnode: VNode,
expectedMap: Map<string, string>,
) {
const root = instance.subTree
if (
instance.getCssVars &&
(vnode === root ||
(root &&
root.type === Fragment &&
(root.children as VNode[]).includes(vnode)))
) {
const cssVars = instance.getCssVars()
for (const key in cssVars) {
const value = normalizeCssVarValue(cssVars[key])
expectedMap.set(`--${getEscapedCssVarName(key, false)}`, value)
}
}
if (vnode === root && instance.parent) {
resolveCssVars(instance.parent, instance.vnode, expectedMap)
}
}
const allowMismatchAttr = 'data-allow-mismatch'
enum MismatchTypes {
TEXT = 0,
CHILDREN = 1,
CLASS = 2,
STYLE = 3,
ATTRIBUTE = 4,
}
const MismatchTypeString: Record<MismatchTypes, string> = {
[MismatchTypes.TEXT]: 'text',
[MismatchTypes.CHILDREN]: 'children',
[MismatchTypes.CLASS]: 'class',
[MismatchTypes.STYLE]: 'style',
[MismatchTypes.ATTRIBUTE]: 'attribute',
} as const
function isMismatchAllowed(
el: Element | null,
allowedType: MismatchTypes,
): boolean {
if (
allowedType === MismatchTypes.TEXT ||
allowedType === MismatchTypes.CHILDREN
) {
while (el && !el.hasAttribute(allowMismatchAttr)) {
el = el.parentElement
}
}
return isMismatchAllowedByAttr(
el && el.getAttribute(allowMismatchAttr),
allowedType,
)
}
function isMismatchAllowedByAttr(
allowedAttr: string | null,
allowedType: MismatchTypes,
): boolean {
if (allowedAttr == null) {
return false
} else if (allowedAttr === '') {
return true
} else {
const list = allowedAttr.split(',')
// text is a subset of children
if (allowedType === MismatchTypes.TEXT && list.includes('children')) {
return true
}
return list.includes(MismatchTypeString[allowedType])
}
}
function isNodeMismatchAllowed(node: Node, vnode: VNode): boolean {
return (
isMismatchAllowed(node.parentElement, MismatchTypes.CHILDREN) ||
isMismatchAllowedByNode(node) ||
isMismatchAllowedByVNode(vnode)
)
}
function isMismatchAllowedByNode(node: Node): boolean {
return (
node.nodeType === DOMNodeTypes.ELEMENT &&
isMismatchAllowedByAttr(
(node as Element).getAttribute(allowMismatchAttr),
MismatchTypes.CHILDREN,
)
)
}
function isMismatchAllowedByVNode({ props }: VNode): boolean {
const allowedAttr = props && props[allowMismatchAttr]
return (
typeof allowedAttr === 'string' &&
isMismatchAllowedByAttr(allowedAttr, MismatchTypes.CHILDREN)
)
}
|