2022-03-18 17:35:45 -05:00
|
|
|
import React from 'react';
|
2022-03-31 11:51:29 -05:00
|
|
|
import ReactDOM from 'react-dom/server';
|
2022-03-18 17:35:45 -05:00
|
|
|
import StaticHtml from './static-html.js';
|
|
|
|
|
|
|
|
const reactTypeof = Symbol.for('react.element');
|
|
|
|
|
|
|
|
function errorIsComingFromPreactComponent(err) {
|
|
|
|
return (
|
|
|
|
err.message &&
|
|
|
|
(err.message.startsWith("Cannot read property '__H'") ||
|
|
|
|
err.message.includes("(reading '__H')"))
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2022-04-20 16:17:36 -05:00
|
|
|
function check(Component, props, children) {
|
2022-03-18 17:35:45 -05:00
|
|
|
// Note: there are packages that do some unholy things to create "components".
|
|
|
|
// Checking the $$typeof property catches most of these patterns.
|
|
|
|
if (typeof Component === 'object') {
|
|
|
|
const $$typeof = Component['$$typeof'];
|
|
|
|
return $$typeof && $$typeof.toString().slice('Symbol('.length).startsWith('react');
|
|
|
|
}
|
|
|
|
if (typeof Component !== 'function') return false;
|
|
|
|
|
|
|
|
if (Component.prototype != null && typeof Component.prototype.render === 'function') {
|
|
|
|
return React.Component.isPrototypeOf(Component) || React.PureComponent.isPrototypeOf(Component);
|
|
|
|
}
|
|
|
|
|
|
|
|
let error = null;
|
|
|
|
let isReactComponent = false;
|
|
|
|
function Tester(...args) {
|
|
|
|
try {
|
|
|
|
const vnode = Component(...args);
|
|
|
|
if (vnode && vnode['$$typeof'] === reactTypeof) {
|
|
|
|
isReactComponent = true;
|
|
|
|
}
|
|
|
|
} catch (err) {
|
|
|
|
if (!errorIsComingFromPreactComponent(err)) {
|
|
|
|
error = err;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return React.createElement('div');
|
|
|
|
}
|
|
|
|
|
2022-04-20 16:17:36 -05:00
|
|
|
renderToStaticMarkup(Tester, props, children, {});
|
2022-03-18 17:35:45 -05:00
|
|
|
|
|
|
|
if (error) {
|
|
|
|
throw error;
|
|
|
|
}
|
|
|
|
return isReactComponent;
|
|
|
|
}
|
|
|
|
|
2022-04-20 16:17:36 -05:00
|
|
|
function renderToStaticMarkup(Component, props, children, metadata) {
|
2022-03-18 17:35:45 -05:00
|
|
|
delete props['class'];
|
|
|
|
const vnode = React.createElement(Component, {
|
|
|
|
...props,
|
|
|
|
children: children != null ? React.createElement(StaticHtml, { value: children }) : undefined,
|
|
|
|
});
|
|
|
|
let html;
|
|
|
|
if (metadata && metadata.hydrate) {
|
|
|
|
html = ReactDOM.renderToString(vnode);
|
|
|
|
} else {
|
2022-04-20 16:17:36 -05:00
|
|
|
html = ReactDOM.renderToStaticMarkup(vnode);
|
2022-03-18 17:35:45 -05:00
|
|
|
}
|
|
|
|
return { html };
|
|
|
|
}
|
|
|
|
|
|
|
|
export default {
|
|
|
|
check,
|
|
|
|
renderToStaticMarkup,
|
|
|
|
};
|