salesforce / lwc

⚡️ LWC - A Blazing Fast, Enterprise-Grade Web Components Foundation
https://lwc.dev
Other
1.63k stars 393 forks source link

Show compiler warning/error for `slot` attribute not at the top level #4703

Open nolanlawson opened 16 hours ago

nolanlawson commented 16 hours ago
    <x-inner>
        <div>
            <span slot="foo">I am the foo slot</span>
        </div>
    </x-inner>

In the case above, the developer is probably confused because they seem to be trying to slot something into the foo slot of <x-inner>, but since it's inside a <div>, the whole<div> is actually treated as the default slotted content, and the slot attribute is effectively ignored. This works in all three of native shadow, synthetic shadow, and light DOM slots.

There are valid cases where it's not at the top level, e.g.:

    <x-inner>
        <template lwc:if={isTrue}>
            <span slot="foo">I am the foo slot</span>
        </template>
    </x-inner>

In this case, the <span> would truly go into the foo slot since the <template lwc:if> is not a "real" element.

We should enumerate all the cases where the slot attribute is valid or invalid when not at the top level and warn for it. Potentially in the future we could even throw an error to be more explicit.

nolanlawson commented 16 hours ago

Doing a warning here is up for grabs, but doing an error is trickier so would probably have to be done with API versioning.

nolanlawson commented 15 hours ago

The full list of Node types is here:

https://github.com/salesforce/lwc/blob/e337b3ccbe74fd7ed744453770f97633a51318e9/packages/%40lwc/template-compiler/src/shared/types.ts#L321-L331

Off the top of my head, the ones that are "valid" to have between the component (<x-inner> above) and the element with the slot attribute are If, IfBlock, ElseifBlock, ElseBlock. For ForBlock and ScopedSlotFragment I'm not sure.

cardoso commented 11 hours ago

@nolanlawson this warning would need to be ignored here due to fixtures added in #4689 right?

https://github.com/salesforce/lwc/blob/cd41384f631c2223023c8228af8a964364513477/packages/%40lwc/engine-server/src/__tests__/fixtures.spec.ts#L57-L66

Example:

https://github.com/salesforce/lwc/blob/cd41384f631c2223023c8228af8a964364513477/packages/%40lwc/engine-server/src/__tests__/fixtures/slot-not-at-top-level/element/shadow/expected.html#L15-L19