"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useRenderToText = useRenderToText;

var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));

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

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

var _inner_text = require("./inner_text");

/*
 * Licensed to Elasticsearch B.V. under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch B.V. licenses this file to you under
 * the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
function useRenderToText(node) {
  var placeholder = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';

  var _useInnerText = (0, _inner_text.useInnerText)(placeholder),
      _useInnerText2 = (0, _slicedToArray2.default)(_useInnerText, 2),
      ref = _useInnerText2[0],
      text = _useInnerText2[1];

  var hostNode = (0, _react.useRef)(null);

  var onUnmount = function onUnmount() {
    if (hostNode.current) {
      (0, _reactDom.unmountComponentAtNode)(hostNode.current);
      hostNode.current = null;
    }
  };

  var setRef = (0, _react.useCallback)(function (node) {
    if (hostNode.current) {
      ref(node);
    }
  }, [ref]);
  (0, _react.useEffect)(function () {
    hostNode.current = document.createDocumentFragment();
    (0, _reactDom.render)( /*#__PURE__*/_react.default.createElement("div", {
      ref: setRef
    }, node), hostNode.current);
    return function () {
      onUnmount();
    };
  }, [node, setRef]);
  return text || placeholder;
}