Skip to content

feat(runtime-dom): useNativeSlots helper #13731

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

Open
wants to merge 1 commit into
base: minor
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
107 changes: 107 additions & 0 deletions packages/runtime-dom/__tests__/customElement.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
render,
renderSlot,
useHost,
useNativeSlots,
useShadowRoot,
} from '../src'

Expand Down Expand Up @@ -1399,6 +1400,112 @@ describe('defineCustomElement', () => {
const style = el.shadowRoot?.querySelector('style')!
expect(style.textContent).toBe(`div { color: red; }`)
})

describe('useNativeSlots', () => {
test('default slot', async () => {
async function testDefaultSlot(shadowRoot: boolean) {
let slots: Record<string, Node[]>
const Comp = defineCustomElement(
{
setup() {
slots = useNativeSlots()!
},
render() {
return h('div', null, [
renderSlot(this.$slots, 'default', undefined, () => [
'fallback',
]),
])
},
},
{ shadowRoot },
)

const ceTag =
'my-el-use-native-slots' + (shadowRoot ? '-sr' : '-no-sr')
customElements.define(ceTag, Comp)

container.innerHTML = `<${ceTag}><div>Content</div></${ceTag}>`
await nextTick()
expect(Object.keys(slots!)).toHaveLength(1)
expect(slots!['default']).toMatchObject([
{ tagName: 'DIV', textContent: 'Content' },
])

container.innerHTML = `<${ceTag}><div>New Content</div></${ceTag}>`
await nextTick()
expect(Object.keys(slots!)).toHaveLength(1)
expect(slots!['default']).toMatchObject([
{ tagName: 'DIV', textContent: 'New Content' },
])

container.innerHTML = `<${ceTag}><div>New Content</div><span>More Content</span></${ceTag}>`
await nextTick()
expect(Object.keys(slots!)).toHaveLength(1)
expect(slots!['default']).toMatchObject([
{ tagName: 'DIV', textContent: 'New Content' },
{ tagName: 'SPAN', textContent: 'More Content' },
])

container.innerHTML = `<${ceTag}></${ceTag}>`
await nextTick()
expect(Object.keys(slots!)).toHaveLength(0)
}

await testDefaultSlot(true)
await testDefaultSlot(false)
})

test('named slots', async () => {
async function testNamedSlots(shadowRoot: boolean) {
let slots: Record<string, Node[]>
const Comp = defineCustomElement(
{
setup() {
slots = useNativeSlots()!
},
render() {
return h('div', null, [
renderSlot(this.$slots, 'slot1', undefined, () => [
'fallback',
]),
renderSlot(this.$slots, 'slot2', undefined, () => [
'fallback',
]),
])
},
},
{ shadowRoot },
)

const ceTag =
'my-el-use-native-slots-named' + (shadowRoot ? '-sr' : '-no-sr')
customElements.define(ceTag, Comp)

container.innerHTML = `<${ceTag}><div slot="slot1">Content</div></${ceTag}>`
await nextTick()
expect(Object.keys(slots!)).toHaveLength(1)
expect(slots!['slot1']).toMatchObject([
{ tagName: 'DIV', textContent: 'Content' },
])

container.innerHTML = `<${ceTag}><div slot="slot2">Content</div></${ceTag}>`
await nextTick()
expect(Object.keys(slots!)).toHaveLength(1)
expect(slots!['slot2']).toMatchObject([
{ tagName: 'DIV', textContent: 'Content' },
])

container.innerHTML = `<${ceTag}><div>New Content</div><span>More Content</span><p slot="nonExisting">Even More</p></${ceTag}>`
await nextTick()
// The slot values provided were not defined as outlets by component
expect(Object.keys(slots!)).toHaveLength(0)
}

await testNamedSlots(true)
await testNamedSlots(false)
})
})
})

describe('expose', () => {
Expand Down
47 changes: 41 additions & 6 deletions packages/runtime-dom/src/apiCustomElement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,10 @@ export class VueElement
*/
private _childStyles?: Map<string, HTMLStyleElement[]>
private _ob?: MutationObserver | null = null
private _slots?: Record<string, Node[]>
_slots: Record<string, Node[]> = {}
// differs from `_slots` by only exposing slot values that actually have corresponding
// slot outlets defined by this component
_componentDefinedSlots: Record<string, Node[]> = {}

constructor(
/**
Expand Down Expand Up @@ -275,9 +278,13 @@ export class VueElement
// avoid resolving component if it's not connected
if (!this.isConnected) return

// avoid re-parsing slots if already resolved
if (!this.shadowRoot && !this._resolved) {
this._parseSlots()
if (this.shadowRoot) {
this._root.addEventListener('slotchange', this._slotChangeEventListener)
} else {
// avoid re-parsing slots if already resolved
if (!this._resolved) {
this._parseSlots()
}
}
this._connected = true

Expand Down Expand Up @@ -326,6 +333,18 @@ export class VueElement
}
}

_slotChangeEventListener = (event: Event): void => {
if (event.target instanceof HTMLSlotElement) {
const slotName = event.target.name || 'default'
const assignedNodes = event.target.assignedNodes()
if (!assignedNodes.length) {
delete this._componentDefinedSlots[slotName]
} else {
this._componentDefinedSlots[slotName] = assignedNodes
}
}
}

disconnectedCallback(): void {
this._connected = false
nextTick(() => {
Expand All @@ -334,6 +353,12 @@ export class VueElement
this._ob.disconnect()
this._ob = null
}
if (this.shadowRoot) {
this._root.removeEventListener(
'slotchange',
this._slotChangeEventListener,
)
}
// unmount
this._app && this._app.unmount()
if (this._instance) this._instance.ce = undefined
Expand Down Expand Up @@ -621,7 +646,7 @@ export class VueElement
* Only called when shadowRoot is false
*/
private _parseSlots() {
const slots: VueElement['_slots'] = (this._slots = {})
const slots: VueElement['_slots'] = this._slots
let n
while ((n = this.firstChild)) {
const slotName =
Expand All @@ -640,9 +665,10 @@ export class VueElement
for (let i = 0; i < outlets.length; i++) {
const o = outlets[i] as HTMLSlotElement
const slotName = o.getAttribute('name') || 'default'
const content = this._slots![slotName]
const content = this._slots[slotName]
const parent = o.parentNode!
if (content) {
this._componentDefinedSlots[slotName] = content
for (const n of content) {
// for :slotted css
if (scopeId && n.nodeType === 1) {
Expand Down Expand Up @@ -716,3 +742,12 @@ export function useShadowRoot(): ShadowRoot | null {
const el = __DEV__ ? useHost('useShadowRoot') : useHost()
return el && el.shadowRoot
}

/**
* Retrieve the nodes assigned to each `<slot>` of the current custom element.
* Only usable in setup() of a `defineCustomElement` component.
*/
export function useNativeSlots(): Record<string, Node[]> | null {
const el = __DEV__ ? useHost('useNativeSlots') : useHost()
return el && el._componentDefinedSlots
}
1 change: 1 addition & 0 deletions packages/runtime-dom/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,7 @@ export {
defineCustomElement,
defineSSRCustomElement,
useShadowRoot,
useNativeSlots,
useHost,
VueElement,
type VueElementConstructor,
Expand Down
Loading