"use strict";

exports.__esModule = true;
exports.ServerSlice = void 0;

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

var _createContentDigest = require("gatsby-core-utils/create-content-digest");

var _slice = require("../slice");

var _serverSliceRenderer = require("./server-slice-renderer");

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

// const orig = React.createElement
// React.createElement = (...args) => {
//   if (!args[0]) {
//     console.trace(`where`)
//   }
//   return orig(...args)
// }
const getSliceId = (sliceName, sliceProps) => {
  if (!Object.keys(sliceProps).length) {
    return sliceName;
  }

  const propsString = (0, _createContentDigest.createContentDigest)(sliceProps);
  return `${sliceName}-${propsString}`;
};

const ServerSlice = ({
  sliceName,
  allowEmpty,
  children,
  ...sliceProps
}) => {
  const slicesMap = (0, _react.useContext)(_slice.SlicesMapContext);
  const slicesProps = (0, _react.useContext)(_slice.SlicesPropsContext);
  const concreteSliceName = slicesMap[sliceName];

  if (!concreteSliceName) {
    if (allowEmpty) {
      return null;
    } else {
      throw new Error(`Slice "${concreteSliceName}" for "${sliceName}" slot not found`);
    }
  }

  const sliceId = getSliceId(concreteSliceName, sliceProps); // set props on context object for static-entry to return

  let sliceUsage = slicesProps[sliceId];

  if (!sliceUsage) {
    slicesProps[sliceId] = sliceUsage = {
      props: sliceProps,
      sliceName: concreteSliceName,
      hasChildren: !!children
    };
  } else {
    if (children) {
      sliceUsage.hasChildren = true;
    }
  }

  return /*#__PURE__*/_react.default.createElement(_serverSliceRenderer.ServerSliceRenderer, {
    sliceId: sliceId
  }, children);
};

exports.ServerSlice = ServerSlice;