astro/packages/renderers/renderer-react/server.js
2021-07-13 17:04:11 -04:00

59 lines
1.4 KiB
JavaScript

import { Component as BaseComponent, createElement as h } from 'react';
import { renderToStaticMarkup as reactRenderToStaticMarkup, renderToString } from 'react-dom/server.js';
import StaticHtml from './static-html.js';
const reactTypeof = Symbol.for('react.element');
async function check(Component, props, children) {
if (typeof Component !== 'function') return false;
if (Component.prototype != null && typeof Component.prototype.render === 'function') {
return BaseComponent.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) {
error = err;
}
return h('div');
}
await renderToStaticMarkup(Tester, props, children, {});
if (error) {
throw error;
}
return isReactComponent;
}
async function renderToStaticMarkup(Component, props, children, metadata) {
const childrenValue = children || (await props.children);
const vnode = h(Component, {
...props,
children: h(StaticHtml, {
value: childrenValue
}),
innerHTML: children
});
let html;
if (metadata && metadata.hydrate) {
html = renderToString(vnode);
} else {
html = reactRenderToStaticMarkup(vnode);
}
return { html };
}
export default {
check,
renderToStaticMarkup,
};