"use strict";

exports.__esModule = true;
exports.onProviderMount = onProviderMount;
exports.onProviderUnMount = onProviderUnMount;
exports.renderToRoot = renderToRoot;

var _react = _interopRequireDefault(require("react"));

var _reactDom = require("react-dom");

var _env = require("./env");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var shared = {
  Host: {
    driver: {}
  }
};
var provider = null;

function onProviderMount(p) {
  provider = p;
}

function onProviderUnMount() {
  provider = null;
}

function renderWithProvider(element, onHide) {
  return provider.addPortal({
    element: element,
    onHide: onHide
  });
}

function renderWithDriver(element, onHide) {
  if (!shared || !shared.Host || !shared.Host.driver) {
    throw new Error('Render fail: driver not found.');
  }

  shared.Host.driver;
  var root = document.createElement('div');
  var hid = false;

  var hide = function () {
    if (hid) {
      return;
    }

    try {
      hid = true;
      (0, _reactDom.unmountComponentAtNode)(root);
      document.body.removeChild(root);

      if (onHide) {
        onHide();
      }
    } catch (e) {
      throw new Error('remove element error');
    }
  };

  if (_env.isStrictWechatMiniProgram || _env.isStrictByteDanceMicroApp) {
    (0, _reactDom.render)(element, root);
  } else {
    document.body.appendChild(root);
    (0, _reactDom.render)(element, root);
  }

  return hide;
}

function renderToRoot(element, onHide) {
  if (provider) {
    return renderWithProvider(element, onHide);
  }

  return renderWithDriver(element, onHide);
}