Description
Describe the bug
When using shadowDOM, event are "retargeted" to hide the inner representation of the element.
Composed events dispatched from within a shadow root are retargeted, meaning that to any listener on an element hosting a shadow root or any of its ancestors, they appear to come from the hosting element.
from https://lit.dev/docs/components/events/#shadowdom-retargeting
I usually use retargeting to get the instance of the custom element (e.g. a card element) rather than the image or text element inside it. It allows having a single listener on the container when a huge number of elements is expected.
With Svelte 5 and the new on[event] syntax, the Event.target is not retargeted.
It was working with Svelte 4.
The issue can be circumvented by manually adding the event listener (see example code below).
Other issues related to the subject:
- Svelte 5: Incorrect
target
andcurrentTarget
when usingon:
directive #10215 - Svelte5: event.currentTarget always equals event.target #11328
Reproduction
Main Svelte file:
<script>
import {onMount} from "svelte";
import "./HelloWorld.js";
let elt1 = $state();
onMount(() => {
elt1.addEventListener("click", (e) => {
console.log(`addEL: ${e.target?.tagName}`); // HELLO-WORLD, as expected
});
});
function onclick(e) {
console.log(`onclick: ${e.target?.tagName}`); // SPAN, error!
}
</script>
<!-- svelte-ignore a11y_click_events_have_key_events -->
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div bind:this={elt1} {onclick}>
<hello-world></hello-world>
</div>
Custom element definition in HelloWorld.js:
class HelloWorld extends HTMLElement {
constructor() {
super();
this._shadowRoot = this.attachShadow({ mode: "open" });
}
connectedCallback() {
const text = document.createElement("span");
text.innerText="Hello world";
this._shadowRoot.appendChild(text);
}
}
if (window.customElements.get("hello-world") == undefined) {
window.customElements.define("hello-world", HelloWorld);
}
Logs
No response
System Info
REPL: Svelte compiler version 5.0.0-next.148
Severity
blocking an upgrade