From 280137ca972ad9e0a067bb6c18223613b863cd62 Mon Sep 17 00:00:00 2001 From: Shahar Talmi Date: Wed, 9 Oct 2024 01:43:45 +0300 Subject: [PATCH] adjusted implementation according to code review --- packages/core/src/core.ts | 31 +++++++++++++------ .../src/react-to-web-component.test.tsx | 3 +- 2 files changed, 23 insertions(+), 11 deletions(-) diff --git a/packages/core/src/core.ts b/packages/core/src/core.ts index a305d7c..a9def9b 100644 --- a/packages/core/src/core.ts +++ b/packages/core/src/core.ts @@ -6,8 +6,8 @@ type PropNames = Array> export interface R2WCOptions { shadow?: "open" | "closed" - dispatchEvents?: EventInit props?: PropNames | Partial, R2WCType>> + events?: Array | Partial> } export interface R2WCRenderer { @@ -46,12 +46,19 @@ export default function r2wc( ? (Object.keys(ReactComponent.propTypes) as PropNames) : [] } + if (!options.events) { + options.events = [] + } const propNames = Array.isArray(options.props) ? options.props.slice() : (Object.keys(options.props) as PropNames) + const eventNames = Array.isArray(options.events) + ? options.events.slice() + : Object.keys(options.events) const propTypes = {} as Partial, R2WCType>> + const eventParams = {} as Partial> const mapPropAttribute = {} as Record, string> const mapAttributeProp = {} as Record> for (const prop of propNames) { @@ -64,6 +71,11 @@ export default function r2wc( mapPropAttribute[prop] = attribute mapAttributeProp[attribute] = prop } + for (const event of eventNames) { + eventParams[event] = Array.isArray(options.events) + ? {} + : options.events[event] + } class ReactWebComponent extends HTMLElement { static get observedAttributes() { @@ -97,14 +109,15 @@ export default function r2wc( if (transform?.parse && value) { //@ts-ignore this[propsSymbol][prop] = transform.parse(value, attribute, this) - } else if (options.dispatchEvents && type === "function") { - //@ts-ignore - this[propsSymbol][prop] = (detail) => { - const name = prop.replace(/^on/, "").toLowerCase() - this.dispatchEvent( - new CustomEvent(name, { detail, ...options.dispatchEvents }), - ) - } + } + } + for (const event of eventNames) { + const prop = `on${event.charAt(0).toUpperCase()}${event.slice(1)}` + //@ts-ignore + this[propsSymbol][prop] = (detail) => { + this.dispatchEvent( + new CustomEvent(event, { detail, ...eventParams[event] }), + ) } } } diff --git a/packages/react-to-web-component/src/react-to-web-component.test.tsx b/packages/react-to-web-component/src/react-to-web-component.test.tsx index 03047d5..4f4cf93 100644 --- a/packages/react-to-web-component/src/react-to-web-component.test.tsx +++ b/packages/react-to-web-component/src/react-to-web-component.test.tsx @@ -340,8 +340,7 @@ describe("react-to-web-component 1", () => { } const WebThemeSelect = r2wc(ThemeSelect, { - props: { onSelect: "function" }, - dispatchEvents: { bubbles: true }, + events: { select: { bubbles: true } }, }) customElements.define("theme-select-events", WebThemeSelect) document.body.innerHTML = ""