|
| 1 | +/* eslint-disable @typescript-eslint/no-explicit-any */ |
| 2 | +import React from "react" |
| 3 | + |
| 4 | +const renderSymbol = Symbol.for("r2wc.reactRender") |
| 5 | +const shouldRenderSymbol = Symbol.for("r2wc.shouldRender") |
| 6 | + |
| 7 | +function toDashedStyle(camelCase = "") { |
| 8 | + return camelCase.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase() |
| 9 | +} |
| 10 | + |
| 11 | +function isAllCaps(word: string) { |
| 12 | + return word.split("").every((c: string) => c.toUpperCase() === c) |
| 13 | +} |
| 14 | + |
| 15 | +function flattenIfOne(arr: object) { |
| 16 | + if (!Array.isArray(arr)) { |
| 17 | + return arr |
| 18 | + } |
| 19 | + if (arr.length === 1) { |
| 20 | + return arr[0] |
| 21 | + } |
| 22 | + return arr |
| 23 | +} |
| 24 | + |
| 25 | +function mapChildren(node: Element) { |
| 26 | + if (node.nodeType === Node.TEXT_NODE) { |
| 27 | + return node.textContent?.toString() |
| 28 | + } |
| 29 | + |
| 30 | + const arr = Array.from(node.childNodes as unknown as Element[]).map( |
| 31 | + (c: Element) => { |
| 32 | + if (c.nodeType === Node.TEXT_NODE) { |
| 33 | + return c.textContent?.toString() |
| 34 | + } |
| 35 | + // BR = br, ReactElement = ReactElement |
| 36 | + const nodeName = isAllCaps(c.nodeName) |
| 37 | + ? c.nodeName.toLowerCase() |
| 38 | + : c.nodeName |
| 39 | + const children = flattenIfOne(mapChildren(c)) |
| 40 | + |
| 41 | + // we need to format c.attributes before passing it to createElement |
| 42 | + const attributes: Record<string, string | null> = {} |
| 43 | + for (const attr of c.getAttributeNames()) { |
| 44 | + attributes[attr] = c.getAttribute(attr) |
| 45 | + } |
| 46 | + |
| 47 | + return React.createElement(nodeName, attributes, children) |
| 48 | + }, |
| 49 | + ) |
| 50 | + |
| 51 | + return flattenIfOne(arr) |
| 52 | +} |
| 53 | + |
| 54 | +const define = { |
| 55 | + // Creates a getter/setter that re-renders everytime a property is set. |
| 56 | + expando: function ( |
| 57 | + receiver: Record<typeof renderSymbol, any>, |
| 58 | + key: string, |
| 59 | + value: unknown, |
| 60 | + ) { |
| 61 | + Object.defineProperty(receiver, key, { |
| 62 | + enumerable: true, |
| 63 | + get: function () { |
| 64 | + return value |
| 65 | + }, |
| 66 | + set: function (newValue) { |
| 67 | + value = newValue |
| 68 | + this[renderSymbol]() |
| 69 | + }, |
| 70 | + }) |
| 71 | + receiver[renderSymbol]() |
| 72 | + }, |
| 73 | +} |
| 74 | + |
| 75 | +/** |
| 76 | + * Converts a React component into a webcomponent by wrapping it in a Proxy object. |
| 77 | + * @param {ReactComponent} |
| 78 | + * @param {Object} config - Optional parameters |
| 79 | + * @param {String?} config.shadow - Shadow DOM mode as either open or closed. |
| 80 | + * @param {Object|Array?} config.props - Array of camelCasedProps to watch as Strings or { [camelCasedProp]: String | Number | Boolean | Function | Object | Array } |
| 81 | + */ |
| 82 | +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types |
| 83 | +export default function ( |
| 84 | + ReactComponent: FC<any> | ComponentClass<any>, |
| 85 | + config: R2WCOptions = {}, |
| 86 | + renderer: Renderer<ReturnType<typeof React.createElement>>, |
| 87 | +): CustomElementConstructor { |
| 88 | + const propTypes: Record<string, any> = {} // { [camelCasedProp]: String | Number | Boolean | Function | Object | Array } |
| 89 | + const propAttrMap: Record<string, any> = {} // @TODO: add option to specify for asymetric mapping (eg "className" from "class") |
| 90 | + const attrPropMap: Record<string, any> = {} // cached inverse of propAttrMap |
| 91 | + |
| 92 | + if (!config.props) { |
| 93 | + config.props = ReactComponent.propTypes |
| 94 | + ? Object.keys(ReactComponent.propTypes) |
| 95 | + : [] |
| 96 | + } |
| 97 | + |
| 98 | + const propKeys = Array.isArray(config.props) |
| 99 | + ? config.props.slice() |
| 100 | + : Object.keys(config.props) |
| 101 | + |
| 102 | + propKeys.forEach((key) => { |
| 103 | + propTypes[key] = Array.isArray(config.props) ? String : config.props?.[key] |
| 104 | + propAttrMap[key] = toDashedStyle(key) |
| 105 | + attrPropMap[propAttrMap[key]] = key |
| 106 | + }) |
| 107 | + const renderAddedProperties: Record<string, boolean> = { |
| 108 | + isConnected: "isConnected" in HTMLElement.prototype, |
| 109 | + } |
| 110 | + let rendering = false |
| 111 | + // Create the web component "class" |
| 112 | + const WebComponent = function (this: any, ...args: any[]) { |
| 113 | + const self: HTMLElement = Reflect.construct( |
| 114 | + HTMLElement, |
| 115 | + args, |
| 116 | + this.constructor, |
| 117 | + ) |
| 118 | + if (typeof config.shadow === "string") { |
| 119 | + self.attachShadow({ mode: config.shadow } as ShadowRoot) |
| 120 | + } else if (config.shadow) { |
| 121 | + console.warn( |
| 122 | + 'Specifying the "shadow" option as a boolean is deprecated and will be removed in a future version.', |
| 123 | + ) |
| 124 | + self.attachShadow({ mode: "open" }) |
| 125 | + } |
| 126 | + return self |
| 127 | + } |
| 128 | + |
| 129 | + // Make the class extend HTMLElement |
| 130 | + const targetPrototype = Object.create(HTMLElement.prototype) |
| 131 | + targetPrototype.constructor = WebComponent |
| 132 | + |
| 133 | + // But have that prototype be wrapped in a proxy. |
| 134 | + const proxyPrototype = new Proxy(targetPrototype, { |
| 135 | + has: function (target, key) { |
| 136 | + return key in propTypes || key in targetPrototype |
| 137 | + }, |
| 138 | + |
| 139 | + // when any undefined property is set, create a getter/setter that re-renders |
| 140 | + set: function (target, key, value, receiver) { |
| 141 | + if (rendering) { |
| 142 | + renderAddedProperties[key as string] = true |
| 143 | + } |
| 144 | + |
| 145 | + if ( |
| 146 | + typeof key === "symbol" || |
| 147 | + renderAddedProperties[key] || |
| 148 | + key in target |
| 149 | + ) { |
| 150 | + // If the property is defined in the component props, just set it. |
| 151 | + if ( |
| 152 | + ReactComponent.propTypes && |
| 153 | + key in ReactComponent.propTypes && |
| 154 | + typeof key === "string" |
| 155 | + ) { |
| 156 | + define.expando(receiver, key, value) |
| 157 | + } |
| 158 | + // Set it on the HTML element as well. |
| 159 | + return Reflect.set(target, key, value, receiver) |
| 160 | + } else { |
| 161 | + define.expando(receiver, key, value) |
| 162 | + } |
| 163 | + return true |
| 164 | + }, |
| 165 | + // makes sure the property looks writable |
| 166 | + getOwnPropertyDescriptor: function (target, key) { |
| 167 | + const own = Reflect.getOwnPropertyDescriptor(target, key) |
| 168 | + if (own) { |
| 169 | + return own |
| 170 | + } |
| 171 | + if (key in propTypes) { |
| 172 | + return { |
| 173 | + configurable: true, |
| 174 | + enumerable: true, |
| 175 | + writable: true, |
| 176 | + value: undefined, |
| 177 | + } |
| 178 | + } |
| 179 | + }, |
| 180 | + }) |
| 181 | + WebComponent.prototype = proxyPrototype |
| 182 | + |
| 183 | + // Setup lifecycle methods |
| 184 | + targetPrototype.connectedCallback = function () { |
| 185 | + // Once connected, it will keep updating the innerHTML. |
| 186 | + // We could add a render method to allow this as well. |
| 187 | + this[shouldRenderSymbol] = true |
| 188 | + this[renderSymbol]() |
| 189 | + } |
| 190 | + targetPrototype.disconnectedCallback = function () { |
| 191 | + renderer.unmount(this) |
| 192 | + } |
| 193 | + targetPrototype[renderSymbol] = function () { |
| 194 | + if (this[shouldRenderSymbol] === true) { |
| 195 | + const data: Record<string, any> = {} |
| 196 | + Object.keys(this).forEach(function (this: any, key) { |
| 197 | + if (renderAddedProperties[key] !== false) { |
| 198 | + data[key] = this[key] |
| 199 | + } |
| 200 | + }, this) |
| 201 | + rendering = true |
| 202 | + // Container is either shadow DOM or light DOM depending on `shadow` option. |
| 203 | + const container = config.shadow ? this.shadowRoot : this |
| 204 | + |
| 205 | + const children = flattenIfOne(mapChildren(this)) |
| 206 | + |
| 207 | + const element = React.createElement(ReactComponent, data, children) |
| 208 | + |
| 209 | + // Use react to render element in container |
| 210 | + renderer.mount(container, element) |
| 211 | + rendering = false |
| 212 | + } |
| 213 | + } |
| 214 | + |
| 215 | + // Handle attributes changing |
| 216 | + WebComponent.observedAttributes = Object.keys(attrPropMap) |
| 217 | + |
| 218 | + targetPrototype.attributeChangedCallback = function ( |
| 219 | + name: string, |
| 220 | + oldValue: any, |
| 221 | + newValue: any, |
| 222 | + ) { |
| 223 | + const propertyName = attrPropMap[name] || name |
| 224 | + switch (propTypes[propertyName]) { |
| 225 | + case "ref": |
| 226 | + case Function: |
| 227 | + if (!newValue && propTypes[propertyName] === "ref") { |
| 228 | + newValue = React.createRef() |
| 229 | + break |
| 230 | + } |
| 231 | + if (typeof window !== "undefined") { |
| 232 | + newValue = window[newValue] || newValue |
| 233 | + } else if (typeof global !== "undefined") { |
| 234 | + newValue = global[newValue] || newValue |
| 235 | + } |
| 236 | + if (typeof newValue === "function") { |
| 237 | + newValue = newValue.bind(this) // this = instance of the WebComponent / HTMLElement |
| 238 | + } |
| 239 | + break |
| 240 | + case Number: |
| 241 | + newValue = parseFloat(newValue) |
| 242 | + break |
| 243 | + case Boolean: |
| 244 | + newValue = /^[ty1-9]/i.test(newValue) |
| 245 | + break |
| 246 | + case Object: |
| 247 | + case Array: |
| 248 | + newValue = JSON.parse(newValue) |
| 249 | + break |
| 250 | + case String: |
| 251 | + default: |
| 252 | + break |
| 253 | + } |
| 254 | + |
| 255 | + this[propertyName] = newValue |
| 256 | + } |
| 257 | + |
| 258 | + return WebComponent as unknown as CustomElementConstructor |
| 259 | +} |
0 commit comments