2021-12-31 01:16:11 +03:00
|
|
|
/**
|
|
|
|
* @license
|
|
|
|
* Copyright 2021 Google LLC
|
|
|
|
* SPDX-License-Identifier: Apache-2.0
|
|
|
|
*/
|
|
|
|
|
|
|
|
/**
|
2022-03-22 00:44:00 +03:00
|
|
|
* Re-dispatches an event from the provided element.
|
2021-12-31 01:16:11 +03:00
|
|
|
*
|
|
|
|
* This function is useful for forwarding non-composed events, such as `change`
|
|
|
|
* events.
|
|
|
|
*
|
|
|
|
* @example
|
|
|
|
* class MyInput extends LitElement {
|
|
|
|
* render() {
|
|
|
|
* return html`<input @change=${this.redispatchEvent}>`;
|
|
|
|
* }
|
|
|
|
*
|
2022-03-22 00:44:00 +03:00
|
|
|
* protected redispatchEvent(event: Event) {
|
|
|
|
* redispatchEvent(this, event);
|
|
|
|
* }
|
2021-12-31 01:16:11 +03:00
|
|
|
* }
|
|
|
|
*
|
2022-03-22 00:44:00 +03:00
|
|
|
* @param element The element to dispatch the event from.
|
2021-12-31 01:16:11 +03:00
|
|
|
* @param event The event to re-dispatch.
|
|
|
|
* @return Whether or not the event was dispatched (if cancelable).
|
|
|
|
*/
|
2022-03-22 00:44:00 +03:00
|
|
|
export function redispatchEvent(element: Element, event: Event) {
|
2021-12-31 01:16:11 +03:00
|
|
|
// For bubbling events in SSR light DOM (or composed), stop their propagation
|
|
|
|
// and dispatch the copy.
|
2022-03-22 00:44:00 +03:00
|
|
|
if (event.bubbles && (!element.shadowRoot || event.composed)) {
|
2021-12-31 01:16:11 +03:00
|
|
|
event.stopPropagation();
|
|
|
|
}
|
|
|
|
|
|
|
|
const copy = Reflect.construct(event.constructor, [event.type, event]);
|
2022-03-22 00:44:00 +03:00
|
|
|
const dispatched = element.dispatchEvent(copy);
|
2021-12-31 01:16:11 +03:00
|
|
|
if (!dispatched) {
|
|
|
|
event.preventDefault();
|
|
|
|
}
|
|
|
|
|
|
|
|
return dispatched;
|
|
|
|
}
|