"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.mapNativeEventNames = mapNativeEventNames;
exports.propFromEvent = propFromEvent;
exports.withSetStateAllowed = withSetStateAllowed;
exports.assertDomAvailable = assertDomAvailable;
exports.displayNameOfNode = displayNameOfNode;
exports.nodeTypeFromType = nodeTypeFromType;
exports.isArrayLike = isArrayLike;
exports.flatten = flatten;
exports.ensureKeyOrUndefined = ensureKeyOrUndefined;
exports.elementToTree = elementToTree;
exports.findElement = findElement;
exports.propsWithKeysAndRef = propsWithKeysAndRef;
exports.getComponentStack = getComponentStack;
exports.simulateError = simulateError;
exports.getMaskedContext = getMaskedContext;
exports.getNodeFromRootFinder = getNodeFromRootFinder;
exports.wrapWithWrappingComponent = wrapWithWrappingComponent;
exports.getWrappingComponentMountRenderer = getWrappingComponentMountRenderer;
exports.fakeDynamicImport = fakeDynamicImport;
exports.compareNodeTypeOf = compareNodeTypeOf;
exports.spyMethod = spyMethod;
exports.spyProperty = spyProperty;
Object.defineProperty(exports, "createMountWrapper", {
  enumerable: true,
  get: function get() {
    return _createMountWrapper["default"];
  }
});
Object.defineProperty(exports, "createRenderWrapper", {
  enumerable: true,
  get: function get() {
    return _createRenderWrapper["default"];
  }
});
Object.defineProperty(exports, "wrap", {
  enumerable: true,
  get: function get() {
    return _wrapWithSimpleWrapper["default"];
  }
});
Object.defineProperty(exports, "RootFinder", {
  enumerable: true,
  get: function get() {
    return _RootFinder["default"];
  }
});

var _functionPrototype = _interopRequireDefault(require("function.prototype.name"));

var _object = _interopRequireDefault(require("object.fromentries"));

var _has = _interopRequireDefault(require("has"));

var _createMountWrapper = _interopRequireDefault(require("./createMountWrapper"));

var _createRenderWrapper = _interopRequireDefault(require("./createRenderWrapper"));

var _wrapWithSimpleWrapper = _interopRequireDefault(require("./wrapWithSimpleWrapper"));

var _RootFinder = _interopRequireDefault(require("./RootFinder"));

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

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function mapNativeEventNames(event) {
  var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
      _ref$animation = _ref.animation,
      animation = _ref$animation === void 0 ? false : _ref$animation,
      _ref$pointerEvents = _ref.pointerEvents,
      pointerEvents = _ref$pointerEvents === void 0 ? false : _ref$pointerEvents,
      _ref$auxClick = _ref.auxClick,
      auxClick = _ref$auxClick === void 0 ? false : _ref$auxClick;

  var nativeToReactEventMap = _objectSpread(_objectSpread(_objectSpread({
    compositionend: 'compositionEnd',
    compositionstart: 'compositionStart',
    compositionupdate: 'compositionUpdate',
    keydown: 'keyDown',
    keyup: 'keyUp',
    keypress: 'keyPress',
    contextmenu: 'contextMenu',
    dblclick: 'doubleClick',
    doubleclick: 'doubleClick',
    // kept for legacy. TODO: remove with next major.
    dragend: 'dragEnd',
    dragenter: 'dragEnter',
    dragexist: 'dragExit',
    dragleave: 'dragLeave',
    dragover: 'dragOver',
    dragstart: 'dragStart',
    mousedown: 'mouseDown',
    mousemove: 'mouseMove',
    mouseout: 'mouseOut',
    mouseover: 'mouseOver',
    mouseup: 'mouseUp',
    touchcancel: 'touchCancel',
    touchend: 'touchEnd',
    touchmove: 'touchMove',
    touchstart: 'touchStart',
    canplay: 'canPlay',
    canplaythrough: 'canPlayThrough',
    durationchange: 'durationChange',
    loadeddata: 'loadedData',
    loadedmetadata: 'loadedMetadata',
    loadstart: 'loadStart',
    ratechange: 'rateChange',
    timeupdate: 'timeUpdate',
    volumechange: 'volumeChange',
    beforeinput: 'beforeInput',
    mouseenter: 'mouseEnter',
    mouseleave: 'mouseLeave',
    transitionend: 'transitionEnd'
  }, animation && {
    animationstart: 'animationStart',
    animationiteration: 'animationIteration',
    animationend: 'animationEnd'
  }), pointerEvents && {
    pointerdown: 'pointerDown',
    pointermove: 'pointerMove',
    pointerup: 'pointerUp',
    pointercancel: 'pointerCancel',
    gotpointercapture: 'gotPointerCapture',
    lostpointercapture: 'lostPointerCapture',
    pointerenter: 'pointerEnter',
    pointerleave: 'pointerLeave',
    pointerover: 'pointerOver',
    pointerout: 'pointerOut'
  }), auxClick && {
    auxclick: 'auxClick'
  });

  return nativeToReactEventMap[event] || event;
} // 'click' => 'onClick'
// 'mouseEnter' => 'onMouseEnter'


function propFromEvent(event) {
  var eventOptions = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var nativeEvent = mapNativeEventNames(event, eventOptions);
  return "on".concat(nativeEvent[0].toUpperCase()).concat(nativeEvent.slice(1));
}

function withSetStateAllowed(fn) {
  // NOTE(lmr):
  // this is currently here to circumvent a React bug where `setState()` is
  // not allowed without global being defined.
  var cleanup = false;

  if (typeof global.document === 'undefined') {
    cleanup = true;
    global.document = {};
  }

  var result = fn();

  if (cleanup) {
    // This works around a bug in node/jest in that developers aren't able to
    // delete things from global when running in a node vm.
    global.document = undefined;
    delete global.document;
  }

  return result;
}

function assertDomAvailable(feature) {
  if (!global || !global.document || !global.document.createElement) {
    throw new Error("Enzyme's ".concat(feature, " expects a DOM environment to be loaded, but found none"));
  }
}

function displayNameOfNode(node) {
  if (!node) return null;
  var type = node.type;
  if (!type) return null;
  return type.displayName || (typeof type === 'function' ? (0, _functionPrototype["default"])(type) : type.name || type);
}

function nodeTypeFromType(type) {
  if (typeof type === 'string') {
    return 'host';
  }

  if (type && type.prototype && type.prototype.isReactComponent) {
    return 'class';
  }

  return 'function';
}

function getIteratorFn(obj) {
  var iteratorFn = obj && (typeof Symbol === 'function' && _typeof(Symbol.iterator) === 'symbol' && obj[Symbol.iterator] || obj['@@iterator']);

  if (typeof iteratorFn === 'function') {
    return iteratorFn;
  }

  return undefined;
}

function isIterable(obj) {
  return !!getIteratorFn(obj);
}

function isArrayLike(obj) {
  return Array.isArray(obj) || typeof obj !== 'string' && isIterable(obj);
}

function flatten(arrs) {
  // optimize for the most common case
  if (Array.isArray(arrs)) {
    return arrs.reduce(function (flatArrs, item) {
      return flatArrs.concat(isArrayLike(item) ? flatten(item) : item);
    }, []);
  } // fallback for arbitrary iterable children


  var flatArrs = [];
  var iteratorFn = getIteratorFn(arrs);
  var iterator = iteratorFn.call(arrs);
  var step = iterator.next();

  while (!step.done) {
    var item = step.value;
    var flatItem = void 0;

    if (isArrayLike(item)) {
      flatItem = flatten(item);
    } else {
      flatItem = item;
    }

    flatArrs = flatArrs.concat(flatItem);
    step = iterator.next();
  }

  return flatArrs;
}

function ensureKeyOrUndefined(key) {
  return key || (key === '' ? '' : undefined);
}

function elementToTree(el) {
  var recurse = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : elementToTree;

  if (typeof recurse !== 'function' && arguments.length === 3) {
    // special case for backwards compat for `.map(elementToTree)`
    recurse = elementToTree; // eslint-disable-line no-param-reassign
  }

  if (el === null || _typeof(el) !== 'object' || !('type' in el)) {
    return el;
  }

  var type = el.type,
      props = el.props,
      key = el.key,
      ref = el.ref;
  var children = props.children;
  var rendered = null;

  if (isArrayLike(children)) {
    rendered = flatten(children).map(function (x) {
      return recurse(x);
    });
  } else if (typeof children !== 'undefined') {
    rendered = recurse(children);
  }

  var nodeType = nodeTypeFromType(type);

  if (nodeType === 'host' && props.dangerouslySetInnerHTML) {
    if (props.children != null) {
      var error = new Error('Can only set one of `children` or `props.dangerouslySetInnerHTML`.');
      error.name = 'Invariant Violation';
      throw error;
    }
  }

  return {
    nodeType: nodeType,
    type: type,
    props: props,
    key: ensureKeyOrUndefined(key),
    ref: ref,
    instance: null,
    rendered: rendered
  };
}

function mapFind(arraylike, mapper, finder) {
  var found;
  var isFound = Array.prototype.find.call(arraylike, function (item) {
    found = mapper(item);
    return finder(found);
  });
  return isFound ? found : undefined;
}

function findElement(el, predicate) {
  if (el === null || _typeof(el) !== 'object' || !('type' in el)) {
    return undefined;
  }

  if (predicate(el)) {
    return el;
  }

  var rendered = el.rendered;

  if (isArrayLike(rendered)) {
    return mapFind(rendered, function (x) {
      return findElement(x, predicate);
    }, function (x) {
      return typeof x !== 'undefined';
    });
  }

  return findElement(rendered, predicate);
}

function propsWithKeysAndRef(node) {
  if (node.ref !== null || node.key !== null) {
    return _objectSpread(_objectSpread({}, node.props), {}, {
      key: node.key,
      ref: node.ref
    });
  }

  return node.props;
}

function getComponentStack(hierarchy) {
  var getNodeType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : nodeTypeFromType;
  var getDisplayName = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : displayNameOfNode;
  var tuples = hierarchy.filter(function (node) {
    return node.type !== _RootFinder["default"];
  }).map(function (x) {
    return [getNodeType(x.type), getDisplayName(x)];
  }).concat([['class', 'WrapperComponent']]);
  return tuples.map(function (_ref2, i, arr) {
    var _ref3 = _slicedToArray(_ref2, 2),
        name = _ref3[1];

    var _ref4 = arr.slice(i + 1).find(function (_ref6) {
      var _ref7 = _slicedToArray(_ref6, 1),
          nodeType = _ref7[0];

      return nodeType !== 'host';
    }) || [],
        _ref5 = _slicedToArray(_ref4, 2),
        closestComponent = _ref5[1];

    return "\n    in ".concat(name).concat(closestComponent ? " (created by ".concat(closestComponent, ")") : '');
  }).join('');
}

function simulateError(error, catchingInstance, rootNode, // TODO: remove `rootNode` next semver-major
hierarchy) {
  var getNodeType = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : nodeTypeFromType;
  var getDisplayName = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : displayNameOfNode;
  var catchingType = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : {};
  var instance = catchingInstance || {};
  var componentDidCatch = instance.componentDidCatch;
  var getDerivedStateFromError = catchingType.getDerivedStateFromError;

  if (!componentDidCatch && !getDerivedStateFromError) {
    throw error;
  }

  if (getDerivedStateFromError) {
    var stateUpdate = getDerivedStateFromError.call(catchingType, error);
    instance.setState(stateUpdate);
  }

  if (componentDidCatch) {
    var componentStack = getComponentStack(hierarchy, getNodeType, getDisplayName);
    componentDidCatch.call(instance, error, {
      componentStack: componentStack
    });
  }
}

function getMaskedContext(contextTypes, unmaskedContext) {
  if (!contextTypes || !unmaskedContext) {
    return {};
  }

  return (0, _object["default"])(Object.keys(contextTypes).map(function (key) {
    return [key, unmaskedContext[key]];
  }));
}

function getNodeFromRootFinder(isCustomComponent, tree, options) {
  if (!isCustomComponent(options.wrappingComponent)) {
    return tree.rendered;
  }

  var rootFinder = findElement(tree, function (node) {
    return node.type === _RootFinder["default"];
  });

  if (!rootFinder) {
    throw new Error('`wrappingComponent` must render its children!');
  }

  return rootFinder.rendered;
}

function wrapWithWrappingComponent(createElement, node, options) {
  var wrappingComponent = options.wrappingComponent,
      wrappingComponentProps = options.wrappingComponentProps;

  if (!wrappingComponent) {
    return node;
  }

  return createElement(wrappingComponent, wrappingComponentProps, createElement(_RootFinder["default"], null, node));
}

function getWrappingComponentMountRenderer(_ref8) {
  var toTree = _ref8.toTree,
      getMountWrapperInstance = _ref8.getMountWrapperInstance;
  return {
    getNode: function getNode() {
      var instance = getMountWrapperInstance();
      return instance ? toTree(instance).rendered : null;
    },
    render: function render(el, context, callback) {
      var instance = getMountWrapperInstance();

      if (!instance) {
        throw new Error('The wrapping component may not be updated if the root is unmounted.');
      }

      return instance.setWrappingComponentProps(el.props, callback);
    }
  };
}

function fakeDynamicImport(moduleToImport) {
  return Promise.resolve({
    "default": moduleToImport
  });
}

function compareNodeTypeOf(node, matchingTypeOf) {
  if (!node) {
    return false;
  }

  return node.$$typeof === matchingTypeOf;
} // TODO: when enzyme v3.12.0 is required, delete this


function spyMethod(instance, methodName) {
  var getStub = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : function () {};
  var lastReturnValue;
  var originalMethod = instance[methodName];
  var hasOwn = (0, _has["default"])(instance, methodName);
  var descriptor;

  if (hasOwn) {
    descriptor = Object.getOwnPropertyDescriptor(instance, methodName);
  }

  Object.defineProperty(instance, methodName, {
    configurable: true,
    enumerable: !descriptor || !!descriptor.enumerable,
    value: getStub(originalMethod) || function spied() {
      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }

      var result = originalMethod.apply(this, args);
      lastReturnValue = result;
      return result;
    }
  });
  return {
    restore: function restore() {
      if (hasOwn) {
        if (descriptor) {
          Object.defineProperty(instance, methodName, descriptor);
        } else {
          /* eslint-disable no-param-reassign */
          instance[methodName] = originalMethod;
          /* eslint-enable no-param-reassign */
        }
      } else {
        /* eslint-disable no-param-reassign */
        delete instance[methodName];
        /* eslint-enable no-param-reassign */
      }
    },
    getLastReturnValue: function getLastReturnValue() {
      return lastReturnValue;
    }
  };
} // TODO: when enzyme v3.12.0 is required, delete this


function spyProperty(instance, propertyName) {
  var handlers = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  var originalValue = instance[propertyName];
  var hasOwn = (0, _has["default"])(instance, propertyName);
  var descriptor;

  if (hasOwn) {
    descriptor = Object.getOwnPropertyDescriptor(instance, propertyName);
  }

  var _wasAssigned = false;
  var holder = originalValue;
  var getV = handlers.get ? function () {
    var value = descriptor && descriptor.get ? descriptor.get.call(instance) : holder;
    return handlers.get.call(instance, value);
  } : function () {
    return holder;
  };
  var set = handlers.set ? function (newValue) {
    _wasAssigned = true;
    var handlerNewValue = handlers.set.call(instance, holder, newValue);
    holder = handlerNewValue;

    if (descriptor && descriptor.set) {
      descriptor.set.call(instance, holder);
    }
  } : function (v) {
    _wasAssigned = true;
    holder = v;
  };
  Object.defineProperty(instance, propertyName, {
    configurable: true,
    enumerable: !descriptor || !!descriptor.enumerable,
    get: getV,
    set: set
  });
  return {
    restore: function restore() {
      if (hasOwn) {
        if (descriptor) {
          Object.defineProperty(instance, propertyName, descriptor);
        } else {
          /* eslint-disable no-param-reassign */
          instance[propertyName] = holder;
          /* eslint-enable no-param-reassign */
        }
      } else {
        /* eslint-disable no-param-reassign */
        delete instance[propertyName];
        /* eslint-enable no-param-reassign */
      }
    },
    wasAssigned: function wasAssigned() {
      return _wasAssigned;
    }
  };
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,[encoded data, 39080 characters]
//# sourceMappingURL=Utils.js.map