Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(custom-element): properly handle custom element remove then insert again #12413

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions packages/runtime-dom/__tests__/customElement.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,62 @@ describe('defineCustomElement', () => {
expect(e._instance).toBeTruthy()
expect(e.shadowRoot!.innerHTML).toBe('<div>hello</div>')
})

// #12412
const contextElStyle = ':host { color: red }'
const ContextEl = defineCustomElement({
props: {
msg: String,
},
styles: [contextElStyle],
setup(props, { expose }) {
expose({
text: () => props.msg,
})
provide('context', props)
const context = inject('context', {}) as typeof props
return () => context.msg || props.msg
},
})
customElements.define('my-context-el', ContextEl)
test('remove element with child custom element and wait fully disconnected then append and change attribute', async () => {
container.innerHTML = `<div><my-context-el msg="msg1"><my-context-el></my-context-el></my-context-el></div>`
const parent = container.children[0].children[0] as VueElement & {
text: () => string
}
const child = parent.children[0] as VueElement
parent.remove()
await nextTick()
await nextTick() // wait two ticks for disconnect
expect('text' in parent).toBe(false)
expect(child.shadowRoot!.querySelectorAll('style').length).toBe(1)
container.appendChild(parent) // should not throw Error
await nextTick()
expect(parent.text()).toBe('msg1')
expect(parent.shadowRoot!.textContent).toBe(contextElStyle + 'msg1')
expect(child.shadowRoot!.textContent).toBe(contextElStyle + 'msg1')
parent.setAttribute('msg', 'msg2')
await nextTick()
expect(parent.shadowRoot!.textContent).toBe(contextElStyle + 'msg2')
await nextTick()
expect(child.shadowRoot!.textContent).toBe(contextElStyle + 'msg2')
expect(child.shadowRoot!.querySelectorAll('style').length).toBe(1)
})

test('move element to new parent', async () => {
container.innerHTML = `<my-context-el msg="msg1"></my-context-el><my-context-el msg="msg2"></my-context-el>`
const first = container.children[0] as VueElement,
second = container.children[1] as VueElement & { text: () => string }
await nextTick()
expect(second.shadowRoot!.textContent).toBe(contextElStyle + 'msg2')
first.append(second)
await nextTick()
expect(second.shadowRoot!.textContent).toBe(contextElStyle + 'msg1')
expect(second.shadowRoot!.querySelectorAll('style').length).toBe(1)
second.setAttribute('msg', 'msg3')
await nextTick()
expect(second.text()).toBe('msg3')
})
})

describe('props', () => {
Expand Down
71 changes: 49 additions & 22 deletions packages/runtime-dom/src/apiCustomElement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -286,20 +286,25 @@ export class VueElement
this._connected = true

// locate nearest Vue custom element parent for provide/inject
let parent: Node | null = this
let parent: Node | null = this,
parentChanged = false
while (
(parent = parent && (parent.parentNode || (parent as ShadowRoot).host))
) {
if (parent instanceof VueElement) {
parentChanged = parent !== this._parent
this._parent = parent
break
}
}

if (!this._instance) {
// unmount if parent changed and previously mounted, should keep parent and observer
if (this._instance && parentChanged) this._unmount(true)
if (!this._instance || parentChanged) {
if (this._resolved) {
this._setParent()
this._update()
// no instance means no observer
if (!this._instance) this._observe()
this._mount(this._def)
} else {
if (parent && parent._pendingResolve) {
this._pendingResolve = parent._pendingResolve.then(() => {
Expand All @@ -320,22 +325,47 @@ export class VueElement
}
}

private _unmount(keepParentAndOb?: boolean) {
if (!keepParentAndOb) {
this._parent = undefined
if (this._ob) {
this._ob.disconnect()
this._ob = null
}
}
this._app && this._app.unmount()
if (this._instance) {
const exposed = this._instance.exposed
if (exposed) {
for (const key in exposed) {
delete this[key as keyof this]
}
}
this._instance.ce = undefined
}
this._app = this._instance = null
}

disconnectedCallback(): void {
this._connected = false
nextTick(() => {
if (!this._connected) {
if (this._ob) {
this._ob.disconnect()
this._ob = null
}
// unmount
this._app && this._app.unmount()
if (this._instance) this._instance.ce = undefined
this._app = this._instance = null
this._unmount()
}
})
}

private _observe() {
if (!this._ob) {
this._ob = new MutationObserver(mutations => {
for (const m of mutations) {
this._setAttr(m.attributeName!)
}
})
}
this._ob.observe(this, { attributes: true })
}

/**
* resolve inner component definition (handle possible async component)
*/
Expand All @@ -350,13 +380,7 @@ export class VueElement
}

// watch future attr changes
this._ob = new MutationObserver(mutations => {
for (const m of mutations) {
this._setAttr(m.attributeName!)
}
})

this._ob.observe(this, { attributes: true })
this._observe()

const resolve = (def: InnerComponentDef, isAsync = false) => {
this._resolved = true
Expand Down Expand Up @@ -430,11 +454,14 @@ export class VueElement
if (!hasOwn(this, key)) {
// exposed properties are readonly
Object.defineProperty(this, key, {
configurable: true, // should be configurable to allow deleting when disconnected
// unwrap ref to be consistent with public instance behavior
get: () => unref(exposed[key]),
})
} else if (__DEV__) {
warn(`Exposed property "${key}" already exists on custom element.`)
} else {
delete exposed[key] // delete it from exposed in case of deleting wrong exposed key when disconnected
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you provide more info on why need this line?

Copy link
Author

@lejunyang lejunyang Nov 18, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is to remove invalid exposed key.
Let's say we have an element with prop foo, and we accidentally expose an object {foo: 1}, it will be ignored as foo is already on this element. In disconnectedCallback, we'll delete exposed properties according to exposed, but deleting foo can cause an error as it's non-configurable prop.
Therefore, we should remove that key ahead

if (__DEV__)
warn(`Exposed property "${key}" already exists on custom element.`)
}
}
}
Expand Down Expand Up @@ -514,7 +541,7 @@ export class VueElement
} else if (!val) {
this.removeAttribute(hyphenate(key))
}
ob && ob.observe(this, { attributes: true })
this._observe()
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion packages/vue/__tests__/e2e/ssr-custom-element.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,6 @@ test('work with Teleport (shadowRoot: false)', async () => {
},
{ shadowRoot: false },
)
customElements.define('my-y', Y)
const P = defineSSRCustomElement(
{
render() {
Expand All @@ -110,6 +109,7 @@ test('work with Teleport (shadowRoot: false)', async () => {
{ shadowRoot: false },
)
customElements.define('my-p', P)
customElements.define('my-y', Y)
})

function getInnerHTML() {
Expand Down