summaryrefslogtreecommitdiff
path: root/packages/renderers/renderer-react/server.js
blob: e4f1cf69051a239551baf637a12316816d673b5e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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');

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');
  }

  renderToStaticMarkup(Tester, props, children, {});

  if (error) {
    throw error;
  }
  return isReactComponent;
}

function renderToStaticMarkup(Component, props, children, metadata) {
  const vnode = h(Component, { ...props, children: h(StaticHtml, { value: children }), innerHTML: children });
  let html;
  if(metadata.hydrate) {
    html = renderToString(vnode);
  } else {
    html = reactRenderToStaticMarkup(vnode);
  }
  return { html };
}

export default {
  check,
  renderToStaticMarkup,
};