@r2wc/react-to-web-component 1.0.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,129 @@
1
+ # React to Web Component
2
+
3
+ `@r2wc/react-to-web-component` converts [React](https://reactjs.org/) components to [custom elements](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements)! It lets you share React components as native elements that **don't** require mounted being through React. The custom element acts as a wrapper for the underlying React component. Use these custom elements with any project that uses HTML even in any framework (vue, svelte, angular, ember, canjs) the same way you would use standard HTML elements.
4
+
5
+ `@r2wc/react-to-web-component`:
6
+
7
+ - Works in all modern browsers. (Edge needs a [customElements polyfill](https://github.com/webcomponents/polyfills/tree/master/packages/custom-elements)).
8
+ - Is `1.11KB` minified and gzipped.
9
+
10
+ ## Need help or have questions?
11
+
12
+ This project is supported by [Bitovi, a React consultancy](https://www.bitovi.com/frontend-javascript-consulting/react-consulting). You can get help or ask questions on our:
13
+
14
+ - [Discord Community](https://discord.gg/J7ejFsZnJ4)
15
+ - [Twitter](https://twitter.com/bitovi)
16
+
17
+ Or, you can hire us for training, consulting, or development. [Set up a free consultation.](https://www.bitovi.com/frontend-javascript-consulting/react-consulting)
18
+
19
+ ## Basic Use
20
+
21
+ For basic usage, we will use this simple React component:
22
+
23
+ ```js
24
+ const Greeting = () => {
25
+ return <h1>Hello, World!</h1>
26
+ }
27
+ ```
28
+
29
+ With our React component complete, all we have to do is call `r2wc` and [customElements.define](https://developer.mozilla.org/en-US/docs/Web/API/CustomElementRegistry/define) to create and define our custom element:
30
+
31
+ ```js
32
+ import r2wc from "@r2wc/react-to-web-component"
33
+
34
+ const WebGreeting = r2wc(Greeting)
35
+
36
+ customElements.define("web-greeting", WebGreeting)
37
+ ```
38
+
39
+ Now we can use `<web-greeting>` like any other HTML element!
40
+
41
+ ```html
42
+ <body>
43
+ <h1>Greeting Demo</h1>
44
+
45
+ <web-greeting></web-greeting>
46
+ </body>
47
+ ```
48
+
49
+ Note that by using React 18, `r2wc` will use the new root API. If your application needs the legacy API, please use React 17
50
+
51
+ In the above case, the web-greeting custom element is not making use of the `name` property from our `Greeting` component.
52
+
53
+ ## Working with Attributes
54
+
55
+ By default, custom elements created by `r2wc` only pass properties to the underlying React component. To make attributes work, you must specify your component's props.
56
+
57
+ ```js
58
+ const Greeting = ({ name }) => {
59
+ return <h1>Hello, {name}!</h1>
60
+ }
61
+
62
+ const WebGreeting = r2wc(Greeting, {
63
+ props: {
64
+ name: "string",
65
+ },
66
+ })
67
+ ```
68
+
69
+ Now `r2wc` will know to look for `name` attributes
70
+ as follows:
71
+
72
+ ```html
73
+ <body>
74
+ <h1>Greeting Demo</h1>
75
+
76
+ <web-greeting name="Justin"></web-greeting>
77
+ </body>
78
+ ```
79
+
80
+ For projects needing more advanced usage of the web components, see our [programatic usage and declarative demos](docs/programatic-usage.md).
81
+
82
+ We also have a [complete example using a third party library](docs/complete-example.md).
83
+
84
+ ## Setup
85
+
86
+ To install from npm:
87
+
88
+ ```
89
+ npm install @r2wc/react-to-web-component
90
+ ```
91
+
92
+ ## External Examples
93
+
94
+ Greeting example in a [CodePen](https://codepen.io/bavinedwards/pen/jOveaGm)
95
+
96
+ Greeting example in [CodeSandbox](https://codesandbox.io/s/sample-greeting-app-ts-qwidh9)
97
+
98
+ Hello, world example (React17) in [CodeSandbox](https://codesandbox.io/s/hello-world-react17-u4l3x1)
99
+
100
+ Example with all prop types in [CodeSandbox](https://codesandbox.io/p/sandbox/vite-example-with-numerous-types-gjf87o)
101
+
102
+ R2WC With Vite Header Example in [CodeSandbox](https://codesandbox.io/p/sandbox/header-example-e4x25q)
103
+
104
+ ## External Blog Posts
105
+
106
+ R2WC with Vite [View Post](https://www.bitovi.com/blog/react-everywhere-with-vite-and-react-to-webcomponent)
107
+
108
+ R2WC with Create React App (CRA) [View Post](https://www.bitovi.com/blog/how-to-create-a-web-component-with-create-react-app)
109
+
110
+ ## How it works
111
+
112
+ Check out our [full API documentation](../../docs/api.md).
113
+
114
+ `r2wc` creates a constructor function whose prototype is a [Proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy). This acts as a trap for any property set on instances of the custom element. When a property is set, the proxy:
115
+
116
+ - re-renders the React component inside the custom element.
117
+ - creates an enumerable getter / setter on the instance
118
+ to save the set value and avoid hitting the proxy in the future.
119
+
120
+ Also:
121
+
122
+ - Enumerable properties and values on the custom element are used as the `props` passed to the React component.
123
+ - The React component is not rendered until the custom element is inserted into the page.
124
+
125
+ # We want to hear from you.
126
+
127
+ Come chat with us about open source in our Bitovi community [Discord](https://discord.gg/J7ejFsZnJ4).
128
+
129
+ See what we're up to by following us on [Twitter](https://twitter.com/bitovi).
@@ -0,0 +1 @@
1
+ "use strict";const k=require("/home/runner/work/react-to-web-component/react-to-web-component/node_modules/react/index.js"),A=require("/home/runner/work/react-to-web-component/react-to-web-component/node_modules/react-dom/index.js");var v=Object.defineProperty,C=(t,e,n)=>e in t?v(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,l=(t,e,n)=>(C(t,typeof e!="symbol"?e+"":e,n),n);const x={stringify:t=>t,parse:t=>t},N={stringify:t=>`${t}`,parse:t=>parseFloat(t)},T={stringify:t=>t?"true":"false",parse:t=>/^[ty1-9]/i.test(t)},$={stringify:t=>t.name,parse:(t,e)=>{const n=(()=>{if(typeof window<"u"&&t in window)return window[t];if(typeof global<"u"&&t in global)return global[t]})();return typeof n=="function"?n.bind(e):void 0}},E={stringify:t=>JSON.stringify(t),parse:t=>JSON.parse(t)},m={string:x,number:N,boolean:T,function:$,json:E},w=Symbol.for("r2wc.render"),b=Symbol.for("r2wc.connected"),u=Symbol.for("r2wc.context"),i=Symbol.for("r2wc.props");function L(t,e,n){var a,O,S;e.props||(e.props=t.propTypes?Object.keys(t.propTypes):[]);const y=(Array.isArray(e.props)?e.props.slice():Object.keys(e.props)).filter(r=>r!=="container"),p={},d={},g={};for(const r of y){p[r]=Array.isArray(e.props)?"string":e.props[r];const s=P(r);d[r]=s,g[s]=r}class j extends HTMLElement{constructor(){super(),l(this,a,!0),l(this,O),l(this,S,{}),l(this,"container"),e.shadow?this.container=this.attachShadow({mode:e.shadow}):this.container=this,this[i].container=this.container;for(const s of y){const f=d[s],c=this.getAttribute(f),o=p[s];c&&(this[i][s]=m[o].parse(c,this))}}static get observedAttributes(){return Object.keys(g)}connectedCallback(){this[b]=!0,this[w]()}disconnectedCallback(){this[b]=!1,this[u]&&n.unmount(this[u])}attributeChangedCallback(s,f,c){const o=g[s],h=p[o];o in p&&(this[i][o]=m[h].parse(c,this),this[w]())}[(a=b,O=u,S=i,w)](){this[b]&&(this[u]?n.update(this[u],this[i]):this[u]=n.mount(this.container,t,this[i]))}}for(const r of y){const s=d[r],f=p[r];Object.defineProperty(j.prototype,r,{enumerable:!0,configurable:!0,get(){return this[i][r]},set(c){this[i][r]=c;const o=m[f].stringify;if(o){const h=o(c);this.getAttribute(s)!==h&&this.setAttribute(s,h)}}})}return j}function P(t=""){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}function q(t,e,n){const a=k.createElement(e,n);return A.render(a,t),{container:t,ReactComponent:e}}function J({container:t,ReactComponent:e},n){const a=k.createElement(e,n);A.render(a,t)}function M({container:t}){A.unmountComponentAtNode(t)}function z(t,e={}){return L(t,e,{mount:q,update:J,unmount:M})}module.exports=z;
@@ -0,0 +1,3 @@
1
+ import type { R2WCOptions } from "@r2wc/core";
2
+ import React from "react";
3
+ export default function r2wc<Props extends object>(ReactComponent: React.ComponentType<Props>, options?: R2WCOptions<Props>): CustomElementConstructor;
@@ -0,0 +1,116 @@
1
+ import k from "/home/runner/work/react-to-web-component/react-to-web-component/node_modules/react/index.js";
2
+ import A from "/home/runner/work/react-to-web-component/react-to-web-component/node_modules/react-dom/index.js";
3
+ var v = Object.defineProperty, C = (t, e, n) => e in t ? v(t, e, { enumerable: !0, configurable: !0, writable: !0, value: n }) : t[e] = n, l = (t, e, n) => (C(t, typeof e != "symbol" ? e + "" : e, n), n);
4
+ const x = {
5
+ stringify: (t) => t,
6
+ parse: (t) => t
7
+ }, N = {
8
+ stringify: (t) => `${t}`,
9
+ parse: (t) => parseFloat(t)
10
+ }, T = {
11
+ stringify: (t) => t ? "true" : "false",
12
+ parse: (t) => /^[ty1-9]/i.test(t)
13
+ }, $ = {
14
+ stringify: (t) => t.name,
15
+ parse: (t, e) => {
16
+ const n = (() => {
17
+ if (typeof window < "u" && t in window)
18
+ return window[t];
19
+ if (typeof global < "u" && t in global)
20
+ return global[t];
21
+ })();
22
+ return typeof n == "function" ? n.bind(e) : void 0;
23
+ }
24
+ }, E = {
25
+ stringify: (t) => JSON.stringify(t),
26
+ parse: (t) => JSON.parse(t)
27
+ }, g = {
28
+ string: x,
29
+ number: N,
30
+ boolean: T,
31
+ function: $,
32
+ json: E
33
+ }, w = Symbol.for("r2wc.render"), b = Symbol.for("r2wc.connected"), p = Symbol.for("r2wc.context"), i = Symbol.for("r2wc.props");
34
+ function L(t, e, n) {
35
+ var c, O, S;
36
+ e.props || (e.props = t.propTypes ? Object.keys(t.propTypes) : []);
37
+ const y = (Array.isArray(e.props) ? e.props.slice() : Object.keys(e.props)).filter((r) => r !== "container"), u = {}, d = {}, m = {};
38
+ for (const r of y) {
39
+ u[r] = Array.isArray(e.props) ? "string" : e.props[r];
40
+ const o = P(r);
41
+ d[r] = o, m[o] = r;
42
+ }
43
+ class j extends HTMLElement {
44
+ constructor() {
45
+ super(), l(this, c, !0), l(this, O), l(this, S, {}), l(this, "container"), e.shadow ? this.container = this.attachShadow({
46
+ mode: e.shadow
47
+ }) : this.container = this, this[i].container = this.container;
48
+ for (const o of y) {
49
+ const f = d[o], a = this.getAttribute(f), s = u[o];
50
+ a && (this[i][o] = g[s].parse(a, this));
51
+ }
52
+ }
53
+ static get observedAttributes() {
54
+ return Object.keys(m);
55
+ }
56
+ connectedCallback() {
57
+ this[b] = !0, this[w]();
58
+ }
59
+ disconnectedCallback() {
60
+ this[b] = !1, this[p] && n.unmount(this[p]);
61
+ }
62
+ attributeChangedCallback(o, f, a) {
63
+ const s = m[o], h = u[s];
64
+ s in u && (this[i][s] = g[h].parse(a, this), this[w]());
65
+ }
66
+ [(c = b, O = p, S = i, w)]() {
67
+ this[b] && (this[p] ? n.update(this[p], this[i]) : this[p] = n.mount(
68
+ this.container,
69
+ t,
70
+ this[i]
71
+ ));
72
+ }
73
+ }
74
+ for (const r of y) {
75
+ const o = d[r], f = u[r];
76
+ Object.defineProperty(j.prototype, r, {
77
+ enumerable: !0,
78
+ configurable: !0,
79
+ get() {
80
+ return this[i][r];
81
+ },
82
+ set(a) {
83
+ this[i][r] = a;
84
+ const s = g[f].stringify;
85
+ if (s) {
86
+ const h = s(a);
87
+ this.getAttribute(o) !== h && this.setAttribute(o, h);
88
+ }
89
+ }
90
+ });
91
+ }
92
+ return j;
93
+ }
94
+ function P(t = "") {
95
+ return t.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
96
+ }
97
+ function J(t, e, n) {
98
+ const c = k.createElement(e, n);
99
+ return A.render(c, t), {
100
+ container: t,
101
+ ReactComponent: e
102
+ };
103
+ }
104
+ function M({ container: t, ReactComponent: e }, n) {
105
+ const c = k.createElement(e, n);
106
+ A.render(c, t);
107
+ }
108
+ function z({ container: t }) {
109
+ A.unmountComponentAtNode(t);
110
+ }
111
+ function H(t, e = {}) {
112
+ return L(t, e, { mount: J, update: M, unmount: z });
113
+ }
114
+ export {
115
+ H as default
116
+ };
package/package.json ADDED
@@ -0,0 +1,59 @@
1
+ {
2
+ "name": "@r2wc/react-to-web-component",
3
+ "version": "1.0.0-alpha.1",
4
+ "description": "Convert React components to native Web Components.",
5
+ "homepage": "https://www.bitovi.com/frontend-javascript-consulting/react-consulting",
6
+ "author": "Bitovi",
7
+ "license": "MIT",
8
+ "keywords": [
9
+ "React",
10
+ "Web Component"
11
+ ],
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/bitovi/react-to-webcomponent.git"
15
+ },
16
+ "type": "module",
17
+ "main": "./dist/react-to-web-component.cjs",
18
+ "module": "./dist/react-to-web-component.js",
19
+ "types": "./dist/react-to-web-component.d.ts",
20
+ "exports": {
21
+ ".": {
22
+ "require": "./dist/react-to-web-component.cjs",
23
+ "import": "./dist/react-to-web-component.js",
24
+ "types": "./dist/react-to-web-component.d.ts"
25
+ },
26
+ "./package.json": "./package.json"
27
+ },
28
+ "files": [
29
+ "dist",
30
+ "src"
31
+ ],
32
+ "scripts": {
33
+ "typecheck": "tsc --noEmit",
34
+ "eslint": "eslint vite.config.ts src",
35
+ "prettier": "prettier --check vite.config.ts src",
36
+ "depcheck": "depcheck .",
37
+ "dev": "vite",
38
+ "test": "vitest",
39
+ "test:ci": "vitest run",
40
+ "test:coverage": "vitest run --coverage",
41
+ "clean": "rm -rf tsconfig.tsbuildinfo dist",
42
+ "build": "vite build"
43
+ },
44
+ "dependencies": {
45
+ "@r2wc/core": "^1.0.0-alpha.0"
46
+ },
47
+ "devDependencies": {
48
+ "@testing-library/jest-dom": "^5.16.5",
49
+ "@types/react": "^17.0.0",
50
+ "@types/react-dom": "^17.0.0",
51
+ "vite": "^4.3.1",
52
+ "vite-plugin-dts": "^2.3.0",
53
+ "vitest": "^0.30.1"
54
+ },
55
+ "peerDependencies": {
56
+ "react": "^16.0.0 || ^17.0.0",
57
+ "react-dom": "^16.0.0 || ^17.0.0"
58
+ }
59
+ }
@@ -0,0 +1,261 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2
+ import { describe, it, expect, assert } from "vitest"
3
+ import matchers from "@testing-library/jest-dom/matchers"
4
+
5
+ import r2wc from "./react-to-web-component"
6
+
7
+ expect.extend(matchers)
8
+
9
+ function flushPromises() {
10
+ return new Promise((resolve) => setImmediate(resolve))
11
+ }
12
+
13
+ const Greeting: React.FC<{ name: string }> = ({ name }) => (
14
+ <h1>Hello, {name}</h1>
15
+ )
16
+
17
+ describe("react-to-web-component", () => {
18
+ it("basics with react", () => {
19
+ const MyWelcome = r2wc(Greeting)
20
+ customElements.define("my-welcome", MyWelcome)
21
+
22
+ const myWelcome = new MyWelcome()
23
+
24
+ document.getElementsByTagName("body")[0].appendChild(myWelcome)
25
+
26
+ expect(myWelcome.nodeName).toEqual("MY-WELCOME")
27
+ })
28
+
29
+ it("works with shadow DOM `options.shadow === 'open'`", async () => {
30
+ expect.assertions(5)
31
+
32
+ const MyWelcome = r2wc(Greeting, {
33
+ shadow: "open",
34
+ })
35
+
36
+ customElements.define("my-shadow-welcome", MyWelcome)
37
+
38
+ const body = document.body
39
+ const myWelcome = new MyWelcome() as HTMLElement & { name: string }
40
+ body.appendChild(myWelcome)
41
+
42
+ await flushPromises()
43
+
44
+ expect(myWelcome.shadowRoot).not.toEqual(undefined)
45
+ expect(myWelcome.shadowRoot?.children.length).toEqual(1)
46
+
47
+ const child = myWelcome.shadowRoot?.childNodes[0] as HTMLElement
48
+
49
+ expect(child.tagName).toEqual("H1")
50
+ expect(child.innerHTML).toEqual("Hello, ")
51
+
52
+ myWelcome.name = "Justin"
53
+
54
+ await flushPromises()
55
+
56
+ expect(child.innerHTML, "Hello, Justin")
57
+ })
58
+
59
+ it('It works without shadow option set to "true"', async () => {
60
+ expect.assertions(1)
61
+
62
+ const MyWelcome = r2wc(Greeting)
63
+
64
+ customElements.define("my-noshadow-welcome", MyWelcome)
65
+
66
+ const body = document.body
67
+
68
+ const myWelcome = new MyWelcome()
69
+ body.appendChild(myWelcome)
70
+
71
+ await new Promise((resolve) => {
72
+ setTimeout(() => {
73
+ expect(myWelcome.shadowRoot).toEqual(null)
74
+ resolve(true)
75
+ }, 0)
76
+ })
77
+ })
78
+
79
+ it("It converts dashed-attributes to camelCase", async () => {
80
+ expect.assertions(1)
81
+
82
+ const CamelCaseGreeting = ({
83
+ camelCaseName,
84
+ }: {
85
+ camelCaseName: string
86
+ }) => <h1>Hello, {camelCaseName}</h1>
87
+
88
+ const MyGreeting = r2wc(CamelCaseGreeting, { props: ["camelCaseName"] })
89
+
90
+ customElements.define("my-dashed-style-greeting", MyGreeting)
91
+
92
+ const body = document.body
93
+
94
+ console.error = function (...messages) {
95
+ assert.ok(
96
+ messages.some((message) => message.includes("required")),
97
+ "got a warning with required",
98
+ )
99
+ }
100
+
101
+ body.innerHTML =
102
+ "<my-dashed-style-greeting camel-case-name='Christopher'></my-dashed-style-greeting>"
103
+
104
+ await flushPromises()
105
+
106
+ expect(body.firstElementChild?.innerHTML).toEqual(
107
+ "<h1>Hello, Christopher</h1>",
108
+ )
109
+ })
110
+
111
+ it("options.props can specify and will convert the String attribute value into Number, Boolean, Array, and/or Object", async () => {
112
+ expect.assertions(12)
113
+
114
+ type CastinProps = {
115
+ stringProp: string
116
+ numProp: number
117
+ floatProp: number
118
+ trueProp: boolean
119
+ falseProp: boolean
120
+ arrayProp: any[]
121
+ objProp: object
122
+ }
123
+
124
+ const global = window as any
125
+
126
+ function OptionsPropsTypeCasting({
127
+ stringProp,
128
+ numProp,
129
+ floatProp,
130
+ trueProp,
131
+ falseProp,
132
+ arrayProp,
133
+ objProp,
134
+ }: CastinProps) {
135
+ global.castedValues = {
136
+ stringProp,
137
+ numProp,
138
+ floatProp,
139
+ trueProp,
140
+ falseProp,
141
+ arrayProp,
142
+ objProp,
143
+ }
144
+
145
+ return <h1>{stringProp}</h1>
146
+ }
147
+
148
+ const WebOptionsPropsTypeCasting = r2wc(OptionsPropsTypeCasting, {
149
+ props: {
150
+ stringProp: "string",
151
+ numProp: "number",
152
+ floatProp: "number",
153
+ trueProp: "boolean",
154
+ falseProp: "boolean",
155
+ arrayProp: "json",
156
+ objProp: "json",
157
+ },
158
+ })
159
+
160
+ customElements.define("attr-type-casting", WebOptionsPropsTypeCasting)
161
+
162
+ const body = document.body
163
+
164
+ console.error = function (...messages) {
165
+ // propTypes will throw if any of the types passed into the underlying react component are wrong or missing
166
+ expect("propTypes should not have thrown").toEqual(messages.join(""))
167
+ }
168
+
169
+ body.innerHTML = `
170
+ <attr-type-casting
171
+ string-prop="iloveyou"
172
+ num-prop="360"
173
+ float-prop="0.5"
174
+ true-prop="true"
175
+ false-prop="false"
176
+ array-prop='[true, 100.25, "👽", { "aliens": "welcome" }]'
177
+ obj-prop='{ "very": "object", "such": "wow!" }'
178
+ ></attr-type-casting>
179
+ `
180
+
181
+ await flushPromises()
182
+ const {
183
+ stringProp,
184
+ numProp,
185
+ floatProp,
186
+ trueProp,
187
+ falseProp,
188
+ arrayProp,
189
+ objProp,
190
+ } = global.castedValues
191
+ expect(stringProp).toEqual("iloveyou")
192
+ expect(numProp).toEqual(360)
193
+ expect(floatProp).toEqual(0.5)
194
+ expect(trueProp).toEqual(true)
195
+ expect(falseProp).toEqual(false)
196
+ expect(arrayProp.length).toEqual(4)
197
+ expect(arrayProp[0]).toEqual(true)
198
+ expect(arrayProp[1]).toEqual(100.25)
199
+ expect(arrayProp[2]).toEqual("👽")
200
+ expect(arrayProp[3].aliens).toEqual("welcome")
201
+ expect(objProp.very).toEqual("object")
202
+ expect(objProp.such).toEqual("wow!")
203
+ })
204
+
205
+ it("Props typed as Function convert the string value of attribute into global fn calls bound to the webcomponent instance", async () => {
206
+ expect.assertions(2)
207
+
208
+ const global = window as any
209
+
210
+ function ThemeSelect({
211
+ handleClick,
212
+ }: {
213
+ handleClick: (arg: string) => void
214
+ }) {
215
+ return (
216
+ <div>
217
+ <button onClick={() => handleClick("V")}>V</button>
218
+ <button onClick={() => handleClick("Johnny")}>Johnny</button>
219
+ <button onClick={() => handleClick("Jane")}>Jane</button>
220
+ </div>
221
+ )
222
+ }
223
+
224
+ const WebThemeSelect = r2wc(ThemeSelect, {
225
+ props: {
226
+ handleClick: "function",
227
+ },
228
+ })
229
+
230
+ customElements.define("theme-select", WebThemeSelect)
231
+
232
+ const body = document.body
233
+
234
+ await new Promise((r) => {
235
+ const failUnlessCleared = setTimeout(() => {
236
+ delete global.globalFn
237
+ expect("globalFn was not called to clear the failure timeout").toEqual(
238
+ "not to fail because globalFn should have been called to clear the failure timeout",
239
+ )
240
+ r(true)
241
+ }, 1000)
242
+
243
+ global.globalFn = function (selected: string) {
244
+ delete global.globalFn
245
+ clearTimeout(failUnlessCleared)
246
+ expect(selected).toEqual("Jane")
247
+ expect(this).toEqual(document.querySelector("theme-select"))
248
+ r(true)
249
+ }
250
+
251
+ body.innerHTML = "<theme-select handle-click='globalFn'></theme-select>"
252
+
253
+ setTimeout(() => {
254
+ const button = document.querySelector(
255
+ "theme-select button:last-child",
256
+ ) as HTMLButtonElement
257
+ button.click()
258
+ }, 0)
259
+ })
260
+ })
261
+ })
@@ -0,0 +1,46 @@
1
+ import type { R2WCOptions } from "@r2wc/core"
2
+
3
+ import React from "react"
4
+ import ReactDOM from "react-dom"
5
+
6
+ import r2wcCore from "@r2wc/core"
7
+
8
+ interface Context<Props extends object> {
9
+ container: HTMLElement
10
+ ReactComponent: React.ComponentType<Props>
11
+ }
12
+
13
+ function mount<Props extends object>(
14
+ container: HTMLElement,
15
+ ReactComponent: React.ComponentType<Props>,
16
+ props: Props,
17
+ ): Context<Props> {
18
+ const element = React.createElement(ReactComponent, props)
19
+
20
+ ReactDOM.render(element, container)
21
+
22
+ return {
23
+ container,
24
+ ReactComponent,
25
+ }
26
+ }
27
+
28
+ function update<Props extends object>(
29
+ { container, ReactComponent }: Context<Props>,
30
+ props: Props,
31
+ ): void {
32
+ const element = React.createElement(ReactComponent, props)
33
+
34
+ ReactDOM.render(element, container)
35
+ }
36
+
37
+ function unmount<Props extends object>({ container }: Context<Props>): void {
38
+ ReactDOM.unmountComponentAtNode(container)
39
+ }
40
+
41
+ export default function r2wc<Props extends object>(
42
+ ReactComponent: React.ComponentType<Props>,
43
+ options: R2WCOptions<Props> = {},
44
+ ): CustomElementConstructor {
45
+ return r2wcCore(ReactComponent, options, { mount, update, unmount })
46
+ }