Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,4 @@ jobs:
cache: 'yarn'
- run: yarn install --frozen-lockfile
- run: yarn test
- run: yarn tsc --noEmit
- run: yarn tsc --noEmit --emitDeclarationOnly false
137 changes: 137 additions & 0 deletions examples/property-binding.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
<!doctype html>
<html>
<head>
<meta charset='utf-8'>
<script crossorigin src='https://cdn.jsdelivr.net/npm/@webcomponents/[email protected]/custom-elements-es5-adapter.js'></script>
<script crossorigin src='https://cdn.jsdelivr.net/npm/@webcomponents/[email protected]/webcomponents-loader.js'></script>
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<script src='../dist/remount.es5.js'></script>
</head>
<body>
<h1>Web components test</h1>
<my-lit-element></my-lit-element>

<!-- Defines <my-react-element> -->
<script>
const h = React.createElement
/**
* Basic counter button that also calls the arbitrary callback function that was passed in
* and renders the complex data that was passed in, without needing to serialize
*/
function Counter({ count, complexData, arbitraryCallback }) {
React.useEffect(() => {
console.log('complex data received in React!', complexData)
}, [complexData])

const handleClick = () => {
console.log('handleClick from React')
arbitraryCallback();
}

return h('button', { onClick: () => handleClick() }, 'Count from React:', count, '')
}

Remount.define({
'my-react-element': Counter,
})
</script>

<!-- Defines <my-lit-element> -->
<script type="module">
import { LitElement, html } from 'https://cdn.skypack.dev/lit@2'

/**
* Basic example of usage of a LitElement, a close to native Web Components library maintained by Google.
* See more: https://lit.dev/docs/
*/
class ElementThatUsesWrappedReact extends LitElement {
static properties = {
name: { type: String },
count: { type: Number },
}

/**
* @override See: https://lit.dev/docs/api/LitElement/#LitElement.firstUpdated
*/
firstUpdated() {
this.name = 'World'
this.count = 0
}

_handleClick() {
console.log('handleClick from Lit!')
this.count += 1
}

render() {
return html`
<p>Hello, ${this.name}!</p>
<p>
In <a href="https://lit.dev/docs/">Lit</a>, the Property Expression (the <code>.props</code> part) is used to assign
<u>Properties</u> to an element, not to be confused with its <u>Attributes</u> (<a href="https://stackoverflow.com/q/6003819">there's a difference</a>).
</p>
<blockquote>
<span><a href="https://lit.dev/docs/templates/expressions/#property-expressions">Lit syntax</a>:</span><br />
<code>&lt;custom-element my-attr="123" .myProperty=\$\{123\}></custom-element></code>
</blockquote>
<p>
There are similar syntaxes in other web frameworks, such as:
</p>
<ul>
<li><a href="https://angular.io/guide/property-binding#binding-to-a-property">Angular</a>:</li>
<ul>
<li>
<code>&lt;img alt="item" [attr.title]="'Title ' + ' goes here'" [src]="itemImageUrl"></code>
</li>
<li>
<code>&lt;custom-element [attr.my-attr]="123" [myProperty]="123"></code>
</li>
</ul>
<li><a href="https://vuejs.org/guide/extras/web-components.html#using-custom-elements-in-vue">Vue.js</a></li>
<ul>
<li>
<code>&lt;my-element :user.prop="{ name: 'jack' }"></my-element></code>
</li>
<li>
<code>&lt;my-element .user="{ name: 'jack' }"></my-element></code>
</li>
<li>
<code>&lt;custom-element :my-attr="123" .myProperty="123"></my-element></code>
</li>
</ul>
<li><a href="https://github.com/facebook/react/issues/11347#top">React is expected to support assigning properties like attributes in the future, but for now you're limited to doing this:</a>
<ul>
<li>
<code>&lt;custom-element my-attr="123" ref={el => el.myProperty = 123;} /></code>
</li>
</ul>
</ul>
<p style="color: red; font-weight: bold;">Check the console!</p>
<button @click="${this._handleClick}">Count from Lit: ${this.count}</button>
<my-react-element .props=${{
count: this.count,
complexData: {
hello: 'world',
foo: [4, 5, 6],
bar: new Set([1,1,1,2,2,2,3,3,3]),
bazz: {
fizz: 99,
buzz: {
id: 11,
name: 'GitHub'
}
},
doc: document.querySelector('h1'),
doThing: () => alert(1)
},
arbitraryCallback: () => this._handleClick()
}}
></my-react-element>
`
}
}
customElements.define('my-lit-element', ElementThatUsesWrappedReact);
</script>
</body>
</html>
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@
"license": "MIT",
"main": "dist/remount.es5.js",
"module": "dist/remount.js",
"types": "dist/index.d.ts",
"peerDependencies": {
"react": ">= 18.0.0",
"react-dom": ">= 18.0.0"
Expand All @@ -70,6 +71,7 @@
},
"scripts": {
"build": "rollup --config",
"postbuild": "run-s tsc",
"prettier": "prettier '*.js' 'src/**/*.{js,ts}'",
"tsc": "tsc",
"jest": "jest",
Expand Down
9 changes: 8 additions & 1 deletion src/core.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
/** @typedef { import('./types').ElementSpec } ElementSpec */
/** @typedef { import('./types').PropertyMap } PropertyMap */
/** @typedef { import('./types').Strategy } Strategy */
/** @typedef { import('./types').ComponentElement } ComponentElement */

import * as CustomElementsStrategy from './strategies/custom_elements'
import * as MutationObserverStrategy from './strategies/mutation_observer'
Expand Down Expand Up @@ -137,7 +138,7 @@ function isElementSpec(spec) {
* Returns properties for a given HTML element.
*
* @private
* @param {HTMLElement} element
* @param {HTMLElement | ComponentElement} element
* @param {string[] | null | undefined} attributes
*
* @example
Expand All @@ -146,6 +147,12 @@ function isElementSpec(spec) {
*/

function getProps(element, attributes) {
// If the `props` property is present, get that
if('props' in element) {
return element.props
}

// If the props-json attribute is present, get that
const rawJson = element.getAttribute('props-json')
if (rawJson) {
return JSON.parse(rawJson)
Expand Down
12 changes: 12 additions & 0 deletions src/strategies/custom_elements.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,18 @@ export function defineElement(elSpec, elName, events) {
const attributes = elSpec.attributes || []

class ComponentElement extends HTMLElement {
_props = {}
get props() {
return this._props;
}
set props(p) {
this._props = p;
// only fire "onUpdate" if mountpoint is present
if (!!this._mountPoint) {
onUpdate(this, this._mountPoint);
}
}

static get observedAttributes() {
return ['props-json', ...attributes]
}
Expand Down
9 changes: 9 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
import React from 'react'

/**
* Excerpt from `custom_elements.js` to keep type safety
* @private
*/
export class ComponentElement extends HTMLElement {
_props: any = {};
props: any = {};
}

export type Component =
| React.ComponentClass<any, any>
| React.FunctionComponent<any>
Expand Down
11 changes: 10 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
{
"compilerOptions": {
// Types should go into this directory.
// Removing this would place the .d.ts files
// next to the .js files
"outDir": "dist",
// Generate d.ts files
"declaration": true,
// This compiler run should
// only output d.ts files
"emitDeclarationOnly": true,
"noEmit": false,
"target": "es5",
"lib": [
"dom",
Expand All @@ -16,7 +26,6 @@
"strict": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "preserve"
},
"include": [
Expand Down