|
| 1 | +import React from 'react'; |
| 2 | + |
| 3 | +const getReactCSSOMClass = (componentName) => `⚛${componentName}`; |
| 4 | + |
| 5 | +function injectInElement(component, componentName) { |
| 6 | + let result = component; |
| 7 | + if (component) { |
| 8 | + const classToInject = getReactCSSOMClass(componentName); |
| 9 | + if (typeof component.type === 'string') { |
| 10 | + result = React.cloneElement( |
| 11 | + component, |
| 12 | + { |
| 13 | + className: `${classToInject} ${component.props.className || ''}`, |
| 14 | + } |
| 15 | + ); |
| 16 | + } else if (typeof component.type === 'function') { |
| 17 | + result = ( |
| 18 | + <div className={`${classToInject}`}> |
| 19 | + {component} |
| 20 | + </div> |
| 21 | + ); |
| 22 | + } |
| 23 | + } |
| 24 | + return result; |
| 25 | +} |
| 26 | + |
| 27 | +function injectInComponent(Component, componentName) { |
| 28 | + const componentPrototype = Component.prototype; |
| 29 | + const componentConstructor = Component; |
| 30 | + |
| 31 | + //eslint-disable-next-line |
| 32 | + const newComponent = function ReactComponent(...params) { |
| 33 | + componentConstructor.apply(this, [...params]); |
| 34 | + const originalRender = this.render; |
| 35 | + this.render = () => ( |
| 36 | + injectInElement( |
| 37 | + originalRender.apply(this), |
| 38 | + componentName || this.constructor.displayName || this.constructor.name |
| 39 | + ) |
| 40 | + ); |
| 41 | + }; |
| 42 | + |
| 43 | + //eslint-disable-next-line |
| 44 | + newComponent.prototype = componentPrototype; |
| 45 | + Object.keys(Component).forEach((x) => { |
| 46 | + newComponent[x] = Component[x]; |
| 47 | + }); |
| 48 | + |
| 49 | + return newComponent; |
| 50 | +} |
| 51 | + |
| 52 | +function injectInFunctionalComponent(component, componentName) { |
| 53 | + return (props) => injectInElement( |
| 54 | + component(props), |
| 55 | + componentName |
| 56 | + ); |
| 57 | +} |
| 58 | + |
| 59 | +export default function inject(component) { |
| 60 | + return (componentName) => { |
| 61 | + let result = null; |
| 62 | + if ( |
| 63 | + typeof component === 'function' && |
| 64 | + component.prototype && |
| 65 | + component.prototype.isReactComponent |
| 66 | + ) { |
| 67 | + result = injectInComponent(component, componentName); |
| 68 | + } else if (typeof component === 'function') { |
| 69 | + result = injectInFunctionalComponent(component, componentName); |
| 70 | + } else if (component !== null && typeof component === 'object') { |
| 71 | + result = injectInElement(component, componentName); |
| 72 | + } |
| 73 | + return result; |
| 74 | + }; |
| 75 | +} |
0 commit comments