"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _element = require("@wordpress/element");
var _context = _interopRequireDefault(require("./context"));
var _jsxRuntime = require("react/jsx-runtime");
/**
 * External dependencies
 */

/**
 * WordPress dependencies
 */

/**
 * Internal dependencies
 */

/**
 * Whether the argument is a function.
 *
 * @param maybeFunc The argument to check.
 * @return True if the argument is a function, false otherwise.
 */
function isFunction(maybeFunc) {
  return typeof maybeFunc === 'function';
}
function Slot(props) {
  var _registry$getFills;
  const registry = (0, _element.useContext)(_context.default);
  const [, rerender] = (0, _element.useReducer)(() => [], []);
  const ref = (0, _element.useRef)({
    rerender
  });
  const {
    name,
    children,
    fillProps = {}
  } = props;
  (0, _element.useEffect)(() => {
    const refValue = ref.current;
    registry.registerSlot(name, refValue);
    return () => registry.unregisterSlot(name, refValue);
  }, [registry, name]);
  const fills = ((_registry$getFills = registry.getFills(name, ref.current)) !== null && _registry$getFills !== void 0 ? _registry$getFills : []).map(fill => {
    const fillChildren = isFunction(fill.children) ? fill.children(fillProps) : fill.children;
    return _element.Children.map(fillChildren, (child, childIndex) => {
      if (!child || typeof child === 'string') {
        return child;
      }
      let childKey = childIndex;
      if (typeof child === 'object' && 'key' in child && child?.key) {
        childKey = child.key;
      }
      return (0, _element.cloneElement)(child, {
        key: childKey
      });
    });
  }).filter(
  // In some cases fills are rendered only when some conditions apply.
  // This ensures that we only use non-empty fills when rendering, i.e.,
  // it allows us to render wrappers only when the fills are actually present.
  element => !(0, _element.isEmptyElement)(element));
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_jsxRuntime.Fragment, {
    children: isFunction(children) ? children(fills) : fills
  });
}
var _default = exports.default = Slot;
//# sourceMappingURL=slot.js.map