diff --git a/packages/runtime-core/src/hydration.ts b/packages/runtime-core/src/hydration.ts index 40a65ac63c3..7b36a153ea5 100644 --- a/packages/runtime-core/src/hydration.ts +++ b/packages/runtime-core/src/hydration.ts @@ -38,6 +38,7 @@ import { stringifyStyle, } from '@vue/shared' import { + type ElementNamespace, type RendererInternals, getVaporInterface, needTransition, @@ -92,12 +93,24 @@ const isSVGContainer = (container: Element) => container.namespaceURI!.includes('svg') && container.tagName !== 'foreignObject' -const isMathMLContainer = (container: Element) => - container.namespaceURI!.includes('MathML') +const isMathMLContainer = (container: Element) => { + if (!container.namespaceURI!.includes('MathML')) return false + // switches its children back to HTML, + // mirroring `resolveChildrenNamespace` on the mount path. + if (container.tagName !== 'annotation-xml') return true + const encoding = container.getAttribute('encoding') + return !encoding || !encoding.includes('html') +} -const getContainerType = ( +/** + * Resolve the element namespace a container's children should be created in. + * The live DOM is the source of truth, so this also covers containers that are + * only known at runtime (interop boundaries, teleport targets). + * @internal + */ +export const getContainerType = ( container: Element | ShadowRoot, -): 'svg' | 'mathml' | undefined => { +): ElementNamespace => { if (container.nodeType !== DOMNodeTypes.ELEMENT) return undefined if (isSVGContainer(container as Element)) return 'svg' if (isMathMLContainer(container as Element)) return 'mathml' diff --git a/packages/runtime-core/src/index.ts b/packages/runtime-core/src/index.ts index c60fbfaa5d3..858e6a82fde 100644 --- a/packages/runtime-core/src/index.ts +++ b/packages/runtime-core/src/index.ts @@ -679,7 +679,7 @@ export { createCanSetSetupRefChecker } from './rendererTemplateRef' /** * @internal */ -export { isTemplateNode } from './hydration' +export { isTemplateNode, getContainerType } from './hydration' /** * @internal diff --git a/packages/runtime-vapor/__tests__/hydration.spec.ts b/packages/runtime-vapor/__tests__/hydration.spec.ts index 737e7259128..d6c95ace415 100644 --- a/packages/runtime-vapor/__tests__/hydration.spec.ts +++ b/packages/runtime-vapor/__tests__/hydration.spec.ts @@ -4801,6 +4801,48 @@ describe('Vapor Mode hydration', () => { expect(container.textContent).toBe('B') }) + // The deferred shared fallback parks content in a detached + // DocumentFragment during hydration, so the slot's namespace has to come + // from the SSR container captured before rendering, not from + // `currentParentNode`. + test('shared roots parked during hydration keep the svg namespace', async () => { + const data = reactive({ showA: false, showB: false }) + const { container } = await testWithVDOMApp( + ` + `, + { + Receiver: ``, + Carrier: ` + `, + }, + data, + ) + expect(container.textContent).toBe('fb') + expect(`Hydration children mismatch`).not.toHaveBeenWarned() + + data.showA = true + await nextTick() + expect(container.querySelector('circle')!.namespaceURI).toBe( + 'http://www.w3.org/2000/svg', + ) + + data.showB = true + await nextTick() + expect(container.querySelector('rect')!.namespaceURI).toBe( + 'http://www.w3.org/2000/svg', + ) + }) + test('vdom shared roots hydrate from receiver fallback', async () => { const data = reactive({ mount: true, showA: false, showB: false }) const { app, container } = await testWithVDOMApp( diff --git a/packages/runtime-vapor/__tests__/interopNamespace.spec.ts b/packages/runtime-vapor/__tests__/interopNamespace.spec.ts new file mode 100644 index 00000000000..64f157956fe --- /dev/null +++ b/packages/runtime-vapor/__tests__/interopNamespace.spec.ts @@ -0,0 +1,216 @@ +import { createApp, defineComponent, h, nextTick, ref } from '@vue/runtime-dom' +import { + createComponent, + createIf, + createSlot, + defineVaporComponent, + insert, + template, + vaporInteropPlugin, +} from '../src' + +const svgNS = 'http://www.w3.org/2000/svg' +const mathmlNS = 'http://www.w3.org/1998/Math/MathML' +const htmlNS = 'http://www.w3.org/1999/xhtml' + +let host: HTMLElement +beforeEach(() => { + host = document.createElement('div') +}) +afterEach(() => { + host.remove() +}) + +function mount(comp: any) { + const app = createApp(comp) + app.use(vaporInteropPlugin) + app.mount(host) + return app +} + +// A vapor parent whose template is `html`, with `mountChild()` inserted into +// the node returned by `pick` (the template root by default). +function vaporHost( + html: string, + ns: number, + mountChild: () => any, + pick: (root: any) => any = root => root, +) { + return defineVaporComponent({ + setup() { + const root = template(html, 1, ns)() as any + insert(mountChild(), pick(root)) + return root + }, + }) +} + +describe('vdom-in-vapor element namespace', () => { + test('vdom component under a vapor ', () => { + const Circle = defineComponent({ setup: () => () => h('circle') }) + mount(vaporHost('', 1, () => createComponent(Circle as any))) + expect(host.querySelector('circle')!.namespaceURI).toBe(svgNS) + }) + + test('nested vdom tree under a vapor inherits down', () => { + const Inner = defineComponent({ setup: () => () => h('circle') }) + const Outer = defineComponent({ setup: () => () => h('g', [h(Inner)]) }) + mount(vaporHost('', 1, () => createComponent(Outer as any))) + // vdom propagates the namespace through its own subtree, so the interop + // boundary only has to get the entry point right. + expect(host.querySelector('g')!.namespaceURI).toBe(svgNS) + expect(host.querySelector('circle')!.namespaceURI).toBe(svgNS) + }) + + test('vdom component under a vapor ', () => { + const Mi = defineComponent({ setup: () => () => h('mi', 'x') }) + mount(vaporHost('', 2, () => createComponent(Mi as any))) + expect(host.querySelector('mi')!.namespaceURI).toBe(mathmlNS) + }) + + test('vdom content mounted into a vapor after a v-if flips', async () => { + const show = ref(false) + const Rect = defineComponent({ setup: () => () => h('rect') }) + mount( + defineVaporComponent({ + setup() { + const root = template('', 1)() as any + insert( + createIf( + () => show.value, + () => createComponent(Rect as any), + ) as any, + root, + root.firstChild, + ) + return root + }, + }), + ) + show.value = true + await nextTick() + expect(host.querySelector('rect')!.namespaceURI).toBe(svgNS) + }) + + test('vdom slot content under a vapor ', () => { + const Child = defineVaporComponent({ + setup() { + const root = template('', 1)() as any + insert(createSlot('default', null) as any, root) + return root + }, + }) + mount( + defineComponent({ + setup: () => () => + h(Child as any, null, { default: () => [h('rect')] }), + }), + ) + expect(host.querySelector('rect')!.namespaceURI).toBe(svgNS) + }) + + test('multiple vdom slot children under a vapor ', () => { + const Child = defineVaporComponent({ + setup() { + const root = template('', 1)() as any + insert(createSlot('default', null) as any, root) + return root + }, + }) + mount( + defineComponent({ + setup: () => () => + h(Child as any, null, { default: () => [h('rect'), h('circle')] }), + }), + ) + expect(host.querySelector('rect')!.namespaceURI).toBe(svgNS) + expect(host.querySelector('circle')!.namespaceURI).toBe(svgNS) + }) + + // coverage guard: green before the fix too (undefined happened to be right), + // but it is what stops `` from being treated as an SVG parent. + test('vdom component under stays HTML', () => { + const Div = defineComponent({ setup: () => () => h('div', 'x') }) + mount( + vaporHost( + '', + 1, + () => createComponent(Div as any), + root => root.firstChild, + ), + ) + expect(host.querySelector('div')!.namespaceURI).toBe(htmlNS) + }) + + // Locks the annotation-xml rule added to `getContainerType`. Without it the + // helper reports 'mathml' here and the
is created in the MathML + // namespace — i.e. reusing getContainerType as-is would regress this. + test('vdom component under stays HTML', () => { + const Div = defineComponent({ setup: () => () => h('div', 'x') }) + mount( + vaporHost( + '', + 2, + () => createComponent(Div as any), + root => root.firstChild, + ), + ) + expect(host.querySelector('div')!.namespaceURI).toBe(htmlNS) + }) + + test('vdom component under a non-html annotation-xml stays MathML', () => { + const Mi = defineComponent({ setup: () => () => h('mi', 'x') }) + mount( + vaporHost( + '', + 2, + () => createComponent(Mi as any), + root => root.firstChild, + ), + ) + expect(host.querySelector('mi')!.namespaceURI).toBe(mathmlNS) + }) + + // The namespace is captured once from the real container. Re-reading it per + // patch would report HTML while the content is parked in the detached + // DocumentFragment a shared fallback swaps in. + test('slot content keeps its namespace across a fallback park/restore', async () => { + const show = ref(true) + const Child = defineVaporComponent({ + setup() { + const root = template('', 1)() as any + insert( + createSlot('default', null, () => + template('fb', 0, 1)(), + ) as any, + root, + ) + return root + }, + }) + mount( + defineComponent({ + setup: () => () => + h(Child as any, null, { + default: () => (show.value ? [h('rect')] : []), + }), + }), + ) + expect(host.querySelector('rect')!.namespaceURI).toBe(svgNS) + show.value = false + await nextTick() + expect(host.querySelector('rect')).toBe(null) + show.value = true + await nextTick() + expect(host.querySelector('rect')!.namespaceURI).toBe(svgNS) + }) + + // Known, deliberately unfixed: vapor templates bake their namespace at + // compile time, so a vapor component whose root is an SVG *child* element + // (//) renders in the HTML namespace. Not an interop bug — + // it reproduces in a pure vapor tree too. A vapor component rooted at + // itself is fine. Fixing it needs a creation-time ambient namespace plus + // per-namespace template caching; see namespace.md §6.2 for the revival + // conditions. + test.todo('vapor component rooted at an svg child, used inside an ') +}) diff --git a/packages/runtime-vapor/src/vdomInterop.ts b/packages/runtime-vapor/src/vdomInterop.ts index 7cc9456d1bf..62d6d32f7c4 100644 --- a/packages/runtime-vapor/src/vdomInterop.ts +++ b/packages/runtime-vapor/src/vdomInterop.ts @@ -2,6 +2,7 @@ import { type App, type ComponentInternalInstance, type ConcreteComponent, + type ElementNamespace, ErrorCodes, Fragment, type FunctionalComponent, @@ -33,6 +34,7 @@ import { ensureRenderer, ensureValidVNode, ensureVaporSlotFallback, + getContainerType, getInheritedScopeIds, getTransitionRawChildren, invokeDirectiveHook, @@ -1076,6 +1078,12 @@ function mountVNode( let isMounted = false let mountedParentNode: ParentNode | undefined let mountedAnchor: Node | null = null + // The insertion container is the authority for the element namespace: it sees + // through component boundaries and runtime-resolved targets, which neither a + // compile-time constant nor a plumbed parameter can. Captured once at mount + // and reused for later patches, mirroring how VDOM closes the mount-time + // namespace over a component's render effect. + let namespace: ElementNamespace const unmount = (parentNode?: ParentNode, transition?: TransitionHooks) => { if (transition) setVNodeTransitionHooks(vnode, transition) const parentSuspense = resolveUnmountSuspense(suspense) @@ -1145,6 +1153,7 @@ function mountVNode( simpleSetCurrentInstance(parentComponent) if (!isMounted) { if (transition) setVNodeTransitionHooks(vnode, transition) + namespace = getContainerType(parentNode as Element) internals.p( null, vnode, @@ -1152,7 +1161,7 @@ function mountVNode( anchor, parentComponent as any, operationSuspense, - undefined, // namespace + namespace, frag.slotScopeIds, ) onScopeDispose(unmount, true) @@ -1209,7 +1218,7 @@ function mountVNode( mountedAnchor, parentComponent as any, suspense, - undefined, // namespace + namespace, frag.slotScopeIds, ) simpleSetCurrentInstance(prevInstance) @@ -1401,7 +1410,7 @@ function createVDOMComponent( anchor, parentComponent as any, operationSuspense, - undefined, + getContainerType(parentNode as Element), false, ) // set ref @@ -1650,6 +1659,10 @@ function renderVDOMSlot( rendered: null as VNode | Block | null, } let currentParentNode: ParentNode | null = null + // Captured from the real DOM container on insert. `currentParentNode` is not + // a safe source here: it is swapped to a detached DocumentFragment while + // content is parked for a shared fallback (see `sharedContentStorage`). + let slotNamespace: ElementNamespace let currentAnchor: Node | null = null let sharedContentStorage: DocumentFragment | undefined let disposed = false @@ -1852,7 +1865,7 @@ function renderVDOMSlot( currentAnchor, parentComponent as any, suspense, - undefined, + slotNamespace, concatInteropScopeIds(frag.slotScopeIds, slotScopeIds), ) setRenderedContent(next, valid) @@ -1936,6 +1949,7 @@ function renderVDOMSlot( currentAnchor = anchor if (!isMounted) { + slotNamespace = getContainerType(parentNode as Element) scope.run(render) isMounted = true } else { @@ -2319,7 +2333,7 @@ function renderVDOMSlot( currentAnchor, parentComponent as any, suspense, - undefined, + slotNamespace, null, ) return @@ -2367,7 +2381,7 @@ function renderVDOMSlot( currentAnchor, parentComponent as any, suspense, - undefined, + slotNamespace, null, ) return @@ -2417,11 +2431,20 @@ function renderVDOMSlot( frag.hydrate = () => { if (!isHydrating) return + // Resolve the namespace from the SSR container before rendering: a + // deferred shared fallback parks content in a detached DocumentFragment + // and points `currentParentNode` at it, which would report HTML for + // content that belongs under an /. + const hydrationParent = + currentHydrationNode && currentHydrationNode.parentNode scope.run(render) if (!currentParentNode) { currentAnchor = getCurrentSlotEndAnchor() || currentHydrationNode currentParentNode = currentAnchor!.parentNode as ParentNode } + slotNamespace = getContainerType( + (hydrationParent || currentParentNode) as Element, + ) if (contentState.valid && fallback && !inheritFallback && !frag.anchor) { // Insert an outlet-owned anchor after traversal so it cannot shift // hydration indices. @@ -2984,6 +3007,9 @@ function createVNodeChildrenFragment( let currentVNode: VNode | null = null let currentChildren: VNode[] = EMPTY_VNODES let currentParentNode: ParentNode | null = null + // Captured once from the real DOM container, mirroring how VDOM closes the + // mount-time namespace over a component's render effect. + let childrenNamespace: ElementNamespace let currentAnchor: Node | null = null let isMounted = false let isRenderEffectStarted = false @@ -3051,6 +3077,7 @@ function createVNodeChildrenFragment( currentChildren = nextChildren currentVNode = createVNode(Fragment, null, nextChildren) currentParentNode = currentHydrationNode!.parentNode as ParentNode + childrenNamespace = getContainerType(currentParentNode as Element) currentAnchor = currentHydrationNode // Slot fallback hydration can leave an inner empty-branch anchor // immediately before the enclosing slot end anchor. Fragment @@ -3091,7 +3118,7 @@ function createVNodeChildrenFragment( currentAnchor, parentComponent, suspense, - undefined, + childrenNamespace, frag.slotScopeIds, false, ) @@ -3112,7 +3139,7 @@ function createVNodeChildrenFragment( currentAnchor, parentComponent, suspense, - undefined, + childrenNamespace, frag.slotScopeIds, false, ) @@ -3153,6 +3180,7 @@ function createVNodeChildrenFragment( currentParentNode = parentNode currentAnchor = anchor if (!isMounted) { + childrenNamespace = getContainerType(parentNode as Element) startRenderEffect() if (currentVNode) { trackSlotVNodeUpdatesWithRefresh( @@ -3170,7 +3198,7 @@ function createVNodeChildrenFragment( currentAnchor, parentComponent, suspense, - undefined, + childrenNamespace, frag.slotScopeIds, false, )