// modules are defined as an array
// [ module function, map of requires ]
//
// map of requires is short require name -> numeric require
//
// anything defined in a previous bundle is accessed via the
// orig method which is the require for previous bundles
parcelRequire = (function (modules, cache, entry, globalName) {
  // Save the require from previous bundle to this closure if any
  var previousRequire = typeof parcelRequire === 'function' && parcelRequire;
  var nodeRequire = typeof require === 'function' && require;

  function newRequire(name, jumped) {
    if (!cache[name]) {
      if (!modules[name]) {
        // if we cannot find the module within our internal map or
        // cache jump to the current global require ie. the last bundle
        // that was added to the page.
        var currentRequire = typeof parcelRequire === 'function' && parcelRequire;
        if (!jumped && currentRequire) {
          return currentRequire(name, true);
        }

        // If there are other bundles on this page the require from the
        // previous one is saved to 'previousRequire'. Repeat this as
        // many times as there are bundles until the module is found or
        // we exhaust the require chain.
        if (previousRequire) {
          return previousRequire(name, true);
        }

        // Try the node require function if it exists.
        if (nodeRequire && typeof name === 'string') {
          return nodeRequire(name);
        }

        var err = new Error('Cannot find module \'' + name + '\'');
        err.code = 'MODULE_NOT_FOUND';
        throw err;
      }

      localRequire.resolve = resolve;
      localRequire.cache = {};

      var module = cache[name] = new newRequire.Module(name);

      modules[name][0].call(module.exports, localRequire, module, module.exports, this);
    }

    return cache[name].exports;

    function localRequire(x){
      return newRequire(localRequire.resolve(x));
    }

    function resolve(x){
      return modules[name][1][x] || x;
    }
  }

  function Module(moduleName) {
    this.id = moduleName;
    this.bundle = newRequire;
    this.exports = {};
  }

  newRequire.isParcelRequire = true;
  newRequire.Module = Module;
  newRequire.modules = modules;
  newRequire.cache = cache;
  newRequire.parent = previousRequire;
  newRequire.register = function (id, exports) {
    modules[id] = [function (require, module) {
      module.exports = exports;
    }, {}];
  };

  var error;
  for (var i = 0; i < entry.length; i++) {
    try {
      newRequire(entry[i]);
    } catch (e) {
      // Save first error but execute all entries
      if (!error) {
        error = e;
      }
    }
  }

  if (entry.length) {
    // Expose entry point to Node, AMD or browser globals
    // Based on https://github.com/ForbesLindesay/umd/blob/master/template.js
    var mainExports = newRequire(entry[entry.length - 1]);

    // CommonJS
    if (typeof exports === "object" && typeof module !== "undefined") {
      module.exports = mainExports;

    // RequireJS
    } else if (typeof define === "function" && define.amd) {
     define(function () {
       return mainExports;
     });

    // <script>
    } else if (globalName) {
      this[globalName] = mainExports;
    }
  }

  // Override the current require with this new one
  parcelRequire = newRequire;

  if (error) {
    // throw error from earlier, _after updating parcelRequire_
    throw error;
  }

  return newRequire;
})({"../node_modules/object-assign/index.js":[function(require,module,exports) {
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
'use strict';
/* eslint-disable no-unused-vars */

var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;

function toObject(val) {
  if (val === null || val === undefined) {
    throw new TypeError('Object.assign cannot be called with null or undefined');
  }

  return Object(val);
}

function shouldUseNative() {
  try {
    if (!Object.assign) {
      return false;
    } // Detect buggy property enumeration order in older V8 versions.
    // https://bugs.chromium.org/p/v8/issues/detail?id=4118


    var test1 = new String('abc'); // eslint-disable-line no-new-wrappers

    test1[5] = 'de';

    if (Object.getOwnPropertyNames(test1)[0] === '5') {
      return false;
    } // https://bugs.chromium.org/p/v8/issues/detail?id=3056


    var test2 = {};

    for (var i = 0; i < 10; i++) {
      test2['_' + String.fromCharCode(i)] = i;
    }

    var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
      return test2[n];
    });

    if (order2.join('') !== '0123456789') {
      return false;
    } // https://bugs.chromium.org/p/v8/issues/detail?id=3056


    var test3 = {};
    'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
      test3[letter] = letter;
    });

    if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') {
      return false;
    }

    return true;
  } catch (err) {
    // We don't expect any of the above to throw, but better to be safe.
    return false;
  }
}

module.exports = shouldUseNative() ? Object.assign : function (target, source) {
  var from;
  var to = toObject(target);
  var symbols;

  for (var s = 1; s < arguments.length; s++) {
    from = Object(arguments[s]);

    for (var key in from) {
      if (hasOwnProperty.call(from, key)) {
        to[key] = from[key];
      }
    }

    if (getOwnPropertySymbols) {
      symbols = getOwnPropertySymbols(from);

      for (var i = 0; i < symbols.length; i++) {
        if (propIsEnumerable.call(from, symbols[i])) {
          to[symbols[i]] = from[symbols[i]];
        }
      }
    }
  }

  return to;
};
},{}],"../node_modules/prop-types/lib/ReactPropTypesSecret.js":[function(require,module,exports) {
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

'use strict';

var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';

module.exports = ReactPropTypesSecret;

},{}],"../node_modules/prop-types/checkPropTypes.js":[function(require,module,exports) {
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
'use strict';

var printWarning = function () {};

if ("development" !== 'production') {
  var ReactPropTypesSecret = require('./lib/ReactPropTypesSecret');

  var loggedTypeFailures = {};
  var has = Function.call.bind(Object.prototype.hasOwnProperty);

  printWarning = function (text) {
    var message = 'Warning: ' + text;

    if (typeof console !== 'undefined') {
      console.error(message);
    }

    try {
      // --- Welcome to debugging React ---
      // This error was thrown as a convenience so that you can use this stack
      // to find the callsite that caused this warning to fire.
      throw new Error(message);
    } catch (x) {}
  };
}
/**
 * Assert that the values match with the type specs.
 * Error messages are memorized and will only be shown once.
 *
 * @param {object} typeSpecs Map of name to a ReactPropType
 * @param {object} values Runtime values that need to be type-checked
 * @param {string} location e.g. "prop", "context", "child context"
 * @param {string} componentName Name of the component for error messages.
 * @param {?Function} getStack Returns the component stack.
 * @private
 */


function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
  if ("development" !== 'production') {
    for (var typeSpecName in typeSpecs) {
      if (has(typeSpecs, typeSpecName)) {
        var error; // Prop type validation may throw. In case they do, we don't want to
        // fail the render phase where it didn't fail before. So we log it.
        // After these have been cleaned up, we'll let them throw.

        try {
          // This is intentionally an invariant that gets caught. It's the same
          // behavior as without this statement except with a better message.
          if (typeof typeSpecs[typeSpecName] !== 'function') {
            var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.');
            err.name = 'Invariant Violation';
            throw err;
          }

          error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);
        } catch (ex) {
          error = ex;
        }

        if (error && !(error instanceof Error)) {
          printWarning((componentName || 'React class') + ': type specification of ' + location + ' `' + typeSpecName + '` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a ' + typeof error + '. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).');
        }

        if (error instanceof Error && !(error.message in loggedTypeFailures)) {
          // Only monitor this failure once because there tends to be a lot of the
          // same error.
          loggedTypeFailures[error.message] = true;
          var stack = getStack ? getStack() : '';
          printWarning('Failed ' + location + ' type: ' + error.message + (stack != null ? stack : ''));
        }
      }
    }
  }
}
/**
 * Resets warning cache when testing.
 *
 * @private
 */


checkPropTypes.resetWarningCache = function () {
  if ("development" !== 'production') {
    loggedTypeFailures = {};
  }
};

module.exports = checkPropTypes;
},{"./lib/ReactPropTypesSecret":"../node_modules/prop-types/lib/ReactPropTypesSecret.js"}],"../node_modules/react/cjs/react.development.js":[function(require,module,exports) {
/** @license React v16.13.1
 * react.development.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
'use strict';

if ("development" !== "production") {
  (function () {
    'use strict';

    var _assign = require('object-assign');

    var checkPropTypes = require('prop-types/checkPropTypes');

    var ReactVersion = '16.13.1'; // The Symbol used to tag the ReactElement-like types. If there is no native Symbol
    // nor polyfill, then a plain number is used for performance.

    var hasSymbol = typeof Symbol === 'function' && Symbol.for;
    var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;
    var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;
    var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;
    var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;
    var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;
    var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;
    var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; // TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary

    var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;
    var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;
    var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;
    var REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for('react.suspense_list') : 0xead8;
    var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;
    var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;
    var REACT_BLOCK_TYPE = hasSymbol ? Symbol.for('react.block') : 0xead9;
    var REACT_FUNDAMENTAL_TYPE = hasSymbol ? Symbol.for('react.fundamental') : 0xead5;
    var REACT_RESPONDER_TYPE = hasSymbol ? Symbol.for('react.responder') : 0xead6;
    var REACT_SCOPE_TYPE = hasSymbol ? Symbol.for('react.scope') : 0xead7;
    var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
    var FAUX_ITERATOR_SYMBOL = '@@iterator';

    function getIteratorFn(maybeIterable) {
      if (maybeIterable === null || typeof maybeIterable !== 'object') {
        return null;
      }

      var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];

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

      return null;
    }
    /**
     * Keeps track of the current dispatcher.
     */


    var ReactCurrentDispatcher = {
      /**
       * @internal
       * @type {ReactComponent}
       */
      current: null
    };
    /**
     * Keeps track of the current batch's configuration such as how long an update
     * should suspend for if it needs to.
     */

    var ReactCurrentBatchConfig = {
      suspense: null
    };
    /**
     * Keeps track of the current owner.
     *
     * The current owner is the component who should own any components that are
     * currently being constructed.
     */

    var ReactCurrentOwner = {
      /**
       * @internal
       * @type {ReactComponent}
       */
      current: null
    };
    var BEFORE_SLASH_RE = /^(.*)[\\\/]/;

    function describeComponentFrame(name, source, ownerName) {
      var sourceInfo = '';

      if (source) {
        var path = source.fileName;
        var fileName = path.replace(BEFORE_SLASH_RE, '');
        {
          // In DEV, include code for a common special case:
          // prefer "folder/index.js" instead of just "index.js".
          if (/^index\./.test(fileName)) {
            var match = path.match(BEFORE_SLASH_RE);

            if (match) {
              var pathBeforeSlash = match[1];

              if (pathBeforeSlash) {
                var folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, '');
                fileName = folderName + '/' + fileName;
              }
            }
          }
        }
        sourceInfo = ' (at ' + fileName + ':' + source.lineNumber + ')';
      } else if (ownerName) {
        sourceInfo = ' (created by ' + ownerName + ')';
      }

      return '\n    in ' + (name || 'Unknown') + sourceInfo;
    }

    var Resolved = 1;

    function refineResolvedLazyComponent(lazyComponent) {
      return lazyComponent._status === Resolved ? lazyComponent._result : null;
    }

    function getWrappedName(outerType, innerType, wrapperName) {
      var functionName = innerType.displayName || innerType.name || '';
      return outerType.displayName || (functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName);
    }

    function getComponentName(type) {
      if (type == null) {
        // Host root, text node or just invalid type.
        return null;
      }

      {
        if (typeof type.tag === 'number') {
          error('Received an unexpected object in getComponentName(). ' + 'This is likely a bug in React. Please file an issue.');
        }
      }

      if (typeof type === 'function') {
        return type.displayName || type.name || null;
      }

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

      switch (type) {
        case REACT_FRAGMENT_TYPE:
          return 'Fragment';

        case REACT_PORTAL_TYPE:
          return 'Portal';

        case REACT_PROFILER_TYPE:
          return "Profiler";

        case REACT_STRICT_MODE_TYPE:
          return 'StrictMode';

        case REACT_SUSPENSE_TYPE:
          return 'Suspense';

        case REACT_SUSPENSE_LIST_TYPE:
          return 'SuspenseList';
      }

      if (typeof type === 'object') {
        switch (type.$$typeof) {
          case REACT_CONTEXT_TYPE:
            return 'Context.Consumer';

          case REACT_PROVIDER_TYPE:
            return 'Context.Provider';

          case REACT_FORWARD_REF_TYPE:
            return getWrappedName(type, type.render, 'ForwardRef');

          case REACT_MEMO_TYPE:
            return getComponentName(type.type);

          case REACT_BLOCK_TYPE:
            return getComponentName(type.render);

          case REACT_LAZY_TYPE:
            {
              var thenable = type;
              var resolvedThenable = refineResolvedLazyComponent(thenable);

              if (resolvedThenable) {
                return getComponentName(resolvedThenable);
              }

              break;
            }
        }
      }

      return null;
    }

    var ReactDebugCurrentFrame = {};
    var currentlyValidatingElement = null;

    function setCurrentlyValidatingElement(element) {
      {
        currentlyValidatingElement = element;
      }
    }

    {
      // Stack implementation injected by the current renderer.
      ReactDebugCurrentFrame.getCurrentStack = null;

      ReactDebugCurrentFrame.getStackAddendum = function () {
        var stack = ''; // Add an extra top frame while an element is being validated

        if (currentlyValidatingElement) {
          var name = getComponentName(currentlyValidatingElement.type);
          var owner = currentlyValidatingElement._owner;
          stack += describeComponentFrame(name, currentlyValidatingElement._source, owner && getComponentName(owner.type));
        } // Delegate to the injected renderer-specific implementation


        var impl = ReactDebugCurrentFrame.getCurrentStack;

        if (impl) {
          stack += impl() || '';
        }

        return stack;
      };
    }
    /**
     * Used by act() to track whether you're inside an act() scope.
     */

    var IsSomeRendererActing = {
      current: false
    };
    var ReactSharedInternals = {
      ReactCurrentDispatcher: ReactCurrentDispatcher,
      ReactCurrentBatchConfig: ReactCurrentBatchConfig,
      ReactCurrentOwner: ReactCurrentOwner,
      IsSomeRendererActing: IsSomeRendererActing,
      // Used by renderers to avoid bundling object-assign twice in UMD bundles:
      assign: _assign
    };
    {
      _assign(ReactSharedInternals, {
        // These should not be included in production.
        ReactDebugCurrentFrame: ReactDebugCurrentFrame,
        // Shim for React DOM 16.0.0 which still destructured (but not used) this.
        // TODO: remove in React 17.0.
        ReactComponentTreeHook: {}
      });
    } // by calls to these methods by a Babel plugin.
    //
    // In PROD (or in packages without access to React internals),
    // they are left as they are instead.

    function warn(format) {
      {
        for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
          args[_key - 1] = arguments[_key];
        }

        printWarning('warn', format, args);
      }
    }

    function error(format) {
      {
        for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
          args[_key2 - 1] = arguments[_key2];
        }

        printWarning('error', format, args);
      }
    }

    function printWarning(level, format, args) {
      // When changing this logic, you might want to also
      // update consoleWithStackDev.www.js as well.
      {
        var hasExistingStack = args.length > 0 && typeof args[args.length - 1] === 'string' && args[args.length - 1].indexOf('\n    in') === 0;

        if (!hasExistingStack) {
          var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
          var stack = ReactDebugCurrentFrame.getStackAddendum();

          if (stack !== '') {
            format += '%s';
            args = args.concat([stack]);
          }
        }

        var argsWithFormat = args.map(function (item) {
          return '' + item;
        }); // Careful: RN currently depends on this prefix

        argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
        // breaks IE9: https://github.com/facebook/react/issues/13610
        // eslint-disable-next-line react-internal/no-production-logging

        Function.prototype.apply.call(console[level], console, argsWithFormat);

        try {
          // --- Welcome to debugging React ---
          // This error was thrown as a convenience so that you can use this stack
          // to find the callsite that caused this warning to fire.
          var argIndex = 0;
          var message = 'Warning: ' + format.replace(/%s/g, function () {
            return args[argIndex++];
          });
          throw new Error(message);
        } catch (x) {}
      }
    }

    var didWarnStateUpdateForUnmountedComponent = {};

    function warnNoop(publicInstance, callerName) {
      {
        var _constructor = publicInstance.constructor;
        var componentName = _constructor && (_constructor.displayName || _constructor.name) || 'ReactClass';
        var warningKey = componentName + "." + callerName;

        if (didWarnStateUpdateForUnmountedComponent[warningKey]) {
          return;
        }

        error("Can't call %s on a component that is not yet mounted. " + 'This is a no-op, but it might indicate a bug in your application. ' + 'Instead, assign to `this.state` directly or define a `state = {};` ' + 'class property with the desired state in the %s component.', callerName, componentName);
        didWarnStateUpdateForUnmountedComponent[warningKey] = true;
      }
    }
    /**
     * This is the abstract API for an update queue.
     */


    var ReactNoopUpdateQueue = {
      /**
       * Checks whether or not this composite component is mounted.
       * @param {ReactClass} publicInstance The instance we want to test.
       * @return {boolean} True if mounted, false otherwise.
       * @protected
       * @final
       */
      isMounted: function (publicInstance) {
        return false;
      },

      /**
       * Forces an update. This should only be invoked when it is known with
       * certainty that we are **not** in a DOM transaction.
       *
       * You may want to call this when you know that some deeper aspect of the
       * component's state has changed but `setState` was not called.
       *
       * This will not invoke `shouldComponentUpdate`, but it will invoke
       * `componentWillUpdate` and `componentDidUpdate`.
       *
       * @param {ReactClass} publicInstance The instance that should rerender.
       * @param {?function} callback Called after component is updated.
       * @param {?string} callerName name of the calling function in the public API.
       * @internal
       */
      enqueueForceUpdate: function (publicInstance, callback, callerName) {
        warnNoop(publicInstance, 'forceUpdate');
      },

      /**
       * Replaces all of the state. Always use this or `setState` to mutate state.
       * You should treat `this.state` as immutable.
       *
       * There is no guarantee that `this.state` will be immediately updated, so
       * accessing `this.state` after calling this method may return the old value.
       *
       * @param {ReactClass} publicInstance The instance that should rerender.
       * @param {object} completeState Next state.
       * @param {?function} callback Called after component is updated.
       * @param {?string} callerName name of the calling function in the public API.
       * @internal
       */
      enqueueReplaceState: function (publicInstance, completeState, callback, callerName) {
        warnNoop(publicInstance, 'replaceState');
      },

      /**
       * Sets a subset of the state. This only exists because _pendingState is
       * internal. This provides a merging strategy that is not available to deep
       * properties which is confusing. TODO: Expose pendingState or don't use it
       * during the merge.
       *
       * @param {ReactClass} publicInstance The instance that should rerender.
       * @param {object} partialState Next partial state to be merged with state.
       * @param {?function} callback Called after component is updated.
       * @param {?string} Name of the calling function in the public API.
       * @internal
       */
      enqueueSetState: function (publicInstance, partialState, callback, callerName) {
        warnNoop(publicInstance, 'setState');
      }
    };
    var emptyObject = {};
    {
      Object.freeze(emptyObject);
    }
    /**
     * Base class helpers for the updating state of a component.
     */

    function Component(props, context, updater) {
      this.props = props;
      this.context = context; // If a component has string refs, we will assign a different object later.

      this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the
      // renderer.

      this.updater = updater || ReactNoopUpdateQueue;
    }

    Component.prototype.isReactComponent = {};
    /**
     * Sets a subset of the state. Always use this to mutate
     * state. You should treat `this.state` as immutable.
     *
     * There is no guarantee that `this.state` will be immediately updated, so
     * accessing `this.state` after calling this method may return the old value.
     *
     * There is no guarantee that calls to `setState` will run synchronously,
     * as they may eventually be batched together.  You can provide an optional
     * callback that will be executed when the call to setState is actually
     * completed.
     *
     * When a function is provided to setState, it will be called at some point in
     * the future (not synchronously). It will be called with the up to date
     * component arguments (state, props, context). These values can be different
     * from this.* because your function may be called after receiveProps but before
     * shouldComponentUpdate, and this new state, props, and context will not yet be
     * assigned to this.
     *
     * @param {object|function} partialState Next partial state or function to
     *        produce next partial state to be merged with current state.
     * @param {?function} callback Called after state is updated.
     * @final
     * @protected
     */

    Component.prototype.setState = function (partialState, callback) {
      if (!(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null)) {
        {
          throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");
        }
      }

      this.updater.enqueueSetState(this, partialState, callback, 'setState');
    };
    /**
     * Forces an update. This should only be invoked when it is known with
     * certainty that we are **not** in a DOM transaction.
     *
     * You may want to call this when you know that some deeper aspect of the
     * component's state has changed but `setState` was not called.
     *
     * This will not invoke `shouldComponentUpdate`, but it will invoke
     * `componentWillUpdate` and `componentDidUpdate`.
     *
     * @param {?function} callback Called after update is complete.
     * @final
     * @protected
     */


    Component.prototype.forceUpdate = function (callback) {
      this.updater.enqueueForceUpdate(this, callback, 'forceUpdate');
    };
    /**
     * Deprecated APIs. These APIs used to exist on classic React classes but since
     * we would like to deprecate them, we're not going to move them over to this
     * modern base class. Instead, we define a getter that warns if it's accessed.
     */


    {
      var deprecatedAPIs = {
        isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'],
        replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).']
      };

      var defineDeprecationWarning = function (methodName, info) {
        Object.defineProperty(Component.prototype, methodName, {
          get: function () {
            warn('%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]);
            return undefined;
          }
        });
      };

      for (var fnName in deprecatedAPIs) {
        if (deprecatedAPIs.hasOwnProperty(fnName)) {
          defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
        }
      }
    }

    function ComponentDummy() {}

    ComponentDummy.prototype = Component.prototype;
    /**
     * Convenience component with default shallow equality check for sCU.
     */

    function PureComponent(props, context, updater) {
      this.props = props;
      this.context = context; // If a component has string refs, we will assign a different object later.

      this.refs = emptyObject;
      this.updater = updater || ReactNoopUpdateQueue;
    }

    var pureComponentPrototype = PureComponent.prototype = new ComponentDummy();
    pureComponentPrototype.constructor = PureComponent; // Avoid an extra prototype jump for these methods.

    _assign(pureComponentPrototype, Component.prototype);

    pureComponentPrototype.isPureReactComponent = true; // an immutable object with a single mutable value

    function createRef() {
      var refObject = {
        current: null
      };
      {
        Object.seal(refObject);
      }
      return refObject;
    }

    var hasOwnProperty = Object.prototype.hasOwnProperty;
    var RESERVED_PROPS = {
      key: true,
      ref: true,
      __self: true,
      __source: true
    };
    var specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs;
    {
      didWarnAboutStringRefs = {};
    }

    function hasValidRef(config) {
      {
        if (hasOwnProperty.call(config, 'ref')) {
          var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;

          if (getter && getter.isReactWarning) {
            return false;
          }
        }
      }
      return config.ref !== undefined;
    }

    function hasValidKey(config) {
      {
        if (hasOwnProperty.call(config, 'key')) {
          var getter = Object.getOwnPropertyDescriptor(config, 'key').get;

          if (getter && getter.isReactWarning) {
            return false;
          }
        }
      }
      return config.key !== undefined;
    }

    function defineKeyPropWarningGetter(props, displayName) {
      var warnAboutAccessingKey = function () {
        {
          if (!specialPropKeyWarningShown) {
            specialPropKeyWarningShown = true;
            error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName);
          }
        }
      };

      warnAboutAccessingKey.isReactWarning = true;
      Object.defineProperty(props, 'key', {
        get: warnAboutAccessingKey,
        configurable: true
      });
    }

    function defineRefPropWarningGetter(props, displayName) {
      var warnAboutAccessingRef = function () {
        {
          if (!specialPropRefWarningShown) {
            specialPropRefWarningShown = true;
            error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName);
          }
        }
      };

      warnAboutAccessingRef.isReactWarning = true;
      Object.defineProperty(props, 'ref', {
        get: warnAboutAccessingRef,
        configurable: true
      });
    }

    function warnIfStringRefCannotBeAutoConverted(config) {
      {
        if (typeof config.ref === 'string' && ReactCurrentOwner.current && config.__self && ReactCurrentOwner.current.stateNode !== config.__self) {
          var componentName = getComponentName(ReactCurrentOwner.current.type);

          if (!didWarnAboutStringRefs[componentName]) {
            error('Component "%s" contains the string ref "%s". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://fb.me/react-strict-mode-string-ref', getComponentName(ReactCurrentOwner.current.type), config.ref);
            didWarnAboutStringRefs[componentName] = true;
          }
        }
      }
    }
    /**
     * Factory method to create a new React element. This no longer adheres to
     * the class pattern, so do not use new to call it. Also, instanceof check
     * will not work. Instead test $$typeof field against Symbol.for('react.element') to check
     * if something is a React Element.
     *
     * @param {*} type
     * @param {*} props
     * @param {*} key
     * @param {string|object} ref
     * @param {*} owner
     * @param {*} self A *temporary* helper to detect places where `this` is
     * different from the `owner` when React.createElement is called, so that we
     * can warn. We want to get rid of owner and replace string `ref`s with arrow
     * functions, and as long as `this` and owner are the same, there will be no
     * change in behavior.
     * @param {*} source An annotation object (added by a transpiler or otherwise)
     * indicating filename, line number, and/or other information.
     * @internal
     */


    var ReactElement = function (type, key, ref, self, source, owner, props) {
      var element = {
        // This tag allows us to uniquely identify this as a React Element
        $$typeof: REACT_ELEMENT_TYPE,
        // Built-in properties that belong on the element
        type: type,
        key: key,
        ref: ref,
        props: props,
        // Record the component responsible for creating this element.
        _owner: owner
      };
      {
        // The validation flag is currently mutative. We put it on
        // an external backing store so that we can freeze the whole object.
        // This can be replaced with a WeakMap once they are implemented in
        // commonly used development environments.
        element._store = {}; // To make comparing ReactElements easier for testing purposes, we make
        // the validation flag non-enumerable (where possible, which should
        // include every environment we run tests in), so the test framework
        // ignores it.

        Object.defineProperty(element._store, 'validated', {
          configurable: false,
          enumerable: false,
          writable: true,
          value: false
        }); // self and source are DEV only properties.

        Object.defineProperty(element, '_self', {
          configurable: false,
          enumerable: false,
          writable: false,
          value: self
        }); // Two elements created in two different places should be considered
        // equal for testing purposes and therefore we hide it from enumeration.

        Object.defineProperty(element, '_source', {
          configurable: false,
          enumerable: false,
          writable: false,
          value: source
        });

        if (Object.freeze) {
          Object.freeze(element.props);
          Object.freeze(element);
        }
      }
      return element;
    };
    /**
     * Create and return a new ReactElement of the given type.
     * See https://reactjs.org/docs/react-api.html#createelement
     */


    function createElement(type, config, children) {
      var propName; // Reserved names are extracted

      var props = {};
      var key = null;
      var ref = null;
      var self = null;
      var source = null;

      if (config != null) {
        if (hasValidRef(config)) {
          ref = config.ref;
          {
            warnIfStringRefCannotBeAutoConverted(config);
          }
        }

        if (hasValidKey(config)) {
          key = '' + config.key;
        }

        self = config.__self === undefined ? null : config.__self;
        source = config.__source === undefined ? null : config.__source; // Remaining properties are added to a new props object

        for (propName in config) {
          if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
            props[propName] = config[propName];
          }
        }
      } // Children can be more than one argument, and those are transferred onto
      // the newly allocated props object.


      var childrenLength = arguments.length - 2;

      if (childrenLength === 1) {
        props.children = children;
      } else if (childrenLength > 1) {
        var childArray = Array(childrenLength);

        for (var i = 0; i < childrenLength; i++) {
          childArray[i] = arguments[i + 2];
        }

        {
          if (Object.freeze) {
            Object.freeze(childArray);
          }
        }
        props.children = childArray;
      } // Resolve default props


      if (type && type.defaultProps) {
        var defaultProps = type.defaultProps;

        for (propName in defaultProps) {
          if (props[propName] === undefined) {
            props[propName] = defaultProps[propName];
          }
        }
      }

      {
        if (key || ref) {
          var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;

          if (key) {
            defineKeyPropWarningGetter(props, displayName);
          }

          if (ref) {
            defineRefPropWarningGetter(props, displayName);
          }
        }
      }
      return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
    }

    function cloneAndReplaceKey(oldElement, newKey) {
      var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props);
      return newElement;
    }
    /**
     * Clone and return a new ReactElement using element as the starting point.
     * See https://reactjs.org/docs/react-api.html#cloneelement
     */


    function cloneElement(element, config, children) {
      if (!!(element === null || element === undefined)) {
        {
          throw Error("React.cloneElement(...): The argument must be a React element, but you passed " + element + ".");
        }
      }

      var propName; // Original props are copied

      var props = _assign({}, element.props); // Reserved names are extracted


      var key = element.key;
      var ref = element.ref; // Self is preserved since the owner is preserved.

      var self = element._self; // Source is preserved since cloneElement is unlikely to be targeted by a
      // transpiler, and the original source is probably a better indicator of the
      // true owner.

      var source = element._source; // Owner will be preserved, unless ref is overridden

      var owner = element._owner;

      if (config != null) {
        if (hasValidRef(config)) {
          // Silently steal the ref from the parent.
          ref = config.ref;
          owner = ReactCurrentOwner.current;
        }

        if (hasValidKey(config)) {
          key = '' + config.key;
        } // Remaining properties override existing props


        var defaultProps;

        if (element.type && element.type.defaultProps) {
          defaultProps = element.type.defaultProps;
        }

        for (propName in config) {
          if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
            if (config[propName] === undefined && defaultProps !== undefined) {
              // Resolve default props
              props[propName] = defaultProps[propName];
            } else {
              props[propName] = config[propName];
            }
          }
        }
      } // Children can be more than one argument, and those are transferred onto
      // the newly allocated props object.


      var childrenLength = arguments.length - 2;

      if (childrenLength === 1) {
        props.children = children;
      } else if (childrenLength > 1) {
        var childArray = Array(childrenLength);

        for (var i = 0; i < childrenLength; i++) {
          childArray[i] = arguments[i + 2];
        }

        props.children = childArray;
      }

      return ReactElement(element.type, key, ref, self, source, owner, props);
    }
    /**
     * Verifies the object is a ReactElement.
     * See https://reactjs.org/docs/react-api.html#isvalidelement
     * @param {?object} object
     * @return {boolean} True if `object` is a ReactElement.
     * @final
     */


    function isValidElement(object) {
      return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
    }

    var SEPARATOR = '.';
    var SUBSEPARATOR = ':';
    /**
     * Escape and wrap key so it is safe to use as a reactid
     *
     * @param {string} key to be escaped.
     * @return {string} the escaped key.
     */

    function escape(key) {
      var escapeRegex = /[=:]/g;
      var escaperLookup = {
        '=': '=0',
        ':': '=2'
      };
      var escapedString = ('' + key).replace(escapeRegex, function (match) {
        return escaperLookup[match];
      });
      return '$' + escapedString;
    }
    /**
     * TODO: Test that a single child and an array with one item have the same key
     * pattern.
     */


    var didWarnAboutMaps = false;
    var userProvidedKeyEscapeRegex = /\/+/g;

    function escapeUserProvidedKey(text) {
      return ('' + text).replace(userProvidedKeyEscapeRegex, '$&/');
    }

    var POOL_SIZE = 10;
    var traverseContextPool = [];

    function getPooledTraverseContext(mapResult, keyPrefix, mapFunction, mapContext) {
      if (traverseContextPool.length) {
        var traverseContext = traverseContextPool.pop();
        traverseContext.result = mapResult;
        traverseContext.keyPrefix = keyPrefix;
        traverseContext.func = mapFunction;
        traverseContext.context = mapContext;
        traverseContext.count = 0;
        return traverseContext;
      } else {
        return {
          result: mapResult,
          keyPrefix: keyPrefix,
          func: mapFunction,
          context: mapContext,
          count: 0
        };
      }
    }

    function releaseTraverseContext(traverseContext) {
      traverseContext.result = null;
      traverseContext.keyPrefix = null;
      traverseContext.func = null;
      traverseContext.context = null;
      traverseContext.count = 0;

      if (traverseContextPool.length < POOL_SIZE) {
        traverseContextPool.push(traverseContext);
      }
    }
    /**
     * @param {?*} children Children tree container.
     * @param {!string} nameSoFar Name of the key path so far.
     * @param {!function} callback Callback to invoke with each child found.
     * @param {?*} traverseContext Used to pass information throughout the traversal
     * process.
     * @return {!number} The number of children in this subtree.
     */


    function traverseAllChildrenImpl(children, nameSoFar, callback, traverseContext) {
      var type = typeof children;

      if (type === 'undefined' || type === 'boolean') {
        // All of the above are perceived as null.
        children = null;
      }

      var invokeCallback = false;

      if (children === null) {
        invokeCallback = true;
      } else {
        switch (type) {
          case 'string':
          case 'number':
            invokeCallback = true;
            break;

          case 'object':
            switch (children.$$typeof) {
              case REACT_ELEMENT_TYPE:
              case REACT_PORTAL_TYPE:
                invokeCallback = true;
            }

        }
      }

      if (invokeCallback) {
        callback(traverseContext, children, // If it's the only child, treat the name as if it was wrapped in an array
        // so that it's consistent if the number of children grows.
        nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar);
        return 1;
      }

      var child;
      var nextName;
      var subtreeCount = 0; // Count of children found in the current subtree.

      var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR;

      if (Array.isArray(children)) {
        for (var i = 0; i < children.length; i++) {
          child = children[i];
          nextName = nextNamePrefix + getComponentKey(child, i);
          subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext);
        }
      } else {
        var iteratorFn = getIteratorFn(children);

        if (typeof iteratorFn === 'function') {
          {
            // Warn about using Maps as children
            if (iteratorFn === children.entries) {
              if (!didWarnAboutMaps) {
                warn('Using Maps as children is deprecated and will be removed in ' + 'a future major release. Consider converting children to ' + 'an array of keyed ReactElements instead.');
              }

              didWarnAboutMaps = true;
            }
          }
          var iterator = iteratorFn.call(children);
          var step;
          var ii = 0;

          while (!(step = iterator.next()).done) {
            child = step.value;
            nextName = nextNamePrefix + getComponentKey(child, ii++);
            subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext);
          }
        } else if (type === 'object') {
          var addendum = '';
          {
            addendum = ' If you meant to render a collection of children, use an array ' + 'instead.' + ReactDebugCurrentFrame.getStackAddendum();
          }
          var childrenString = '' + children;
          {
            {
              throw Error("Objects are not valid as a React child (found: " + (childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString) + ")." + addendum);
            }
          }
        }
      }

      return subtreeCount;
    }
    /**
     * Traverses children that are typically specified as `props.children`, but
     * might also be specified through attributes:
     *
     * - `traverseAllChildren(this.props.children, ...)`
     * - `traverseAllChildren(this.props.leftPanelChildren, ...)`
     *
     * The `traverseContext` is an optional argument that is passed through the
     * entire traversal. It can be used to store accumulations or anything else that
     * the callback might find relevant.
     *
     * @param {?*} children Children tree object.
     * @param {!function} callback To invoke upon traversing each child.
     * @param {?*} traverseContext Context for traversal.
     * @return {!number} The number of children in this subtree.
     */


    function traverseAllChildren(children, callback, traverseContext) {
      if (children == null) {
        return 0;
      }

      return traverseAllChildrenImpl(children, '', callback, traverseContext);
    }
    /**
     * Generate a key string that identifies a component within a set.
     *
     * @param {*} component A component that could contain a manual key.
     * @param {number} index Index that is used if a manual key is not provided.
     * @return {string}
     */


    function getComponentKey(component, index) {
      // Do some typechecking here since we call this blindly. We want to ensure
      // that we don't block potential future ES APIs.
      if (typeof component === 'object' && component !== null && component.key != null) {
        // Explicit key
        return escape(component.key);
      } // Implicit key determined by the index in the set


      return index.toString(36);
    }

    function forEachSingleChild(bookKeeping, child, name) {
      var func = bookKeeping.func,
          context = bookKeeping.context;
      func.call(context, child, bookKeeping.count++);
    }
    /**
     * Iterates through children that are typically specified as `props.children`.
     *
     * See https://reactjs.org/docs/react-api.html#reactchildrenforeach
     *
     * The provided forEachFunc(child, index) will be called for each
     * leaf child.
     *
     * @param {?*} children Children tree container.
     * @param {function(*, int)} forEachFunc
     * @param {*} forEachContext Context for forEachContext.
     */


    function forEachChildren(children, forEachFunc, forEachContext) {
      if (children == null) {
        return children;
      }

      var traverseContext = getPooledTraverseContext(null, null, forEachFunc, forEachContext);
      traverseAllChildren(children, forEachSingleChild, traverseContext);
      releaseTraverseContext(traverseContext);
    }

    function mapSingleChildIntoContext(bookKeeping, child, childKey) {
      var result = bookKeeping.result,
          keyPrefix = bookKeeping.keyPrefix,
          func = bookKeeping.func,
          context = bookKeeping.context;
      var mappedChild = func.call(context, child, bookKeeping.count++);

      if (Array.isArray(mappedChild)) {
        mapIntoWithKeyPrefixInternal(mappedChild, result, childKey, function (c) {
          return c;
        });
      } else if (mappedChild != null) {
        if (isValidElement(mappedChild)) {
          mappedChild = cloneAndReplaceKey(mappedChild, // Keep both the (mapped) and old keys if they differ, just as
          // traverseAllChildren used to do for objects as children
          keyPrefix + (mappedChild.key && (!child || child.key !== mappedChild.key) ? escapeUserProvidedKey(mappedChild.key) + '/' : '') + childKey);
        }

        result.push(mappedChild);
      }
    }

    function mapIntoWithKeyPrefixInternal(children, array, prefix, func, context) {
      var escapedPrefix = '';

      if (prefix != null) {
        escapedPrefix = escapeUserProvidedKey(prefix) + '/';
      }

      var traverseContext = getPooledTraverseContext(array, escapedPrefix, func, context);
      traverseAllChildren(children, mapSingleChildIntoContext, traverseContext);
      releaseTraverseContext(traverseContext);
    }
    /**
     * Maps children that are typically specified as `props.children`.
     *
     * See https://reactjs.org/docs/react-api.html#reactchildrenmap
     *
     * The provided mapFunction(child, key, index) will be called for each
     * leaf child.
     *
     * @param {?*} children Children tree container.
     * @param {function(*, int)} func The map function.
     * @param {*} context Context for mapFunction.
     * @return {object} Object containing the ordered map of results.
     */


    function mapChildren(children, func, context) {
      if (children == null) {
        return children;
      }

      var result = [];
      mapIntoWithKeyPrefixInternal(children, result, null, func, context);
      return result;
    }
    /**
     * Count the number of children that are typically specified as
     * `props.children`.
     *
     * See https://reactjs.org/docs/react-api.html#reactchildrencount
     *
     * @param {?*} children Children tree container.
     * @return {number} The number of children.
     */


    function countChildren(children) {
      return traverseAllChildren(children, function () {
        return null;
      }, null);
    }
    /**
     * Flatten a children object (typically specified as `props.children`) and
     * return an array with appropriately re-keyed children.
     *
     * See https://reactjs.org/docs/react-api.html#reactchildrentoarray
     */


    function toArray(children) {
      var result = [];
      mapIntoWithKeyPrefixInternal(children, result, null, function (child) {
        return child;
      });
      return result;
    }
    /**
     * Returns the first child in a collection of children and verifies that there
     * is only one child in the collection.
     *
     * See https://reactjs.org/docs/react-api.html#reactchildrenonly
     *
     * The current implementation of this function assumes that a single child gets
     * passed without a wrapper, but the purpose of this helper function is to
     * abstract away the particular structure of children.
     *
     * @param {?object} children Child collection structure.
     * @return {ReactElement} The first and only `ReactElement` contained in the
     * structure.
     */


    function onlyChild(children) {
      if (!isValidElement(children)) {
        {
          throw Error("React.Children.only expected to receive a single React element child.");
        }
      }

      return children;
    }

    function createContext(defaultValue, calculateChangedBits) {
      if (calculateChangedBits === undefined) {
        calculateChangedBits = null;
      } else {
        {
          if (calculateChangedBits !== null && typeof calculateChangedBits !== 'function') {
            error('createContext: Expected the optional second argument to be a ' + 'function. Instead received: %s', calculateChangedBits);
          }
        }
      }

      var context = {
        $$typeof: REACT_CONTEXT_TYPE,
        _calculateChangedBits: calculateChangedBits,
        // As a workaround to support multiple concurrent renderers, we categorize
        // some renderers as primary and others as secondary. We only expect
        // there to be two concurrent renderers at most: React Native (primary) and
        // Fabric (secondary); React DOM (primary) and React ART (secondary).
        // Secondary renderers store their context values on separate fields.
        _currentValue: defaultValue,
        _currentValue2: defaultValue,
        // Used to track how many concurrent renderers this context currently
        // supports within in a single renderer. Such as parallel server rendering.
        _threadCount: 0,
        // These are circular
        Provider: null,
        Consumer: null
      };
      context.Provider = {
        $$typeof: REACT_PROVIDER_TYPE,
        _context: context
      };
      var hasWarnedAboutUsingNestedContextConsumers = false;
      var hasWarnedAboutUsingConsumerProvider = false;
      {
        // A separate object, but proxies back to the original context object for
        // backwards compatibility. It has a different $$typeof, so we can properly
        // warn for the incorrect usage of Context as a Consumer.
        var Consumer = {
          $$typeof: REACT_CONTEXT_TYPE,
          _context: context,
          _calculateChangedBits: context._calculateChangedBits
        }; // $FlowFixMe: Flow complains about not setting a value, which is intentional here

        Object.defineProperties(Consumer, {
          Provider: {
            get: function () {
              if (!hasWarnedAboutUsingConsumerProvider) {
                hasWarnedAboutUsingConsumerProvider = true;
                error('Rendering <Context.Consumer.Provider> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Provider> instead?');
              }

              return context.Provider;
            },
            set: function (_Provider) {
              context.Provider = _Provider;
            }
          },
          _currentValue: {
            get: function () {
              return context._currentValue;
            },
            set: function (_currentValue) {
              context._currentValue = _currentValue;
            }
          },
          _currentValue2: {
            get: function () {
              return context._currentValue2;
            },
            set: function (_currentValue2) {
              context._currentValue2 = _currentValue2;
            }
          },
          _threadCount: {
            get: function () {
              return context._threadCount;
            },
            set: function (_threadCount) {
              context._threadCount = _threadCount;
            }
          },
          Consumer: {
            get: function () {
              if (!hasWarnedAboutUsingNestedContextConsumers) {
                hasWarnedAboutUsingNestedContextConsumers = true;
                error('Rendering <Context.Consumer.Consumer> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?');
              }

              return context.Consumer;
            }
          }
        }); // $FlowFixMe: Flow complains about missing properties because it doesn't understand defineProperty

        context.Consumer = Consumer;
      }
      {
        context._currentRenderer = null;
        context._currentRenderer2 = null;
      }
      return context;
    }

    function lazy(ctor) {
      var lazyType = {
        $$typeof: REACT_LAZY_TYPE,
        _ctor: ctor,
        // React uses these fields to store the result.
        _status: -1,
        _result: null
      };
      {
        // In production, this would just set it on the object.
        var defaultProps;
        var propTypes;
        Object.defineProperties(lazyType, {
          defaultProps: {
            configurable: true,
            get: function () {
              return defaultProps;
            },
            set: function (newDefaultProps) {
              error('React.lazy(...): It is not supported to assign `defaultProps` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.');
              defaultProps = newDefaultProps; // Match production behavior more closely:

              Object.defineProperty(lazyType, 'defaultProps', {
                enumerable: true
              });
            }
          },
          propTypes: {
            configurable: true,
            get: function () {
              return propTypes;
            },
            set: function (newPropTypes) {
              error('React.lazy(...): It is not supported to assign `propTypes` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.');
              propTypes = newPropTypes; // Match production behavior more closely:

              Object.defineProperty(lazyType, 'propTypes', {
                enumerable: true
              });
            }
          }
        });
      }
      return lazyType;
    }

    function forwardRef(render) {
      {
        if (render != null && render.$$typeof === REACT_MEMO_TYPE) {
          error('forwardRef requires a render function but received a `memo` ' + 'component. Instead of forwardRef(memo(...)), use ' + 'memo(forwardRef(...)).');
        } else if (typeof render !== 'function') {
          error('forwardRef requires a render function but was given %s.', render === null ? 'null' : typeof render);
        } else {
          if (render.length !== 0 && render.length !== 2) {
            error('forwardRef render functions accept exactly two parameters: props and ref. %s', render.length === 1 ? 'Did you forget to use the ref parameter?' : 'Any additional parameter will be undefined.');
          }
        }

        if (render != null) {
          if (render.defaultProps != null || render.propTypes != null) {
            error('forwardRef render functions do not support propTypes or defaultProps. ' + 'Did you accidentally pass a React component?');
          }
        }
      }
      return {
        $$typeof: REACT_FORWARD_REF_TYPE,
        render: render
      };
    }

    function isValidElementType(type) {
      return typeof type === 'string' || typeof type === 'function' || // Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill.
      type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || typeof type === 'object' && type !== null && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_RESPONDER_TYPE || type.$$typeof === REACT_SCOPE_TYPE || type.$$typeof === REACT_BLOCK_TYPE);
    }

    function memo(type, compare) {
      {
        if (!isValidElementType(type)) {
          error('memo: The first argument must be a component. Instead ' + 'received: %s', type === null ? 'null' : typeof type);
        }
      }
      return {
        $$typeof: REACT_MEMO_TYPE,
        type: type,
        compare: compare === undefined ? null : compare
      };
    }

    function resolveDispatcher() {
      var dispatcher = ReactCurrentDispatcher.current;

      if (!(dispatcher !== null)) {
        {
          throw Error("Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.");
        }
      }

      return dispatcher;
    }

    function useContext(Context, unstable_observedBits) {
      var dispatcher = resolveDispatcher();
      {
        if (unstable_observedBits !== undefined) {
          error('useContext() second argument is reserved for future ' + 'use in React. Passing it is not supported. ' + 'You passed: %s.%s', unstable_observedBits, typeof unstable_observedBits === 'number' && Array.isArray(arguments[2]) ? '\n\nDid you call array.map(useContext)? ' + 'Calling Hooks inside a loop is not supported. ' + 'Learn more at https://fb.me/rules-of-hooks' : '');
        } // TODO: add a more generic warning for invalid values.


        if (Context._context !== undefined) {
          var realContext = Context._context; // Don't deduplicate because this legitimately causes bugs
          // and nobody should be using this in existing code.

          if (realContext.Consumer === Context) {
            error('Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be ' + 'removed in a future major release. Did you mean to call useContext(Context) instead?');
          } else if (realContext.Provider === Context) {
            error('Calling useContext(Context.Provider) is not supported. ' + 'Did you mean to call useContext(Context) instead?');
          }
        }
      }
      return dispatcher.useContext(Context, unstable_observedBits);
    }

    function useState(initialState) {
      var dispatcher = resolveDispatcher();
      return dispatcher.useState(initialState);
    }

    function useReducer(reducer, initialArg, init) {
      var dispatcher = resolveDispatcher();
      return dispatcher.useReducer(reducer, initialArg, init);
    }

    function useRef(initialValue) {
      var dispatcher = resolveDispatcher();
      return dispatcher.useRef(initialValue);
    }

    function useEffect(create, deps) {
      var dispatcher = resolveDispatcher();
      return dispatcher.useEffect(create, deps);
    }

    function useLayoutEffect(create, deps) {
      var dispatcher = resolveDispatcher();
      return dispatcher.useLayoutEffect(create, deps);
    }

    function useCallback(callback, deps) {
      var dispatcher = resolveDispatcher();
      return dispatcher.useCallback(callback, deps);
    }

    function useMemo(create, deps) {
      var dispatcher = resolveDispatcher();
      return dispatcher.useMemo(create, deps);
    }

    function useImperativeHandle(ref, create, deps) {
      var dispatcher = resolveDispatcher();
      return dispatcher.useImperativeHandle(ref, create, deps);
    }

    function useDebugValue(value, formatterFn) {
      {
        var dispatcher = resolveDispatcher();
        return dispatcher.useDebugValue(value, formatterFn);
      }
    }

    var propTypesMisspellWarningShown;
    {
      propTypesMisspellWarningShown = false;
    }

    function getDeclarationErrorAddendum() {
      if (ReactCurrentOwner.current) {
        var name = getComponentName(ReactCurrentOwner.current.type);

        if (name) {
          return '\n\nCheck the render method of `' + name + '`.';
        }
      }

      return '';
    }

    function getSourceInfoErrorAddendum(source) {
      if (source !== undefined) {
        var fileName = source.fileName.replace(/^.*[\\\/]/, '');
        var lineNumber = source.lineNumber;
        return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.';
      }

      return '';
    }

    function getSourceInfoErrorAddendumForProps(elementProps) {
      if (elementProps !== null && elementProps !== undefined) {
        return getSourceInfoErrorAddendum(elementProps.__source);
      }

      return '';
    }
    /**
     * Warn if there's no key explicitly set on dynamic arrays of children or
     * object keys are not valid. This allows us to keep track of children between
     * updates.
     */


    var ownerHasKeyUseWarning = {};

    function getCurrentComponentErrorInfo(parentType) {
      var info = getDeclarationErrorAddendum();

      if (!info) {
        var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;

        if (parentName) {
          info = "\n\nCheck the top-level render call using <" + parentName + ">.";
        }
      }

      return info;
    }
    /**
     * Warn if the element doesn't have an explicit key assigned to it.
     * This element is in an array. The array could grow and shrink or be
     * reordered. All children that haven't already been validated are required to
     * have a "key" property assigned to it. Error statuses are cached so a warning
     * will only be shown once.
     *
     * @internal
     * @param {ReactElement} element Element that requires a key.
     * @param {*} parentType element's parent's type.
     */


    function validateExplicitKey(element, parentType) {
      if (!element._store || element._store.validated || element.key != null) {
        return;
      }

      element._store.validated = true;
      var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);

      if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
        return;
      }

      ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a
      // property, it may be the creator of the child that's responsible for
      // assigning it a key.

      var childOwner = '';

      if (element && element._owner && element._owner !== ReactCurrentOwner.current) {
        // Give the component that originally created this child.
        childOwner = " It was passed a child from " + getComponentName(element._owner.type) + ".";
      }

      setCurrentlyValidatingElement(element);
      {
        error('Each child in a list should have a unique "key" prop.' + '%s%s See https://fb.me/react-warning-keys for more information.', currentComponentErrorInfo, childOwner);
      }
      setCurrentlyValidatingElement(null);
    }
    /**
     * Ensure that every element either is passed in a static location, in an
     * array with an explicit keys property defined, or in an object literal
     * with valid key property.
     *
     * @internal
     * @param {ReactNode} node Statically passed child of any type.
     * @param {*} parentType node's parent's type.
     */


    function validateChildKeys(node, parentType) {
      if (typeof node !== 'object') {
        return;
      }

      if (Array.isArray(node)) {
        for (var i = 0; i < node.length; i++) {
          var child = node[i];

          if (isValidElement(child)) {
            validateExplicitKey(child, parentType);
          }
        }
      } else if (isValidElement(node)) {
        // This element was passed in a valid location.
        if (node._store) {
          node._store.validated = true;
        }
      } else if (node) {
        var iteratorFn = getIteratorFn(node);

        if (typeof iteratorFn === 'function') {
          // Entry iterators used to provide implicit keys,
          // but now we print a separate warning for them later.
          if (iteratorFn !== node.entries) {
            var iterator = iteratorFn.call(node);
            var step;

            while (!(step = iterator.next()).done) {
              if (isValidElement(step.value)) {
                validateExplicitKey(step.value, parentType);
              }
            }
          }
        }
      }
    }
    /**
     * Given an element, validate that its props follow the propTypes definition,
     * provided by the type.
     *
     * @param {ReactElement} element
     */


    function validatePropTypes(element) {
      {
        var type = element.type;

        if (type === null || type === undefined || typeof type === 'string') {
          return;
        }

        var name = getComponentName(type);
        var propTypes;

        if (typeof type === 'function') {
          propTypes = type.propTypes;
        } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here.
        // Inner props are checked in the reconciler.
        type.$$typeof === REACT_MEMO_TYPE)) {
          propTypes = type.propTypes;
        } else {
          return;
        }

        if (propTypes) {
          setCurrentlyValidatingElement(element);
          checkPropTypes(propTypes, element.props, 'prop', name, ReactDebugCurrentFrame.getStackAddendum);
          setCurrentlyValidatingElement(null);
        } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) {
          propTypesMisspellWarningShown = true;
          error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', name || 'Unknown');
        }

        if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) {
          error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.');
        }
      }
    }
    /**
     * Given a fragment, validate that it can only be provided with fragment props
     * @param {ReactElement} fragment
     */


    function validateFragmentProps(fragment) {
      {
        setCurrentlyValidatingElement(fragment);
        var keys = Object.keys(fragment.props);

        for (var i = 0; i < keys.length; i++) {
          var key = keys[i];

          if (key !== 'children' && key !== 'key') {
            error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key);
            break;
          }
        }

        if (fragment.ref !== null) {
          error('Invalid attribute `ref` supplied to `React.Fragment`.');
        }

        setCurrentlyValidatingElement(null);
      }
    }

    function createElementWithValidation(type, props, children) {
      var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to
      // succeed and there will likely be errors in render.

      if (!validType) {
        var info = '';

        if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
          info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports.";
        }

        var sourceInfo = getSourceInfoErrorAddendumForProps(props);

        if (sourceInfo) {
          info += sourceInfo;
        } else {
          info += getDeclarationErrorAddendum();
        }

        var typeString;

        if (type === null) {
          typeString = 'null';
        } else if (Array.isArray(type)) {
          typeString = 'array';
        } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {
          typeString = "<" + (getComponentName(type.type) || 'Unknown') + " />";
          info = ' Did you accidentally export a JSX literal instead of a component?';
        } else {
          typeString = typeof type;
        }

        {
          error('React.createElement: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info);
        }
      }

      var element = createElement.apply(this, arguments); // The result can be nullish if a mock or a custom function is used.
      // TODO: Drop this when these are no longer allowed as the type argument.

      if (element == null) {
        return element;
      } // Skip key warning if the type isn't valid since our key validation logic
      // doesn't expect a non-string/function type and can throw confusing errors.
      // We don't want exception behavior to differ between dev and prod.
      // (Rendering will throw with a helpful message and as soon as the type is
      // fixed, the key warnings will appear.)


      if (validType) {
        for (var i = 2; i < arguments.length; i++) {
          validateChildKeys(arguments[i], type);
        }
      }

      if (type === REACT_FRAGMENT_TYPE) {
        validateFragmentProps(element);
      } else {
        validatePropTypes(element);
      }

      return element;
    }

    var didWarnAboutDeprecatedCreateFactory = false;

    function createFactoryWithValidation(type) {
      var validatedFactory = createElementWithValidation.bind(null, type);
      validatedFactory.type = type;
      {
        if (!didWarnAboutDeprecatedCreateFactory) {
          didWarnAboutDeprecatedCreateFactory = true;
          warn('React.createFactory() is deprecated and will be removed in ' + 'a future major release. Consider using JSX ' + 'or use React.createElement() directly instead.');
        } // Legacy hook: remove it


        Object.defineProperty(validatedFactory, 'type', {
          enumerable: false,
          get: function () {
            warn('Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.');
            Object.defineProperty(this, 'type', {
              value: type
            });
            return type;
          }
        });
      }
      return validatedFactory;
    }

    function cloneElementWithValidation(element, props, children) {
      var newElement = cloneElement.apply(this, arguments);

      for (var i = 2; i < arguments.length; i++) {
        validateChildKeys(arguments[i], newElement.type);
      }

      validatePropTypes(newElement);
      return newElement;
    }

    {
      try {
        var frozenObject = Object.freeze({});
        var testMap = new Map([[frozenObject, null]]);
        var testSet = new Set([frozenObject]); // This is necessary for Rollup to not consider these unused.
        // https://github.com/rollup/rollup/issues/1771
        // TODO: we can remove these if Rollup fixes the bug.

        testMap.set(0, 0);
        testSet.add(0);
      } catch (e) {}
    }
    var createElement$1 = createElementWithValidation;
    var cloneElement$1 = cloneElementWithValidation;
    var createFactory = createFactoryWithValidation;
    var Children = {
      map: mapChildren,
      forEach: forEachChildren,
      count: countChildren,
      toArray: toArray,
      only: onlyChild
    };
    exports.Children = Children;
    exports.Component = Component;
    exports.Fragment = REACT_FRAGMENT_TYPE;
    exports.Profiler = REACT_PROFILER_TYPE;
    exports.PureComponent = PureComponent;
    exports.StrictMode = REACT_STRICT_MODE_TYPE;
    exports.Suspense = REACT_SUSPENSE_TYPE;
    exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals;
    exports.cloneElement = cloneElement$1;
    exports.createContext = createContext;
    exports.createElement = createElement$1;
    exports.createFactory = createFactory;
    exports.createRef = createRef;
    exports.forwardRef = forwardRef;
    exports.isValidElement = isValidElement;
    exports.lazy = lazy;
    exports.memo = memo;
    exports.useCallback = useCallback;
    exports.useContext = useContext;
    exports.useDebugValue = useDebugValue;
    exports.useEffect = useEffect;
    exports.useImperativeHandle = useImperativeHandle;
    exports.useLayoutEffect = useLayoutEffect;
    exports.useMemo = useMemo;
    exports.useReducer = useReducer;
    exports.useRef = useRef;
    exports.useState = useState;
    exports.version = ReactVersion;
  })();
}
},{"object-assign":"../node_modules/object-assign/index.js","prop-types/checkPropTypes":"../node_modules/prop-types/checkPropTypes.js"}],"../node_modules/react/index.js":[function(require,module,exports) {
'use strict';

if ("development" === 'production') {
  module.exports = require('./cjs/react.production.min.js');
} else {
  module.exports = require('./cjs/react.development.js');
}
},{"./cjs/react.development.js":"../node_modules/react/cjs/react.development.js"}],"../node_modules/scheduler/cjs/scheduler.development.js":[function(require,module,exports) {
/** @license React v0.19.1
 * scheduler.development.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
'use strict';

if ("development" !== "production") {
  (function () {
    'use strict';

    var enableSchedulerDebugging = false;
    var enableProfiling = true;
    var requestHostCallback;
    var requestHostTimeout;
    var cancelHostTimeout;
    var shouldYieldToHost;
    var requestPaint;

    if ( // If Scheduler runs in a non-DOM environment, it falls back to a naive
    // implementation using setTimeout.
    typeof window === 'undefined' || // Check if MessageChannel is supported, too.
    typeof MessageChannel !== 'function') {
      // If this accidentally gets imported in a non-browser environment, e.g. JavaScriptCore,
      // fallback to a naive implementation.
      var _callback = null;
      var _timeoutID = null;

      var _flushCallback = function () {
        if (_callback !== null) {
          try {
            var currentTime = exports.unstable_now();
            var hasRemainingTime = true;

            _callback(hasRemainingTime, currentTime);

            _callback = null;
          } catch (e) {
            setTimeout(_flushCallback, 0);
            throw e;
          }
        }
      };

      var initialTime = Date.now();

      exports.unstable_now = function () {
        return Date.now() - initialTime;
      };

      requestHostCallback = function (cb) {
        if (_callback !== null) {
          // Protect against re-entrancy.
          setTimeout(requestHostCallback, 0, cb);
        } else {
          _callback = cb;
          setTimeout(_flushCallback, 0);
        }
      };

      requestHostTimeout = function (cb, ms) {
        _timeoutID = setTimeout(cb, ms);
      };

      cancelHostTimeout = function () {
        clearTimeout(_timeoutID);
      };

      shouldYieldToHost = function () {
        return false;
      };

      requestPaint = exports.unstable_forceFrameRate = function () {};
    } else {
      // Capture local references to native APIs, in case a polyfill overrides them.
      var performance = window.performance;
      var _Date = window.Date;
      var _setTimeout = window.setTimeout;
      var _clearTimeout = window.clearTimeout;

      if (typeof console !== 'undefined') {
        // TODO: Scheduler no longer requires these methods to be polyfilled. But
        // maybe we want to continue warning if they don't exist, to preserve the
        // option to rely on it in the future?
        var requestAnimationFrame = window.requestAnimationFrame;
        var cancelAnimationFrame = window.cancelAnimationFrame; // TODO: Remove fb.me link

        if (typeof requestAnimationFrame !== 'function') {
          // Using console['error'] to evade Babel and ESLint
          console['error']("This browser doesn't support requestAnimationFrame. " + 'Make sure that you load a ' + 'polyfill in older browsers. https://fb.me/react-polyfills');
        }

        if (typeof cancelAnimationFrame !== 'function') {
          // Using console['error'] to evade Babel and ESLint
          console['error']("This browser doesn't support cancelAnimationFrame. " + 'Make sure that you load a ' + 'polyfill in older browsers. https://fb.me/react-polyfills');
        }
      }

      if (typeof performance === 'object' && typeof performance.now === 'function') {
        exports.unstable_now = function () {
          return performance.now();
        };
      } else {
        var _initialTime = _Date.now();

        exports.unstable_now = function () {
          return _Date.now() - _initialTime;
        };
      }

      var isMessageLoopRunning = false;
      var scheduledHostCallback = null;
      var taskTimeoutID = -1; // Scheduler periodically yields in case there is other work on the main
      // thread, like user events. By default, it yields multiple times per frame.
      // It does not attempt to align with frame boundaries, since most tasks don't
      // need to be frame aligned; for those that do, use requestAnimationFrame.

      var yieldInterval = 5;
      var deadline = 0; // TODO: Make this configurable

      {
        // `isInputPending` is not available. Since we have no way of knowing if
        // there's pending input, always yield at the end of the frame.
        shouldYieldToHost = function () {
          return exports.unstable_now() >= deadline;
        }; // Since we yield every frame regardless, `requestPaint` has no effect.


        requestPaint = function () {};
      }

      exports.unstable_forceFrameRate = function (fps) {
        if (fps < 0 || fps > 125) {
          // Using console['error'] to evade Babel and ESLint
          console['error']('forceFrameRate takes a positive int between 0 and 125, ' + 'forcing framerates higher than 125 fps is not unsupported');
          return;
        }

        if (fps > 0) {
          yieldInterval = Math.floor(1000 / fps);
        } else {
          // reset the framerate
          yieldInterval = 5;
        }
      };

      var performWorkUntilDeadline = function () {
        if (scheduledHostCallback !== null) {
          var currentTime = exports.unstable_now(); // Yield after `yieldInterval` ms, regardless of where we are in the vsync
          // cycle. This means there's always time remaining at the beginning of
          // the message event.

          deadline = currentTime + yieldInterval;
          var hasTimeRemaining = true;

          try {
            var hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime);

            if (!hasMoreWork) {
              isMessageLoopRunning = false;
              scheduledHostCallback = null;
            } else {
              // If there's more work, schedule the next message event at the end
              // of the preceding one.
              port.postMessage(null);
            }
          } catch (error) {
            // If a scheduler task throws, exit the current browser task so the
            // error can be observed.
            port.postMessage(null);
            throw error;
          }
        } else {
          isMessageLoopRunning = false;
        } // Yielding to the browser will give it a chance to paint, so we can

      };

      var channel = new MessageChannel();
      var port = channel.port2;
      channel.port1.onmessage = performWorkUntilDeadline;

      requestHostCallback = function (callback) {
        scheduledHostCallback = callback;

        if (!isMessageLoopRunning) {
          isMessageLoopRunning = true;
          port.postMessage(null);
        }
      };

      requestHostTimeout = function (callback, ms) {
        taskTimeoutID = _setTimeout(function () {
          callback(exports.unstable_now());
        }, ms);
      };

      cancelHostTimeout = function () {
        _clearTimeout(taskTimeoutID);

        taskTimeoutID = -1;
      };
    }

    function push(heap, node) {
      var index = heap.length;
      heap.push(node);
      siftUp(heap, node, index);
    }

    function peek(heap) {
      var first = heap[0];
      return first === undefined ? null : first;
    }

    function pop(heap) {
      var first = heap[0];

      if (first !== undefined) {
        var last = heap.pop();

        if (last !== first) {
          heap[0] = last;
          siftDown(heap, last, 0);
        }

        return first;
      } else {
        return null;
      }
    }

    function siftUp(heap, node, i) {
      var index = i;

      while (true) {
        var parentIndex = index - 1 >>> 1;
        var parent = heap[parentIndex];

        if (parent !== undefined && compare(parent, node) > 0) {
          // The parent is larger. Swap positions.
          heap[parentIndex] = node;
          heap[index] = parent;
          index = parentIndex;
        } else {
          // The parent is smaller. Exit.
          return;
        }
      }
    }

    function siftDown(heap, node, i) {
      var index = i;
      var length = heap.length;

      while (index < length) {
        var leftIndex = (index + 1) * 2 - 1;
        var left = heap[leftIndex];
        var rightIndex = leftIndex + 1;
        var right = heap[rightIndex]; // If the left or right node is smaller, swap with the smaller of those.

        if (left !== undefined && compare(left, node) < 0) {
          if (right !== undefined && compare(right, left) < 0) {
            heap[index] = right;
            heap[rightIndex] = node;
            index = rightIndex;
          } else {
            heap[index] = left;
            heap[leftIndex] = node;
            index = leftIndex;
          }
        } else if (right !== undefined && compare(right, node) < 0) {
          heap[index] = right;
          heap[rightIndex] = node;
          index = rightIndex;
        } else {
          // Neither child is smaller. Exit.
          return;
        }
      }
    }

    function compare(a, b) {
      // Compare sort index first, then task id.
      var diff = a.sortIndex - b.sortIndex;
      return diff !== 0 ? diff : a.id - b.id;
    } // TODO: Use symbols?


    var NoPriority = 0;
    var ImmediatePriority = 1;
    var UserBlockingPriority = 2;
    var NormalPriority = 3;
    var LowPriority = 4;
    var IdlePriority = 5;
    var runIdCounter = 0;
    var mainThreadIdCounter = 0;
    var profilingStateSize = 4;
    var sharedProfilingBuffer = // $FlowFixMe Flow doesn't know about SharedArrayBuffer
    typeof SharedArrayBuffer === 'function' ? new SharedArrayBuffer(profilingStateSize * Int32Array.BYTES_PER_ELEMENT) : // $FlowFixMe Flow doesn't know about ArrayBuffer
    typeof ArrayBuffer === 'function' ? new ArrayBuffer(profilingStateSize * Int32Array.BYTES_PER_ELEMENT) : null // Don't crash the init path on IE9
    ;
    var profilingState = sharedProfilingBuffer !== null ? new Int32Array(sharedProfilingBuffer) : []; // We can't read this but it helps save bytes for null checks

    var PRIORITY = 0;
    var CURRENT_TASK_ID = 1;
    var CURRENT_RUN_ID = 2;
    var QUEUE_SIZE = 3;
    {
      profilingState[PRIORITY] = NoPriority; // This is maintained with a counter, because the size of the priority queue
      // array might include canceled tasks.

      profilingState[QUEUE_SIZE] = 0;
      profilingState[CURRENT_TASK_ID] = 0;
    } // Bytes per element is 4

    var INITIAL_EVENT_LOG_SIZE = 131072;
    var MAX_EVENT_LOG_SIZE = 524288; // Equivalent to 2 megabytes

    var eventLogSize = 0;
    var eventLogBuffer = null;
    var eventLog = null;
    var eventLogIndex = 0;
    var TaskStartEvent = 1;
    var TaskCompleteEvent = 2;
    var TaskErrorEvent = 3;
    var TaskCancelEvent = 4;
    var TaskRunEvent = 5;
    var TaskYieldEvent = 6;
    var SchedulerSuspendEvent = 7;
    var SchedulerResumeEvent = 8;

    function logEvent(entries) {
      if (eventLog !== null) {
        var offset = eventLogIndex;
        eventLogIndex += entries.length;

        if (eventLogIndex + 1 > eventLogSize) {
          eventLogSize *= 2;

          if (eventLogSize > MAX_EVENT_LOG_SIZE) {
            // Using console['error'] to evade Babel and ESLint
            console['error']("Scheduler Profiling: Event log exceeded maximum size. Don't " + 'forget to call `stopLoggingProfilingEvents()`.');
            stopLoggingProfilingEvents();
            return;
          }

          var newEventLog = new Int32Array(eventLogSize * 4);
          newEventLog.set(eventLog);
          eventLogBuffer = newEventLog.buffer;
          eventLog = newEventLog;
        }

        eventLog.set(entries, offset);
      }
    }

    function startLoggingProfilingEvents() {
      eventLogSize = INITIAL_EVENT_LOG_SIZE;
      eventLogBuffer = new ArrayBuffer(eventLogSize * 4);
      eventLog = new Int32Array(eventLogBuffer);
      eventLogIndex = 0;
    }

    function stopLoggingProfilingEvents() {
      var buffer = eventLogBuffer;
      eventLogSize = 0;
      eventLogBuffer = null;
      eventLog = null;
      eventLogIndex = 0;
      return buffer;
    }

    function markTaskStart(task, ms) {
      {
        profilingState[QUEUE_SIZE]++;

        if (eventLog !== null) {
          // performance.now returns a float, representing milliseconds. When the
          // event is logged, it's coerced to an int. Convert to microseconds to
          // maintain extra degrees of precision.
          logEvent([TaskStartEvent, ms * 1000, task.id, task.priorityLevel]);
        }
      }
    }

    function markTaskCompleted(task, ms) {
      {
        profilingState[PRIORITY] = NoPriority;
        profilingState[CURRENT_TASK_ID] = 0;
        profilingState[QUEUE_SIZE]--;

        if (eventLog !== null) {
          logEvent([TaskCompleteEvent, ms * 1000, task.id]);
        }
      }
    }

    function markTaskCanceled(task, ms) {
      {
        profilingState[QUEUE_SIZE]--;

        if (eventLog !== null) {
          logEvent([TaskCancelEvent, ms * 1000, task.id]);
        }
      }
    }

    function markTaskErrored(task, ms) {
      {
        profilingState[PRIORITY] = NoPriority;
        profilingState[CURRENT_TASK_ID] = 0;
        profilingState[QUEUE_SIZE]--;

        if (eventLog !== null) {
          logEvent([TaskErrorEvent, ms * 1000, task.id]);
        }
      }
    }

    function markTaskRun(task, ms) {
      {
        runIdCounter++;
        profilingState[PRIORITY] = task.priorityLevel;
        profilingState[CURRENT_TASK_ID] = task.id;
        profilingState[CURRENT_RUN_ID] = runIdCounter;

        if (eventLog !== null) {
          logEvent([TaskRunEvent, ms * 1000, task.id, runIdCounter]);
        }
      }
    }

    function markTaskYield(task, ms) {
      {
        profilingState[PRIORITY] = NoPriority;
        profilingState[CURRENT_TASK_ID] = 0;
        profilingState[CURRENT_RUN_ID] = 0;

        if (eventLog !== null) {
          logEvent([TaskYieldEvent, ms * 1000, task.id, runIdCounter]);
        }
      }
    }

    function markSchedulerSuspended(ms) {
      {
        mainThreadIdCounter++;

        if (eventLog !== null) {
          logEvent([SchedulerSuspendEvent, ms * 1000, mainThreadIdCounter]);
        }
      }
    }

    function markSchedulerUnsuspended(ms) {
      {
        if (eventLog !== null) {
          logEvent([SchedulerResumeEvent, ms * 1000, mainThreadIdCounter]);
        }
      }
    }
    /* eslint-disable no-var */
    // Math.pow(2, 30) - 1
    // 0b111111111111111111111111111111


    var maxSigned31BitInt = 1073741823; // Times out immediately

    var IMMEDIATE_PRIORITY_TIMEOUT = -1; // Eventually times out

    var USER_BLOCKING_PRIORITY = 250;
    var NORMAL_PRIORITY_TIMEOUT = 5000;
    var LOW_PRIORITY_TIMEOUT = 10000; // Never times out

    var IDLE_PRIORITY = maxSigned31BitInt; // Tasks are stored on a min heap

    var taskQueue = [];
    var timerQueue = []; // Incrementing id counter. Used to maintain insertion order.

    var taskIdCounter = 1; // Pausing the scheduler is useful for debugging.

    var currentTask = null;
    var currentPriorityLevel = NormalPriority; // This is set while performing work, to prevent re-entrancy.

    var isPerformingWork = false;
    var isHostCallbackScheduled = false;
    var isHostTimeoutScheduled = false;

    function advanceTimers(currentTime) {
      // Check for tasks that are no longer delayed and add them to the queue.
      var timer = peek(timerQueue);

      while (timer !== null) {
        if (timer.callback === null) {
          // Timer was cancelled.
          pop(timerQueue);
        } else if (timer.startTime <= currentTime) {
          // Timer fired. Transfer to the task queue.
          pop(timerQueue);
          timer.sortIndex = timer.expirationTime;
          push(taskQueue, timer);
          {
            markTaskStart(timer, currentTime);
            timer.isQueued = true;
          }
        } else {
          // Remaining timers are pending.
          return;
        }

        timer = peek(timerQueue);
      }
    }

    function handleTimeout(currentTime) {
      isHostTimeoutScheduled = false;
      advanceTimers(currentTime);

      if (!isHostCallbackScheduled) {
        if (peek(taskQueue) !== null) {
          isHostCallbackScheduled = true;
          requestHostCallback(flushWork);
        } else {
          var firstTimer = peek(timerQueue);

          if (firstTimer !== null) {
            requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
          }
        }
      }
    }

    function flushWork(hasTimeRemaining, initialTime) {
      {
        markSchedulerUnsuspended(initialTime);
      } // We'll need a host callback the next time work is scheduled.

      isHostCallbackScheduled = false;

      if (isHostTimeoutScheduled) {
        // We scheduled a timeout but it's no longer needed. Cancel it.
        isHostTimeoutScheduled = false;
        cancelHostTimeout();
      }

      isPerformingWork = true;
      var previousPriorityLevel = currentPriorityLevel;

      try {
        if (enableProfiling) {
          try {
            return workLoop(hasTimeRemaining, initialTime);
          } catch (error) {
            if (currentTask !== null) {
              var currentTime = exports.unstable_now();
              markTaskErrored(currentTask, currentTime);
              currentTask.isQueued = false;
            }

            throw error;
          }
        } else {
          // No catch in prod codepath.
          return workLoop(hasTimeRemaining, initialTime);
        }
      } finally {
        currentTask = null;
        currentPriorityLevel = previousPriorityLevel;
        isPerformingWork = false;
        {
          var _currentTime = exports.unstable_now();

          markSchedulerSuspended(_currentTime);
        }
      }
    }

    function workLoop(hasTimeRemaining, initialTime) {
      var currentTime = initialTime;
      advanceTimers(currentTime);
      currentTask = peek(taskQueue);

      while (currentTask !== null && !enableSchedulerDebugging) {
        if (currentTask.expirationTime > currentTime && (!hasTimeRemaining || shouldYieldToHost())) {
          // This currentTask hasn't expired, and we've reached the deadline.
          break;
        }

        var callback = currentTask.callback;

        if (callback !== null) {
          currentTask.callback = null;
          currentPriorityLevel = currentTask.priorityLevel;
          var didUserCallbackTimeout = currentTask.expirationTime <= currentTime;
          markTaskRun(currentTask, currentTime);
          var continuationCallback = callback(didUserCallbackTimeout);
          currentTime = exports.unstable_now();

          if (typeof continuationCallback === 'function') {
            currentTask.callback = continuationCallback;
            markTaskYield(currentTask, currentTime);
          } else {
            {
              markTaskCompleted(currentTask, currentTime);
              currentTask.isQueued = false;
            }

            if (currentTask === peek(taskQueue)) {
              pop(taskQueue);
            }
          }

          advanceTimers(currentTime);
        } else {
          pop(taskQueue);
        }

        currentTask = peek(taskQueue);
      } // Return whether there's additional work


      if (currentTask !== null) {
        return true;
      } else {
        var firstTimer = peek(timerQueue);

        if (firstTimer !== null) {
          requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
        }

        return false;
      }
    }

    function unstable_runWithPriority(priorityLevel, eventHandler) {
      switch (priorityLevel) {
        case ImmediatePriority:
        case UserBlockingPriority:
        case NormalPriority:
        case LowPriority:
        case IdlePriority:
          break;

        default:
          priorityLevel = NormalPriority;
      }

      var previousPriorityLevel = currentPriorityLevel;
      currentPriorityLevel = priorityLevel;

      try {
        return eventHandler();
      } finally {
        currentPriorityLevel = previousPriorityLevel;
      }
    }

    function unstable_next(eventHandler) {
      var priorityLevel;

      switch (currentPriorityLevel) {
        case ImmediatePriority:
        case UserBlockingPriority:
        case NormalPriority:
          // Shift down to normal priority
          priorityLevel = NormalPriority;
          break;

        default:
          // Anything lower than normal priority should remain at the current level.
          priorityLevel = currentPriorityLevel;
          break;
      }

      var previousPriorityLevel = currentPriorityLevel;
      currentPriorityLevel = priorityLevel;

      try {
        return eventHandler();
      } finally {
        currentPriorityLevel = previousPriorityLevel;
      }
    }

    function unstable_wrapCallback(callback) {
      var parentPriorityLevel = currentPriorityLevel;
      return function () {
        // This is a fork of runWithPriority, inlined for performance.
        var previousPriorityLevel = currentPriorityLevel;
        currentPriorityLevel = parentPriorityLevel;

        try {
          return callback.apply(this, arguments);
        } finally {
          currentPriorityLevel = previousPriorityLevel;
        }
      };
    }

    function timeoutForPriorityLevel(priorityLevel) {
      switch (priorityLevel) {
        case ImmediatePriority:
          return IMMEDIATE_PRIORITY_TIMEOUT;

        case UserBlockingPriority:
          return USER_BLOCKING_PRIORITY;

        case IdlePriority:
          return IDLE_PRIORITY;

        case LowPriority:
          return LOW_PRIORITY_TIMEOUT;

        case NormalPriority:
        default:
          return NORMAL_PRIORITY_TIMEOUT;
      }
    }

    function unstable_scheduleCallback(priorityLevel, callback, options) {
      var currentTime = exports.unstable_now();
      var startTime;
      var timeout;

      if (typeof options === 'object' && options !== null) {
        var delay = options.delay;

        if (typeof delay === 'number' && delay > 0) {
          startTime = currentTime + delay;
        } else {
          startTime = currentTime;
        }

        timeout = typeof options.timeout === 'number' ? options.timeout : timeoutForPriorityLevel(priorityLevel);
      } else {
        timeout = timeoutForPriorityLevel(priorityLevel);
        startTime = currentTime;
      }

      var expirationTime = startTime + timeout;
      var newTask = {
        id: taskIdCounter++,
        callback: callback,
        priorityLevel: priorityLevel,
        startTime: startTime,
        expirationTime: expirationTime,
        sortIndex: -1
      };
      {
        newTask.isQueued = false;
      }

      if (startTime > currentTime) {
        // This is a delayed task.
        newTask.sortIndex = startTime;
        push(timerQueue, newTask);

        if (peek(taskQueue) === null && newTask === peek(timerQueue)) {
          // All tasks are delayed, and this is the task with the earliest delay.
          if (isHostTimeoutScheduled) {
            // Cancel an existing timeout.
            cancelHostTimeout();
          } else {
            isHostTimeoutScheduled = true;
          } // Schedule a timeout.


          requestHostTimeout(handleTimeout, startTime - currentTime);
        }
      } else {
        newTask.sortIndex = expirationTime;
        push(taskQueue, newTask);
        {
          markTaskStart(newTask, currentTime);
          newTask.isQueued = true;
        } // Schedule a host callback, if needed. If we're already performing work,
        // wait until the next time we yield.

        if (!isHostCallbackScheduled && !isPerformingWork) {
          isHostCallbackScheduled = true;
          requestHostCallback(flushWork);
        }
      }

      return newTask;
    }

    function unstable_pauseExecution() {}

    function unstable_continueExecution() {
      if (!isHostCallbackScheduled && !isPerformingWork) {
        isHostCallbackScheduled = true;
        requestHostCallback(flushWork);
      }
    }

    function unstable_getFirstCallbackNode() {
      return peek(taskQueue);
    }

    function unstable_cancelCallback(task) {
      {
        if (task.isQueued) {
          var currentTime = exports.unstable_now();
          markTaskCanceled(task, currentTime);
          task.isQueued = false;
        }
      } // Null out the callback to indicate the task has been canceled. (Can't
      // remove from the queue because you can't remove arbitrary nodes from an
      // array based heap, only the first one.)

      task.callback = null;
    }

    function unstable_getCurrentPriorityLevel() {
      return currentPriorityLevel;
    }

    function unstable_shouldYield() {
      var currentTime = exports.unstable_now();
      advanceTimers(currentTime);
      var firstTask = peek(taskQueue);
      return firstTask !== currentTask && currentTask !== null && firstTask !== null && firstTask.callback !== null && firstTask.startTime <= currentTime && firstTask.expirationTime < currentTask.expirationTime || shouldYieldToHost();
    }

    var unstable_requestPaint = requestPaint;
    var unstable_Profiling = {
      startLoggingProfilingEvents: startLoggingProfilingEvents,
      stopLoggingProfilingEvents: stopLoggingProfilingEvents,
      sharedProfilingBuffer: sharedProfilingBuffer
    };
    exports.unstable_IdlePriority = IdlePriority;
    exports.unstable_ImmediatePriority = ImmediatePriority;
    exports.unstable_LowPriority = LowPriority;
    exports.unstable_NormalPriority = NormalPriority;
    exports.unstable_Profiling = unstable_Profiling;
    exports.unstable_UserBlockingPriority = UserBlockingPriority;
    exports.unstable_cancelCallback = unstable_cancelCallback;
    exports.unstable_continueExecution = unstable_continueExecution;
    exports.unstable_getCurrentPriorityLevel = unstable_getCurrentPriorityLevel;
    exports.unstable_getFirstCallbackNode = unstable_getFirstCallbackNode;
    exports.unstable_next = unstable_next;
    exports.unstable_pauseExecution = unstable_pauseExecution;
    exports.unstable_requestPaint = unstable_requestPaint;
    exports.unstable_runWithPriority = unstable_runWithPriority;
    exports.unstable_scheduleCallback = unstable_scheduleCallback;
    exports.unstable_shouldYield = unstable_shouldYield;
    exports.unstable_wrapCallback = unstable_wrapCallback;
  })();
}
},{}],"../node_modules/scheduler/index.js":[function(require,module,exports) {
'use strict';

if ("development" === 'production') {
  module.exports = require('./cjs/scheduler.production.min.js');
} else {
  module.exports = require('./cjs/scheduler.development.js');
}
},{"./cjs/scheduler.development.js":"../node_modules/scheduler/cjs/scheduler.development.js"}],"../node_modules/scheduler/cjs/scheduler-tracing.development.js":[function(require,module,exports) {
/** @license React v0.19.1
 * scheduler-tracing.development.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
'use strict';

if ("development" !== "production") {
  (function () {
    'use strict';

    var DEFAULT_THREAD_ID = 0; // Counters used to generate unique IDs.

    var interactionIDCounter = 0;
    var threadIDCounter = 0; // Set of currently traced interactions.
    // Interactions "stack"–
    // Meaning that newly traced interactions are appended to the previously active set.
    // When an interaction goes out of scope, the previous set (if any) is restored.

    exports.__interactionsRef = null; // Listener(s) to notify when interactions begin and end.

    exports.__subscriberRef = null;
    {
      exports.__interactionsRef = {
        current: new Set()
      };
      exports.__subscriberRef = {
        current: null
      };
    }

    function unstable_clear(callback) {
      var prevInteractions = exports.__interactionsRef.current;
      exports.__interactionsRef.current = new Set();

      try {
        return callback();
      } finally {
        exports.__interactionsRef.current = prevInteractions;
      }
    }

    function unstable_getCurrent() {
      {
        return exports.__interactionsRef.current;
      }
    }

    function unstable_getThreadID() {
      return ++threadIDCounter;
    }

    function unstable_trace(name, timestamp, callback) {
      var threadID = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : DEFAULT_THREAD_ID;
      var interaction = {
        __count: 1,
        id: interactionIDCounter++,
        name: name,
        timestamp: timestamp
      };
      var prevInteractions = exports.__interactionsRef.current; // Traced interactions should stack/accumulate.
      // To do that, clone the current interactions.
      // The previous set will be restored upon completion.

      var interactions = new Set(prevInteractions);
      interactions.add(interaction);
      exports.__interactionsRef.current = interactions;
      var subscriber = exports.__subscriberRef.current;
      var returnValue;

      try {
        if (subscriber !== null) {
          subscriber.onInteractionTraced(interaction);
        }
      } finally {
        try {
          if (subscriber !== null) {
            subscriber.onWorkStarted(interactions, threadID);
          }
        } finally {
          try {
            returnValue = callback();
          } finally {
            exports.__interactionsRef.current = prevInteractions;

            try {
              if (subscriber !== null) {
                subscriber.onWorkStopped(interactions, threadID);
              }
            } finally {
              interaction.__count--; // If no async work was scheduled for this interaction,
              // Notify subscribers that it's completed.

              if (subscriber !== null && interaction.__count === 0) {
                subscriber.onInteractionScheduledWorkCompleted(interaction);
              }
            }
          }
        }
      }

      return returnValue;
    }

    function unstable_wrap(callback) {
      var threadID = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_THREAD_ID;
      var wrappedInteractions = exports.__interactionsRef.current;
      var subscriber = exports.__subscriberRef.current;

      if (subscriber !== null) {
        subscriber.onWorkScheduled(wrappedInteractions, threadID);
      } // Update the pending async work count for the current interactions.
      // Update after calling subscribers in case of error.


      wrappedInteractions.forEach(function (interaction) {
        interaction.__count++;
      });
      var hasRun = false;

      function wrapped() {
        var prevInteractions = exports.__interactionsRef.current;
        exports.__interactionsRef.current = wrappedInteractions;
        subscriber = exports.__subscriberRef.current;

        try {
          var returnValue;

          try {
            if (subscriber !== null) {
              subscriber.onWorkStarted(wrappedInteractions, threadID);
            }
          } finally {
            try {
              returnValue = callback.apply(undefined, arguments);
            } finally {
              exports.__interactionsRef.current = prevInteractions;

              if (subscriber !== null) {
                subscriber.onWorkStopped(wrappedInteractions, threadID);
              }
            }
          }

          return returnValue;
        } finally {
          if (!hasRun) {
            // We only expect a wrapped function to be executed once,
            // But in the event that it's executed more than once–
            // Only decrement the outstanding interaction counts once.
            hasRun = true; // Update pending async counts for all wrapped interactions.
            // If this was the last scheduled async work for any of them,
            // Mark them as completed.

            wrappedInteractions.forEach(function (interaction) {
              interaction.__count--;

              if (subscriber !== null && interaction.__count === 0) {
                subscriber.onInteractionScheduledWorkCompleted(interaction);
              }
            });
          }
        }
      }

      wrapped.cancel = function cancel() {
        subscriber = exports.__subscriberRef.current;

        try {
          if (subscriber !== null) {
            subscriber.onWorkCanceled(wrappedInteractions, threadID);
          }
        } finally {
          // Update pending async counts for all wrapped interactions.
          // If this was the last scheduled async work for any of them,
          // Mark them as completed.
          wrappedInteractions.forEach(function (interaction) {
            interaction.__count--;

            if (subscriber && interaction.__count === 0) {
              subscriber.onInteractionScheduledWorkCompleted(interaction);
            }
          });
        }
      };

      return wrapped;
    }

    var subscribers = null;
    {
      subscribers = new Set();
    }

    function unstable_subscribe(subscriber) {
      {
        subscribers.add(subscriber);

        if (subscribers.size === 1) {
          exports.__subscriberRef.current = {
            onInteractionScheduledWorkCompleted: onInteractionScheduledWorkCompleted,
            onInteractionTraced: onInteractionTraced,
            onWorkCanceled: onWorkCanceled,
            onWorkScheduled: onWorkScheduled,
            onWorkStarted: onWorkStarted,
            onWorkStopped: onWorkStopped
          };
        }
      }
    }

    function unstable_unsubscribe(subscriber) {
      {
        subscribers.delete(subscriber);

        if (subscribers.size === 0) {
          exports.__subscriberRef.current = null;
        }
      }
    }

    function onInteractionTraced(interaction) {
      var didCatchError = false;
      var caughtError = null;
      subscribers.forEach(function (subscriber) {
        try {
          subscriber.onInteractionTraced(interaction);
        } catch (error) {
          if (!didCatchError) {
            didCatchError = true;
            caughtError = error;
          }
        }
      });

      if (didCatchError) {
        throw caughtError;
      }
    }

    function onInteractionScheduledWorkCompleted(interaction) {
      var didCatchError = false;
      var caughtError = null;
      subscribers.forEach(function (subscriber) {
        try {
          subscriber.onInteractionScheduledWorkCompleted(interaction);
        } catch (error) {
          if (!didCatchError) {
            didCatchError = true;
            caughtError = error;
          }
        }
      });

      if (didCatchError) {
        throw caughtError;
      }
    }

    function onWorkScheduled(interactions, threadID) {
      var didCatchError = false;
      var caughtError = null;
      subscribers.forEach(function (subscriber) {
        try {
          subscriber.onWorkScheduled(interactions, threadID);
        } catch (error) {
          if (!didCatchError) {
            didCatchError = true;
            caughtError = error;
          }
        }
      });

      if (didCatchError) {
        throw caughtError;
      }
    }

    function onWorkStarted(interactions, threadID) {
      var didCatchError = false;
      var caughtError = null;
      subscribers.forEach(function (subscriber) {
        try {
          subscriber.onWorkStarted(interactions, threadID);
        } catch (error) {
          if (!didCatchError) {
            didCatchError = true;
            caughtError = error;
          }
        }
      });

      if (didCatchError) {
        throw caughtError;
      }
    }

    function onWorkStopped(interactions, threadID) {
      var didCatchError = false;
      var caughtError = null;
      subscribers.forEach(function (subscriber) {
        try {
          subscriber.onWorkStopped(interactions, threadID);
        } catch (error) {
          if (!didCatchError) {
            didCatchError = true;
            caughtError = error;
          }
        }
      });

      if (didCatchError) {
        throw caughtError;
      }
    }

    function onWorkCanceled(interactions, threadID) {
      var didCatchError = false;
      var caughtError = null;
      subscribers.forEach(function (subscriber) {
        try {
          subscriber.onWorkCanceled(interactions, threadID);
        } catch (error) {
          if (!didCatchError) {
            didCatchError = true;
            caughtError = error;
          }
        }
      });

      if (didCatchError) {
        throw caughtError;
      }
    }

    exports.unstable_clear = unstable_clear;
    exports.unstable_getCurrent = unstable_getCurrent;
    exports.unstable_getThreadID = unstable_getThreadID;
    exports.unstable_subscribe = unstable_subscribe;
    exports.unstable_trace = unstable_trace;
    exports.unstable_unsubscribe = unstable_unsubscribe;
    exports.unstable_wrap = unstable_wrap;
  })();
}
},{}],"../node_modules/scheduler/tracing.js":[function(require,module,exports) {
'use strict';

if ("development" === 'production') {
  module.exports = require('./cjs/scheduler-tracing.production.min.js');
} else {
  module.exports = require('./cjs/scheduler-tracing.development.js');
}
},{"./cjs/scheduler-tracing.development.js":"../node_modules/scheduler/cjs/scheduler-tracing.development.js"}],"../node_modules/react-dom/cjs/react-dom.development.js":[function(require,module,exports) {
/** @license React v16.13.1
 * react-dom.development.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
'use strict';

if ("development" !== "production") {
  (function () {
    'use strict';

    var React = require('react');

    var _assign = require('object-assign');

    var Scheduler = require('scheduler');

    var checkPropTypes = require('prop-types/checkPropTypes');

    var tracing = require('scheduler/tracing');

    var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; // Prevent newer renderers from RTE when used with older react package versions.
    // Current owner and dispatcher used to share the same ref,
    // but PR #14548 split them out to better support the react-debug-tools package.

    if (!ReactSharedInternals.hasOwnProperty('ReactCurrentDispatcher')) {
      ReactSharedInternals.ReactCurrentDispatcher = {
        current: null
      };
    }

    if (!ReactSharedInternals.hasOwnProperty('ReactCurrentBatchConfig')) {
      ReactSharedInternals.ReactCurrentBatchConfig = {
        suspense: null
      };
    } // by calls to these methods by a Babel plugin.
    //
    // In PROD (or in packages without access to React internals),
    // they are left as they are instead.


    function warn(format) {
      {
        for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
          args[_key - 1] = arguments[_key];
        }

        printWarning('warn', format, args);
      }
    }

    function error(format) {
      {
        for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
          args[_key2 - 1] = arguments[_key2];
        }

        printWarning('error', format, args);
      }
    }

    function printWarning(level, format, args) {
      // When changing this logic, you might want to also
      // update consoleWithStackDev.www.js as well.
      {
        var hasExistingStack = args.length > 0 && typeof args[args.length - 1] === 'string' && args[args.length - 1].indexOf('\n    in') === 0;

        if (!hasExistingStack) {
          var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
          var stack = ReactDebugCurrentFrame.getStackAddendum();

          if (stack !== '') {
            format += '%s';
            args = args.concat([stack]);
          }
        }

        var argsWithFormat = args.map(function (item) {
          return '' + item;
        }); // Careful: RN currently depends on this prefix

        argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
        // breaks IE9: https://github.com/facebook/react/issues/13610
        // eslint-disable-next-line react-internal/no-production-logging

        Function.prototype.apply.call(console[level], console, argsWithFormat);

        try {
          // --- Welcome to debugging React ---
          // This error was thrown as a convenience so that you can use this stack
          // to find the callsite that caused this warning to fire.
          var argIndex = 0;
          var message = 'Warning: ' + format.replace(/%s/g, function () {
            return args[argIndex++];
          });
          throw new Error(message);
        } catch (x) {}
      }
    }

    if (!React) {
      {
        throw Error("ReactDOM was loaded before React. Make sure you load the React package before loading ReactDOM.");
      }
    }

    var invokeGuardedCallbackImpl = function (name, func, context, a, b, c, d, e, f) {
      var funcArgs = Array.prototype.slice.call(arguments, 3);

      try {
        func.apply(context, funcArgs);
      } catch (error) {
        this.onError(error);
      }
    };

    {
      // In DEV mode, we swap out invokeGuardedCallback for a special version
      // that plays more nicely with the browser's DevTools. The idea is to preserve
      // "Pause on exceptions" behavior. Because React wraps all user-provided
      // functions in invokeGuardedCallback, and the production version of
      // invokeGuardedCallback uses a try-catch, all user exceptions are treated
      // like caught exceptions, and the DevTools won't pause unless the developer
      // takes the extra step of enabling pause on caught exceptions. This is
      // unintuitive, though, because even though React has caught the error, from
      // the developer's perspective, the error is uncaught.
      //
      // To preserve the expected "Pause on exceptions" behavior, we don't use a
      // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake
      // DOM node, and call the user-provided callback from inside an event handler
      // for that fake event. If the callback throws, the error is "captured" using
      // a global event handler. But because the error happens in a different
      // event loop context, it does not interrupt the normal program flow.
      // Effectively, this gives us try-catch behavior without actually using
      // try-catch. Neat!
      // Check that the browser supports the APIs we need to implement our special
      // DEV version of invokeGuardedCallback
      if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') {
        var fakeNode = document.createElement('react');

        var invokeGuardedCallbackDev = function (name, func, context, a, b, c, d, e, f) {
          // If document doesn't exist we know for sure we will crash in this method
          // when we call document.createEvent(). However this can cause confusing
          // errors: https://github.com/facebookincubator/create-react-app/issues/3482
          // So we preemptively throw with a better message instead.
          if (!(typeof document !== 'undefined')) {
            {
              throw Error("The `document` global was defined when React was initialized, but is not defined anymore. This can happen in a test environment if a component schedules an update from an asynchronous callback, but the test has already finished running. To solve this, you can either unmount the component at the end of your test (and ensure that any asynchronous operations get canceled in `componentWillUnmount`), or you can change the test itself to be asynchronous.");
            }
          }

          var evt = document.createEvent('Event'); // Keeps track of whether the user-provided callback threw an error. We
          // set this to true at the beginning, then set it to false right after
          // calling the function. If the function errors, `didError` will never be
          // set to false. This strategy works even if the browser is flaky and
          // fails to call our global error handler, because it doesn't rely on
          // the error event at all.

          var didError = true; // Keeps track of the value of window.event so that we can reset it
          // during the callback to let user code access window.event in the
          // browsers that support it.

          var windowEvent = window.event; // Keeps track of the descriptor of window.event to restore it after event
          // dispatching: https://github.com/facebook/react/issues/13688

          var windowEventDescriptor = Object.getOwnPropertyDescriptor(window, 'event'); // Create an event handler for our fake event. We will synchronously
          // dispatch our fake event using `dispatchEvent`. Inside the handler, we
          // call the user-provided callback.

          var funcArgs = Array.prototype.slice.call(arguments, 3);

          function callCallback() {
            // We immediately remove the callback from event listeners so that
            // nested `invokeGuardedCallback` calls do not clash. Otherwise, a
            // nested call would trigger the fake event handlers of any call higher
            // in the stack.
            fakeNode.removeEventListener(evtType, callCallback, false); // We check for window.hasOwnProperty('event') to prevent the
            // window.event assignment in both IE <= 10 as they throw an error
            // "Member not found" in strict mode, and in Firefox which does not
            // support window.event.

            if (typeof window.event !== 'undefined' && window.hasOwnProperty('event')) {
              window.event = windowEvent;
            }

            func.apply(context, funcArgs);
            didError = false;
          } // Create a global error event handler. We use this to capture the value
          // that was thrown. It's possible that this error handler will fire more
          // than once; for example, if non-React code also calls `dispatchEvent`
          // and a handler for that event throws. We should be resilient to most of
          // those cases. Even if our error event handler fires more than once, the
          // last error event is always used. If the callback actually does error,
          // we know that the last error event is the correct one, because it's not
          // possible for anything else to have happened in between our callback
          // erroring and the code that follows the `dispatchEvent` call below. If
          // the callback doesn't error, but the error event was fired, we know to
          // ignore it because `didError` will be false, as described above.


          var error; // Use this to track whether the error event is ever called.

          var didSetError = false;
          var isCrossOriginError = false;

          function handleWindowError(event) {
            error = event.error;
            didSetError = true;

            if (error === null && event.colno === 0 && event.lineno === 0) {
              isCrossOriginError = true;
            }

            if (event.defaultPrevented) {
              // Some other error handler has prevented default.
              // Browsers silence the error report if this happens.
              // We'll remember this to later decide whether to log it or not.
              if (error != null && typeof error === 'object') {
                try {
                  error._suppressLogging = true;
                } catch (inner) {// Ignore.
                }
              }
            }
          } // Create a fake event type.


          var evtType = "react-" + (name ? name : 'invokeguardedcallback'); // Attach our event handlers

          window.addEventListener('error', handleWindowError);
          fakeNode.addEventListener(evtType, callCallback, false); // Synchronously dispatch our fake event. If the user-provided function
          // errors, it will trigger our global error handler.

          evt.initEvent(evtType, false, false);
          fakeNode.dispatchEvent(evt);

          if (windowEventDescriptor) {
            Object.defineProperty(window, 'event', windowEventDescriptor);
          }

          if (didError) {
            if (!didSetError) {
              // The callback errored, but the error event never fired.
              error = new Error('An error was thrown inside one of your components, but React ' + "doesn't know what it was. This is likely due to browser " + 'flakiness. React does its best to preserve the "Pause on ' + 'exceptions" behavior of the DevTools, which requires some ' + "DEV-mode only tricks. It's possible that these don't work in " + 'your browser. Try triggering the error in production mode, ' + 'or switching to a modern browser. If you suspect that this is ' + 'actually an issue with React, please file an issue.');
            } else if (isCrossOriginError) {
              error = new Error("A cross-origin error was thrown. React doesn't have access to " + 'the actual error object in development. ' + 'See https://fb.me/react-crossorigin-error for more information.');
            }

            this.onError(error);
          } // Remove our event listeners


          window.removeEventListener('error', handleWindowError);
        };

        invokeGuardedCallbackImpl = invokeGuardedCallbackDev;
      }
    }
    var invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl;
    var hasError = false;
    var caughtError = null; // Used by event system to capture/rethrow the first error.

    var hasRethrowError = false;
    var rethrowError = null;
    var reporter = {
      onError: function (error) {
        hasError = true;
        caughtError = error;
      }
    };
    /**
     * Call a function while guarding against errors that happens within it.
     * Returns an error if it throws, otherwise null.
     *
     * In production, this is implemented using a try-catch. The reason we don't
     * use a try-catch directly is so that we can swap out a different
     * implementation in DEV mode.
     *
     * @param {String} name of the guard to use for logging or debugging
     * @param {Function} func The function to invoke
     * @param {*} context The context to use when calling the function
     * @param {...*} args Arguments for function
     */

    function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) {
      hasError = false;
      caughtError = null;
      invokeGuardedCallbackImpl$1.apply(reporter, arguments);
    }
    /**
     * Same as invokeGuardedCallback, but instead of returning an error, it stores
     * it in a global so it can be rethrown by `rethrowCaughtError` later.
     * TODO: See if caughtError and rethrowError can be unified.
     *
     * @param {String} name of the guard to use for logging or debugging
     * @param {Function} func The function to invoke
     * @param {*} context The context to use when calling the function
     * @param {...*} args Arguments for function
     */


    function invokeGuardedCallbackAndCatchFirstError(name, func, context, a, b, c, d, e, f) {
      invokeGuardedCallback.apply(this, arguments);

      if (hasError) {
        var error = clearCaughtError();

        if (!hasRethrowError) {
          hasRethrowError = true;
          rethrowError = error;
        }
      }
    }
    /**
     * During execution of guarded functions we will capture the first error which
     * we will rethrow to be handled by the top level error handler.
     */


    function rethrowCaughtError() {
      if (hasRethrowError) {
        var error = rethrowError;
        hasRethrowError = false;
        rethrowError = null;
        throw error;
      }
    }

    function hasCaughtError() {
      return hasError;
    }

    function clearCaughtError() {
      if (hasError) {
        var error = caughtError;
        hasError = false;
        caughtError = null;
        return error;
      } else {
        {
          {
            throw Error("clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue.");
          }
        }
      }
    }

    var getFiberCurrentPropsFromNode = null;
    var getInstanceFromNode = null;
    var getNodeFromInstance = null;

    function setComponentTree(getFiberCurrentPropsFromNodeImpl, getInstanceFromNodeImpl, getNodeFromInstanceImpl) {
      getFiberCurrentPropsFromNode = getFiberCurrentPropsFromNodeImpl;
      getInstanceFromNode = getInstanceFromNodeImpl;
      getNodeFromInstance = getNodeFromInstanceImpl;
      {
        if (!getNodeFromInstance || !getInstanceFromNode) {
          error('EventPluginUtils.setComponentTree(...): Injected ' + 'module is missing getNodeFromInstance or getInstanceFromNode.');
        }
      }
    }

    var validateEventDispatches;
    {
      validateEventDispatches = function (event) {
        var dispatchListeners = event._dispatchListeners;
        var dispatchInstances = event._dispatchInstances;
        var listenersIsArr = Array.isArray(dispatchListeners);
        var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0;
        var instancesIsArr = Array.isArray(dispatchInstances);
        var instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0;

        if (instancesIsArr !== listenersIsArr || instancesLen !== listenersLen) {
          error('EventPluginUtils: Invalid `event`.');
        }
      };
    }
    /**
     * Dispatch the event to the listener.
     * @param {SyntheticEvent} event SyntheticEvent to handle
     * @param {function} listener Application-level callback
     * @param {*} inst Internal component instance
     */

    function executeDispatch(event, listener, inst) {
      var type = event.type || 'unknown-event';
      event.currentTarget = getNodeFromInstance(inst);
      invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event);
      event.currentTarget = null;
    }
    /**
     * Standard/simple iteration through an event's collected dispatches.
     */


    function executeDispatchesInOrder(event) {
      var dispatchListeners = event._dispatchListeners;
      var dispatchInstances = event._dispatchInstances;
      {
        validateEventDispatches(event);
      }

      if (Array.isArray(dispatchListeners)) {
        for (var i = 0; i < dispatchListeners.length; i++) {
          if (event.isPropagationStopped()) {
            break;
          } // Listeners and Instances are two parallel arrays that are always in sync.


          executeDispatch(event, dispatchListeners[i], dispatchInstances[i]);
        }
      } else if (dispatchListeners) {
        executeDispatch(event, dispatchListeners, dispatchInstances);
      }

      event._dispatchListeners = null;
      event._dispatchInstances = null;
    }

    var FunctionComponent = 0;
    var ClassComponent = 1;
    var IndeterminateComponent = 2; // Before we know whether it is function or class

    var HostRoot = 3; // Root of a host tree. Could be nested inside another node.

    var HostPortal = 4; // A subtree. Could be an entry point to a different renderer.

    var HostComponent = 5;
    var HostText = 6;
    var Fragment = 7;
    var Mode = 8;
    var ContextConsumer = 9;
    var ContextProvider = 10;
    var ForwardRef = 11;
    var Profiler = 12;
    var SuspenseComponent = 13;
    var MemoComponent = 14;
    var SimpleMemoComponent = 15;
    var LazyComponent = 16;
    var IncompleteClassComponent = 17;
    var DehydratedFragment = 18;
    var SuspenseListComponent = 19;
    var FundamentalComponent = 20;
    var ScopeComponent = 21;
    var Block = 22;
    /**
     * Injectable ordering of event plugins.
     */

    var eventPluginOrder = null;
    /**
     * Injectable mapping from names to event plugin modules.
     */

    var namesToPlugins = {};
    /**
     * Recomputes the plugin list using the injected plugins and plugin ordering.
     *
     * @private
     */

    function recomputePluginOrdering() {
      if (!eventPluginOrder) {
        // Wait until an `eventPluginOrder` is injected.
        return;
      }

      for (var pluginName in namesToPlugins) {
        var pluginModule = namesToPlugins[pluginName];
        var pluginIndex = eventPluginOrder.indexOf(pluginName);

        if (!(pluginIndex > -1)) {
          {
            throw Error("EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `" + pluginName + "`.");
          }
        }

        if (plugins[pluginIndex]) {
          continue;
        }

        if (!pluginModule.extractEvents) {
          {
            throw Error("EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `" + pluginName + "` does not.");
          }
        }

        plugins[pluginIndex] = pluginModule;
        var publishedEvents = pluginModule.eventTypes;

        for (var eventName in publishedEvents) {
          if (!publishEventForPlugin(publishedEvents[eventName], pluginModule, eventName)) {
            {
              throw Error("EventPluginRegistry: Failed to publish event `" + eventName + "` for plugin `" + pluginName + "`.");
            }
          }
        }
      }
    }
    /**
     * Publishes an event so that it can be dispatched by the supplied plugin.
     *
     * @param {object} dispatchConfig Dispatch configuration for the event.
     * @param {object} PluginModule Plugin publishing the event.
     * @return {boolean} True if the event was successfully published.
     * @private
     */


    function publishEventForPlugin(dispatchConfig, pluginModule, eventName) {
      if (!!eventNameDispatchConfigs.hasOwnProperty(eventName)) {
        {
          throw Error("EventPluginRegistry: More than one plugin attempted to publish the same event name, `" + eventName + "`.");
        }
      }

      eventNameDispatchConfigs[eventName] = dispatchConfig;
      var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames;

      if (phasedRegistrationNames) {
        for (var phaseName in phasedRegistrationNames) {
          if (phasedRegistrationNames.hasOwnProperty(phaseName)) {
            var phasedRegistrationName = phasedRegistrationNames[phaseName];
            publishRegistrationName(phasedRegistrationName, pluginModule, eventName);
          }
        }

        return true;
      } else if (dispatchConfig.registrationName) {
        publishRegistrationName(dispatchConfig.registrationName, pluginModule, eventName);
        return true;
      }

      return false;
    }
    /**
     * Publishes a registration name that is used to identify dispatched events.
     *
     * @param {string} registrationName Registration name to add.
     * @param {object} PluginModule Plugin publishing the event.
     * @private
     */


    function publishRegistrationName(registrationName, pluginModule, eventName) {
      if (!!registrationNameModules[registrationName]) {
        {
          throw Error("EventPluginRegistry: More than one plugin attempted to publish the same registration name, `" + registrationName + "`.");
        }
      }

      registrationNameModules[registrationName] = pluginModule;
      registrationNameDependencies[registrationName] = pluginModule.eventTypes[eventName].dependencies;
      {
        var lowerCasedName = registrationName.toLowerCase();
        possibleRegistrationNames[lowerCasedName] = registrationName;

        if (registrationName === 'onDoubleClick') {
          possibleRegistrationNames.ondblclick = registrationName;
        }
      }
    }
    /**
     * Registers plugins so that they can extract and dispatch events.
     */

    /**
     * Ordered list of injected plugins.
     */


    var plugins = [];
    /**
     * Mapping from event name to dispatch config
     */

    var eventNameDispatchConfigs = {};
    /**
     * Mapping from registration name to plugin module
     */

    var registrationNameModules = {};
    /**
     * Mapping from registration name to event name
     */

    var registrationNameDependencies = {};
    /**
     * Mapping from lowercase registration names to the properly cased version,
     * used to warn in the case of missing event handlers. Available
     * only in true.
     * @type {Object}
     */

    var possibleRegistrationNames = {}; // Trust the developer to only use possibleRegistrationNames in true

    /**
     * Injects an ordering of plugins (by plugin name). This allows the ordering
     * to be decoupled from injection of the actual plugins so that ordering is
     * always deterministic regardless of packaging, on-the-fly injection, etc.
     *
     * @param {array} InjectedEventPluginOrder
     * @internal
     */

    function injectEventPluginOrder(injectedEventPluginOrder) {
      if (!!eventPluginOrder) {
        {
          throw Error("EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React.");
        }
      } // Clone the ordering so it cannot be dynamically mutated.


      eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder);
      recomputePluginOrdering();
    }
    /**
     * Injects plugins to be used by plugin event system. The plugin names must be
     * in the ordering injected by `injectEventPluginOrder`.
     *
     * Plugins can be injected as part of page initialization or on-the-fly.
     *
     * @param {object} injectedNamesToPlugins Map from names to plugin modules.
     * @internal
     */


    function injectEventPluginsByName(injectedNamesToPlugins) {
      var isOrderingDirty = false;

      for (var pluginName in injectedNamesToPlugins) {
        if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) {
          continue;
        }

        var pluginModule = injectedNamesToPlugins[pluginName];

        if (!namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== pluginModule) {
          if (!!namesToPlugins[pluginName]) {
            {
              throw Error("EventPluginRegistry: Cannot inject two different event plugins using the same name, `" + pluginName + "`.");
            }
          }

          namesToPlugins[pluginName] = pluginModule;
          isOrderingDirty = true;
        }
      }

      if (isOrderingDirty) {
        recomputePluginOrdering();
      }
    }

    var canUseDOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined');
    var PLUGIN_EVENT_SYSTEM = 1;
    var IS_REPLAYED = 1 << 5;
    var IS_FIRST_ANCESTOR = 1 << 6;
    var restoreImpl = null;
    var restoreTarget = null;
    var restoreQueue = null;

    function restoreStateOfTarget(target) {
      // We perform this translation at the end of the event loop so that we
      // always receive the correct fiber here
      var internalInstance = getInstanceFromNode(target);

      if (!internalInstance) {
        // Unmounted
        return;
      }

      if (!(typeof restoreImpl === 'function')) {
        {
          throw Error("setRestoreImplementation() needs to be called to handle a target for controlled events. This error is likely caused by a bug in React. Please file an issue.");
        }
      }

      var stateNode = internalInstance.stateNode; // Guard against Fiber being unmounted.

      if (stateNode) {
        var _props = getFiberCurrentPropsFromNode(stateNode);

        restoreImpl(internalInstance.stateNode, internalInstance.type, _props);
      }
    }

    function setRestoreImplementation(impl) {
      restoreImpl = impl;
    }

    function enqueueStateRestore(target) {
      if (restoreTarget) {
        if (restoreQueue) {
          restoreQueue.push(target);
        } else {
          restoreQueue = [target];
        }
      } else {
        restoreTarget = target;
      }
    }

    function needsStateRestore() {
      return restoreTarget !== null || restoreQueue !== null;
    }

    function restoreStateIfNeeded() {
      if (!restoreTarget) {
        return;
      }

      var target = restoreTarget;
      var queuedTargets = restoreQueue;
      restoreTarget = null;
      restoreQueue = null;
      restoreStateOfTarget(target);

      if (queuedTargets) {
        for (var i = 0; i < queuedTargets.length; i++) {
          restoreStateOfTarget(queuedTargets[i]);
        }
      }
    }

    var enableProfilerTimer = true; // Trace which interactions trigger each commit.

    var enableDeprecatedFlareAPI = false; // Experimental Host Component support.

    var enableFundamentalAPI = false; // Experimental Scope support.

    var warnAboutStringRefs = false; // the renderer. Such as when we're dispatching events or if third party
    // libraries need to call batchedUpdates. Eventually, this API will go away when
    // everything is batched by default. We'll then have a similar API to opt-out of
    // scheduled work and instead do synchronous work.
    // Defaults

    var batchedUpdatesImpl = function (fn, bookkeeping) {
      return fn(bookkeeping);
    };

    var discreteUpdatesImpl = function (fn, a, b, c, d) {
      return fn(a, b, c, d);
    };

    var flushDiscreteUpdatesImpl = function () {};

    var batchedEventUpdatesImpl = batchedUpdatesImpl;
    var isInsideEventHandler = false;
    var isBatchingEventUpdates = false;

    function finishEventHandler() {
      // Here we wait until all updates have propagated, which is important
      // when using controlled components within layers:
      // https://github.com/facebook/react/issues/1698
      // Then we restore state of any controlled component.
      var controlledComponentsHavePendingUpdates = needsStateRestore();

      if (controlledComponentsHavePendingUpdates) {
        // If a controlled event was fired, we may need to restore the state of
        // the DOM node back to the controlled value. This is necessary when React
        // bails out of the update without touching the DOM.
        flushDiscreteUpdatesImpl();
        restoreStateIfNeeded();
      }
    }

    function batchedUpdates(fn, bookkeeping) {
      if (isInsideEventHandler) {
        // If we are currently inside another batch, we need to wait until it
        // fully completes before restoring state.
        return fn(bookkeeping);
      }

      isInsideEventHandler = true;

      try {
        return batchedUpdatesImpl(fn, bookkeeping);
      } finally {
        isInsideEventHandler = false;
        finishEventHandler();
      }
    }

    function batchedEventUpdates(fn, a, b) {
      if (isBatchingEventUpdates) {
        // If we are currently inside another batch, we need to wait until it
        // fully completes before restoring state.
        return fn(a, b);
      }

      isBatchingEventUpdates = true;

      try {
        return batchedEventUpdatesImpl(fn, a, b);
      } finally {
        isBatchingEventUpdates = false;
        finishEventHandler();
      }
    } // This is for the React Flare event system


    function discreteUpdates(fn, a, b, c, d) {
      var prevIsInsideEventHandler = isInsideEventHandler;
      isInsideEventHandler = true;

      try {
        return discreteUpdatesImpl(fn, a, b, c, d);
      } finally {
        isInsideEventHandler = prevIsInsideEventHandler;

        if (!isInsideEventHandler) {
          finishEventHandler();
        }
      }
    }

    function flushDiscreteUpdatesIfNeeded(timeStamp) {
      // event.timeStamp isn't overly reliable due to inconsistencies in
      // how different browsers have historically provided the time stamp.
      // Some browsers provide high-resolution time stamps for all events,
      // some provide low-resolution time stamps for all events. FF < 52
      // even mixes both time stamps together. Some browsers even report
      // negative time stamps or time stamps that are 0 (iOS9) in some cases.
      // Given we are only comparing two time stamps with equality (!==),
      // we are safe from the resolution differences. If the time stamp is 0
      // we bail-out of preventing the flush, which can affect semantics,
      // such as if an earlier flush removes or adds event listeners that
      // are fired in the subsequent flush. However, this is the same
      // behaviour as we had before this change, so the risks are low.
      if (!isInsideEventHandler && !enableDeprecatedFlareAPI) {
        flushDiscreteUpdatesImpl();
      }
    }

    function setBatchingImplementation(_batchedUpdatesImpl, _discreteUpdatesImpl, _flushDiscreteUpdatesImpl, _batchedEventUpdatesImpl) {
      batchedUpdatesImpl = _batchedUpdatesImpl;
      discreteUpdatesImpl = _discreteUpdatesImpl;
      flushDiscreteUpdatesImpl = _flushDiscreteUpdatesImpl;
      batchedEventUpdatesImpl = _batchedEventUpdatesImpl;
    }

    var DiscreteEvent = 0;
    var UserBlockingEvent = 1;
    var ContinuousEvent = 2; // A reserved attribute.
    // It is handled by React separately and shouldn't be written to the DOM.

    var RESERVED = 0; // A simple string attribute.
    // Attributes that aren't in the whitelist are presumed to have this type.

    var STRING = 1; // A string attribute that accepts booleans in React. In HTML, these are called
    // "enumerated" attributes with "true" and "false" as possible values.
    // When true, it should be set to a "true" string.
    // When false, it should be set to a "false" string.

    var BOOLEANISH_STRING = 2; // A real boolean attribute.
    // When true, it should be present (set either to an empty string or its name).
    // When false, it should be omitted.

    var BOOLEAN = 3; // An attribute that can be used as a flag as well as with a value.
    // When true, it should be present (set either to an empty string or its name).
    // When false, it should be omitted.
    // For any other value, should be present with that value.

    var OVERLOADED_BOOLEAN = 4; // An attribute that must be numeric or parse as a numeric.
    // When falsy, it should be removed.

    var NUMERIC = 5; // An attribute that must be positive numeric or parse as a positive numeric.
    // When falsy, it should be removed.

    var POSITIVE_NUMERIC = 6;
    /* eslint-disable max-len */

    var ATTRIBUTE_NAME_START_CHAR = ":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";
    /* eslint-enable max-len */

    var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + "\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
    var ROOT_ATTRIBUTE_NAME = 'data-reactroot';
    var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + ATTRIBUTE_NAME_START_CHAR + '][' + ATTRIBUTE_NAME_CHAR + ']*$');
    var hasOwnProperty = Object.prototype.hasOwnProperty;
    var illegalAttributeNameCache = {};
    var validatedAttributeNameCache = {};

    function isAttributeNameSafe(attributeName) {
      if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) {
        return true;
      }

      if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) {
        return false;
      }

      if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) {
        validatedAttributeNameCache[attributeName] = true;
        return true;
      }

      illegalAttributeNameCache[attributeName] = true;
      {
        error('Invalid attribute name: `%s`', attributeName);
      }
      return false;
    }

    function shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag) {
      if (propertyInfo !== null) {
        return propertyInfo.type === RESERVED;
      }

      if (isCustomComponentTag) {
        return false;
      }

      if (name.length > 2 && (name[0] === 'o' || name[0] === 'O') && (name[1] === 'n' || name[1] === 'N')) {
        return true;
      }

      return false;
    }

    function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) {
      if (propertyInfo !== null && propertyInfo.type === RESERVED) {
        return false;
      }

      switch (typeof value) {
        case 'function': // $FlowIssue symbol is perfectly valid here

        case 'symbol':
          // eslint-disable-line
          return true;

        case 'boolean':
          {
            if (isCustomComponentTag) {
              return false;
            }

            if (propertyInfo !== null) {
              return !propertyInfo.acceptsBooleans;
            } else {
              var prefix = name.toLowerCase().slice(0, 5);
              return prefix !== 'data-' && prefix !== 'aria-';
            }
          }

        default:
          return false;
      }
    }

    function shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag) {
      if (value === null || typeof value === 'undefined') {
        return true;
      }

      if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag)) {
        return true;
      }

      if (isCustomComponentTag) {
        return false;
      }

      if (propertyInfo !== null) {
        switch (propertyInfo.type) {
          case BOOLEAN:
            return !value;

          case OVERLOADED_BOOLEAN:
            return value === false;

          case NUMERIC:
            return isNaN(value);

          case POSITIVE_NUMERIC:
            return isNaN(value) || value < 1;
        }
      }

      return false;
    }

    function getPropertyInfo(name) {
      return properties.hasOwnProperty(name) ? properties[name] : null;
    }

    function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace, sanitizeURL) {
      this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN;
      this.attributeName = attributeName;
      this.attributeNamespace = attributeNamespace;
      this.mustUseProperty = mustUseProperty;
      this.propertyName = name;
      this.type = type;
      this.sanitizeURL = sanitizeURL;
    } // When adding attributes to this list, be sure to also add them to
    // the `possibleStandardNames` module to ensure casing and incorrect
    // name warnings.


    var properties = {}; // These props are reserved by React. They shouldn't be written to the DOM.

    var reservedProps = ['children', 'dangerouslySetInnerHTML', // TODO: This prevents the assignment of defaultValue to regular
    // elements (not just inputs). Now that ReactDOMInput assigns to the
    // defaultValue property -- do we need this?
    'defaultValue', 'defaultChecked', 'innerHTML', 'suppressContentEditableWarning', 'suppressHydrationWarning', 'style'];
    reservedProps.forEach(function (name) {
      properties[name] = new PropertyInfoRecord(name, RESERVED, false, // mustUseProperty
      name, // attributeName
      null, // attributeNamespace
      false);
    }); // A few React string attributes have a different name.
    // This is a mapping from React prop names to the attribute names.

    [['acceptCharset', 'accept-charset'], ['className', 'class'], ['htmlFor', 'for'], ['httpEquiv', 'http-equiv']].forEach(function (_ref) {
      var name = _ref[0],
          attributeName = _ref[1];
      properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
      attributeName, // attributeName
      null, // attributeNamespace
      false);
    }); // These are "enumerated" HTML attributes that accept "true" and "false".
    // In React, we let users pass `true` and `false` even though technically
    // these aren't boolean attributes (they are coerced to strings).

    ['contentEditable', 'draggable', 'spellCheck', 'value'].forEach(function (name) {
      properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
      name.toLowerCase(), // attributeName
      null, // attributeNamespace
      false);
    }); // These are "enumerated" SVG attributes that accept "true" and "false".
    // In React, we let users pass `true` and `false` even though technically
    // these aren't boolean attributes (they are coerced to strings).
    // Since these are SVG attributes, their attribute names are case-sensitive.

    ['autoReverse', 'externalResourcesRequired', 'focusable', 'preserveAlpha'].forEach(function (name) {
      properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
      name, // attributeName
      null, // attributeNamespace
      false);
    }); // These are HTML boolean attributes.

    ['allowFullScreen', 'async', // Note: there is a special case that prevents it from being written to the DOM
    // on the client side because the browsers are inconsistent. Instead we call focus().
    'autoFocus', 'autoPlay', 'controls', 'default', 'defer', 'disabled', 'disablePictureInPicture', 'formNoValidate', 'hidden', 'loop', 'noModule', 'noValidate', 'open', 'playsInline', 'readOnly', 'required', 'reversed', 'scoped', 'seamless', // Microdata
    'itemScope'].forEach(function (name) {
      properties[name] = new PropertyInfoRecord(name, BOOLEAN, false, // mustUseProperty
      name.toLowerCase(), // attributeName
      null, // attributeNamespace
      false);
    }); // These are the few React props that we set as DOM properties
    // rather than attributes. These are all booleans.

    ['checked', // Note: `option.selected` is not updated if `select.multiple` is
    // disabled with `removeAttribute`. We have special logic for handling this.
    'multiple', 'muted', 'selected' // NOTE: if you add a camelCased prop to this list,
    // you'll need to set attributeName to name.toLowerCase()
    // instead in the assignment below.
    ].forEach(function (name) {
      properties[name] = new PropertyInfoRecord(name, BOOLEAN, true, // mustUseProperty
      name, // attributeName
      null, // attributeNamespace
      false);
    }); // These are HTML attributes that are "overloaded booleans": they behave like
    // booleans, but can also accept a string value.

    ['capture', 'download' // NOTE: if you add a camelCased prop to this list,
    // you'll need to set attributeName to name.toLowerCase()
    // instead in the assignment below.
    ].forEach(function (name) {
      properties[name] = new PropertyInfoRecord(name, OVERLOADED_BOOLEAN, false, // mustUseProperty
      name, // attributeName
      null, // attributeNamespace
      false);
    }); // These are HTML attributes that must be positive numbers.

    ['cols', 'rows', 'size', 'span' // NOTE: if you add a camelCased prop to this list,
    // you'll need to set attributeName to name.toLowerCase()
    // instead in the assignment below.
    ].forEach(function (name) {
      properties[name] = new PropertyInfoRecord(name, POSITIVE_NUMERIC, false, // mustUseProperty
      name, // attributeName
      null, // attributeNamespace
      false);
    }); // These are HTML attributes that must be numbers.

    ['rowSpan', 'start'].forEach(function (name) {
      properties[name] = new PropertyInfoRecord(name, NUMERIC, false, // mustUseProperty
      name.toLowerCase(), // attributeName
      null, // attributeNamespace
      false);
    });
    var CAMELIZE = /[\-\:]([a-z])/g;

    var capitalize = function (token) {
      return token[1].toUpperCase();
    }; // This is a list of all SVG attributes that need special casing, namespacing,
    // or boolean value assignment. Regular attributes that just accept strings
    // and have the same names are omitted, just like in the HTML whitelist.
    // Some of these attributes can be hard to find. This list was created by
    // scraping the MDN documentation.


    ['accent-height', 'alignment-baseline', 'arabic-form', 'baseline-shift', 'cap-height', 'clip-path', 'clip-rule', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'dominant-baseline', 'enable-background', 'fill-opacity', 'fill-rule', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'glyph-name', 'glyph-orientation-horizontal', 'glyph-orientation-vertical', 'horiz-adv-x', 'horiz-origin-x', 'image-rendering', 'letter-spacing', 'lighting-color', 'marker-end', 'marker-mid', 'marker-start', 'overline-position', 'overline-thickness', 'paint-order', 'panose-1', 'pointer-events', 'rendering-intent', 'shape-rendering', 'stop-color', 'stop-opacity', 'strikethrough-position', 'strikethrough-thickness', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-decoration', 'text-rendering', 'underline-position', 'underline-thickness', 'unicode-bidi', 'unicode-range', 'units-per-em', 'v-alphabetic', 'v-hanging', 'v-ideographic', 'v-mathematical', 'vector-effect', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'word-spacing', 'writing-mode', 'xmlns:xlink', 'x-height' // NOTE: if you add a camelCased prop to this list,
    // you'll need to set attributeName to name.toLowerCase()
    // instead in the assignment below.
    ].forEach(function (attributeName) {
      var name = attributeName.replace(CAMELIZE, capitalize);
      properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
      attributeName, null, // attributeNamespace
      false);
    }); // String SVG attributes with the xlink namespace.

    ['xlink:actuate', 'xlink:arcrole', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type' // NOTE: if you add a camelCased prop to this list,
    // you'll need to set attributeName to name.toLowerCase()
    // instead in the assignment below.
    ].forEach(function (attributeName) {
      var name = attributeName.replace(CAMELIZE, capitalize);
      properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
      attributeName, 'http://www.w3.org/1999/xlink', false);
    }); // String SVG attributes with the xml namespace.

    ['xml:base', 'xml:lang', 'xml:space' // NOTE: if you add a camelCased prop to this list,
    // you'll need to set attributeName to name.toLowerCase()
    // instead in the assignment below.
    ].forEach(function (attributeName) {
      var name = attributeName.replace(CAMELIZE, capitalize);
      properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
      attributeName, 'http://www.w3.org/XML/1998/namespace', false);
    }); // These attribute exists both in HTML and SVG.
    // The attribute name is case-sensitive in SVG so we can't just use
    // the React name like we do for attributes that exist only in HTML.

    ['tabIndex', 'crossOrigin'].forEach(function (attributeName) {
      properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty
      attributeName.toLowerCase(), // attributeName
      null, // attributeNamespace
      false);
    }); // These attributes accept URLs. These must not allow javascript: URLS.
    // These will also need to accept Trusted Types object in the future.

    var xlinkHref = 'xlinkHref';
    properties[xlinkHref] = new PropertyInfoRecord('xlinkHref', STRING, false, // mustUseProperty
    'xlink:href', 'http://www.w3.org/1999/xlink', true);
    ['src', 'href', 'action', 'formAction'].forEach(function (attributeName) {
      properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty
      attributeName.toLowerCase(), // attributeName
      null, // attributeNamespace
      true);
    });
    var ReactDebugCurrentFrame = null;
    {
      ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
    } // A javascript: URL can contain leading C0 control or \u0020 SPACE,
    // and any newline or tab are filtered out as if they're not part of the URL.
    // https://url.spec.whatwg.org/#url-parsing
    // Tab or newline are defined as \r\n\t:
    // https://infra.spec.whatwg.org/#ascii-tab-or-newline
    // A C0 control is a code point in the range \u0000 NULL to \u001F
    // INFORMATION SEPARATOR ONE, inclusive:
    // https://infra.spec.whatwg.org/#c0-control-or-space

    /* eslint-disable max-len */

    var isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i;
    var didWarn = false;

    function sanitizeURL(url) {
      {
        if (!didWarn && isJavaScriptProtocol.test(url)) {
          didWarn = true;
          error('A future version of React will block javascript: URLs as a security precaution. ' + 'Use event handlers instead if you can. If you need to generate unsafe HTML try ' + 'using dangerouslySetInnerHTML instead. React was passed %s.', JSON.stringify(url));
        }
      }
    }
    /**
     * Get the value for a property on a node. Only used in DEV for SSR validation.
     * The "expected" argument is used as a hint of what the expected value is.
     * Some properties have multiple equivalent values.
     */


    function getValueForProperty(node, name, expected, propertyInfo) {
      {
        if (propertyInfo.mustUseProperty) {
          var propertyName = propertyInfo.propertyName;
          return node[propertyName];
        } else {
          if (propertyInfo.sanitizeURL) {
            // If we haven't fully disabled javascript: URLs, and if
            // the hydration is successful of a javascript: URL, we
            // still want to warn on the client.
            sanitizeURL('' + expected);
          }

          var attributeName = propertyInfo.attributeName;
          var stringValue = null;

          if (propertyInfo.type === OVERLOADED_BOOLEAN) {
            if (node.hasAttribute(attributeName)) {
              var value = node.getAttribute(attributeName);

              if (value === '') {
                return true;
              }

              if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
                return value;
              }

              if (value === '' + expected) {
                return expected;
              }

              return value;
            }
          } else if (node.hasAttribute(attributeName)) {
            if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
              // We had an attribute but shouldn't have had one, so read it
              // for the error message.
              return node.getAttribute(attributeName);
            }

            if (propertyInfo.type === BOOLEAN) {
              // If this was a boolean, it doesn't matter what the value is
              // the fact that we have it is the same as the expected.
              return expected;
            } // Even if this property uses a namespace we use getAttribute
            // because we assume its namespaced name is the same as our config.
            // To use getAttributeNS we need the local name which we don't have
            // in our config atm.


            stringValue = node.getAttribute(attributeName);
          }

          if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
            return stringValue === null ? expected : stringValue;
          } else if (stringValue === '' + expected) {
            return expected;
          } else {
            return stringValue;
          }
        }
      }
    }
    /**
     * Get the value for a attribute on a node. Only used in DEV for SSR validation.
     * The third argument is used as a hint of what the expected value is. Some
     * attributes have multiple equivalent values.
     */


    function getValueForAttribute(node, name, expected) {
      {
        if (!isAttributeNameSafe(name)) {
          return;
        }

        if (!node.hasAttribute(name)) {
          return expected === undefined ? undefined : null;
        }

        var value = node.getAttribute(name);

        if (value === '' + expected) {
          return expected;
        }

        return value;
      }
    }
    /**
     * Sets the value for a property on a node.
     *
     * @param {DOMElement} node
     * @param {string} name
     * @param {*} value
     */


    function setValueForProperty(node, name, value, isCustomComponentTag) {
      var propertyInfo = getPropertyInfo(name);

      if (shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag)) {
        return;
      }

      if (shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag)) {
        value = null;
      } // If the prop isn't in the special list, treat it as a simple attribute.


      if (isCustomComponentTag || propertyInfo === null) {
        if (isAttributeNameSafe(name)) {
          var _attributeName = name;

          if (value === null) {
            node.removeAttribute(_attributeName);
          } else {
            node.setAttribute(_attributeName, '' + value);
          }
        }

        return;
      }

      var mustUseProperty = propertyInfo.mustUseProperty;

      if (mustUseProperty) {
        var propertyName = propertyInfo.propertyName;

        if (value === null) {
          var type = propertyInfo.type;
          node[propertyName] = type === BOOLEAN ? false : '';
        } else {
          // Contrary to `setAttribute`, object properties are properly
          // `toString`ed by IE8/9.
          node[propertyName] = value;
        }

        return;
      } // The rest are treated as attributes with special cases.


      var attributeName = propertyInfo.attributeName,
          attributeNamespace = propertyInfo.attributeNamespace;

      if (value === null) {
        node.removeAttribute(attributeName);
      } else {
        var _type = propertyInfo.type;
        var attributeValue;

        if (_type === BOOLEAN || _type === OVERLOADED_BOOLEAN && value === true) {
          // If attribute type is boolean, we know for sure it won't be an execution sink
          // and we won't require Trusted Type here.
          attributeValue = '';
        } else {
          // `setAttribute` with objects becomes only `[object]` in IE8/9,
          // ('' + value) makes it output the correct toString()-value.
          {
            attributeValue = '' + value;
          }

          if (propertyInfo.sanitizeURL) {
            sanitizeURL(attributeValue.toString());
          }
        }

        if (attributeNamespace) {
          node.setAttributeNS(attributeNamespace, attributeName, attributeValue);
        } else {
          node.setAttribute(attributeName, attributeValue);
        }
      }
    }

    var BEFORE_SLASH_RE = /^(.*)[\\\/]/;

    function describeComponentFrame(name, source, ownerName) {
      var sourceInfo = '';

      if (source) {
        var path = source.fileName;
        var fileName = path.replace(BEFORE_SLASH_RE, '');
        {
          // In DEV, include code for a common special case:
          // prefer "folder/index.js" instead of just "index.js".
          if (/^index\./.test(fileName)) {
            var match = path.match(BEFORE_SLASH_RE);

            if (match) {
              var pathBeforeSlash = match[1];

              if (pathBeforeSlash) {
                var folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, '');
                fileName = folderName + '/' + fileName;
              }
            }
          }
        }
        sourceInfo = ' (at ' + fileName + ':' + source.lineNumber + ')';
      } else if (ownerName) {
        sourceInfo = ' (created by ' + ownerName + ')';
      }

      return '\n    in ' + (name || 'Unknown') + sourceInfo;
    } // The Symbol used to tag the ReactElement-like types. If there is no native Symbol
    // nor polyfill, then a plain number is used for performance.


    var hasSymbol = typeof Symbol === 'function' && Symbol.for;
    var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;
    var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;
    var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;
    var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;
    var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;
    var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;
    var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; // TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary

    var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;
    var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;
    var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;
    var REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for('react.suspense_list') : 0xead8;
    var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;
    var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;
    var REACT_BLOCK_TYPE = hasSymbol ? Symbol.for('react.block') : 0xead9;
    var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
    var FAUX_ITERATOR_SYMBOL = '@@iterator';

    function getIteratorFn(maybeIterable) {
      if (maybeIterable === null || typeof maybeIterable !== 'object') {
        return null;
      }

      var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];

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

      return null;
    }

    var Uninitialized = -1;
    var Pending = 0;
    var Resolved = 1;
    var Rejected = 2;

    function refineResolvedLazyComponent(lazyComponent) {
      return lazyComponent._status === Resolved ? lazyComponent._result : null;
    }

    function initializeLazyComponentType(lazyComponent) {
      if (lazyComponent._status === Uninitialized) {
        lazyComponent._status = Pending;
        var ctor = lazyComponent._ctor;
        var thenable = ctor();
        lazyComponent._result = thenable;
        thenable.then(function (moduleObject) {
          if (lazyComponent._status === Pending) {
            var defaultExport = moduleObject.default;
            {
              if (defaultExport === undefined) {
                error('lazy: Expected the result of a dynamic import() call. ' + 'Instead received: %s\n\nYour code should look like: \n  ' + "const MyComponent = lazy(() => import('./MyComponent'))", moduleObject);
              }
            }
            lazyComponent._status = Resolved;
            lazyComponent._result = defaultExport;
          }
        }, function (error) {
          if (lazyComponent._status === Pending) {
            lazyComponent._status = Rejected;
            lazyComponent._result = error;
          }
        });
      }
    }

    function getWrappedName(outerType, innerType, wrapperName) {
      var functionName = innerType.displayName || innerType.name || '';
      return outerType.displayName || (functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName);
    }

    function getComponentName(type) {
      if (type == null) {
        // Host root, text node or just invalid type.
        return null;
      }

      {
        if (typeof type.tag === 'number') {
          error('Received an unexpected object in getComponentName(). ' + 'This is likely a bug in React. Please file an issue.');
        }
      }

      if (typeof type === 'function') {
        return type.displayName || type.name || null;
      }

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

      switch (type) {
        case REACT_FRAGMENT_TYPE:
          return 'Fragment';

        case REACT_PORTAL_TYPE:
          return 'Portal';

        case REACT_PROFILER_TYPE:
          return "Profiler";

        case REACT_STRICT_MODE_TYPE:
          return 'StrictMode';

        case REACT_SUSPENSE_TYPE:
          return 'Suspense';

        case REACT_SUSPENSE_LIST_TYPE:
          return 'SuspenseList';
      }

      if (typeof type === 'object') {
        switch (type.$$typeof) {
          case REACT_CONTEXT_TYPE:
            return 'Context.Consumer';

          case REACT_PROVIDER_TYPE:
            return 'Context.Provider';

          case REACT_FORWARD_REF_TYPE:
            return getWrappedName(type, type.render, 'ForwardRef');

          case REACT_MEMO_TYPE:
            return getComponentName(type.type);

          case REACT_BLOCK_TYPE:
            return getComponentName(type.render);

          case REACT_LAZY_TYPE:
            {
              var thenable = type;
              var resolvedThenable = refineResolvedLazyComponent(thenable);

              if (resolvedThenable) {
                return getComponentName(resolvedThenable);
              }

              break;
            }
        }
      }

      return null;
    }

    var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;

    function describeFiber(fiber) {
      switch (fiber.tag) {
        case HostRoot:
        case HostPortal:
        case HostText:
        case Fragment:
        case ContextProvider:
        case ContextConsumer:
          return '';

        default:
          var owner = fiber._debugOwner;
          var source = fiber._debugSource;
          var name = getComponentName(fiber.type);
          var ownerName = null;

          if (owner) {
            ownerName = getComponentName(owner.type);
          }

          return describeComponentFrame(name, source, ownerName);
      }
    }

    function getStackByFiberInDevAndProd(workInProgress) {
      var info = '';
      var node = workInProgress;

      do {
        info += describeFiber(node);
        node = node.return;
      } while (node);

      return info;
    }

    var current = null;
    var isRendering = false;

    function getCurrentFiberOwnerNameInDevOrNull() {
      {
        if (current === null) {
          return null;
        }

        var owner = current._debugOwner;

        if (owner !== null && typeof owner !== 'undefined') {
          return getComponentName(owner.type);
        }
      }
      return null;
    }

    function getCurrentFiberStackInDev() {
      {
        if (current === null) {
          return '';
        } // Safe because if current fiber exists, we are reconciling,
        // and it is guaranteed to be the work-in-progress version.


        return getStackByFiberInDevAndProd(current);
      }
    }

    function resetCurrentFiber() {
      {
        ReactDebugCurrentFrame$1.getCurrentStack = null;
        current = null;
        isRendering = false;
      }
    }

    function setCurrentFiber(fiber) {
      {
        ReactDebugCurrentFrame$1.getCurrentStack = getCurrentFiberStackInDev;
        current = fiber;
        isRendering = false;
      }
    }

    function setIsRendering(rendering) {
      {
        isRendering = rendering;
      }
    } // Flow does not allow string concatenation of most non-string types. To work
    // around this limitation, we use an opaque type that can only be obtained by
    // passing the value through getToStringValue first.


    function toString(value) {
      return '' + value;
    }

    function getToStringValue(value) {
      switch (typeof value) {
        case 'boolean':
        case 'number':
        case 'object':
        case 'string':
        case 'undefined':
          return value;

        default:
          // function, symbol are assigned as empty strings
          return '';
      }
    }

    var ReactDebugCurrentFrame$2 = null;
    var ReactControlledValuePropTypes = {
      checkPropTypes: null
    };
    {
      ReactDebugCurrentFrame$2 = ReactSharedInternals.ReactDebugCurrentFrame;
      var hasReadOnlyValue = {
        button: true,
        checkbox: true,
        image: true,
        hidden: true,
        radio: true,
        reset: true,
        submit: true
      };
      var propTypes = {
        value: function (props, propName, componentName) {
          if (hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled || props[propName] == null || enableDeprecatedFlareAPI) {
            return null;
          }

          return new Error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.');
        },
        checked: function (props, propName, componentName) {
          if (props.onChange || props.readOnly || props.disabled || props[propName] == null || enableDeprecatedFlareAPI) {
            return null;
          }

          return new Error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.');
        }
      };
      /**
       * Provide a linked `value` attribute for controlled forms. You should not use
       * this outside of the ReactDOM controlled form components.
       */

      ReactControlledValuePropTypes.checkPropTypes = function (tagName, props) {
        checkPropTypes(propTypes, props, 'prop', tagName, ReactDebugCurrentFrame$2.getStackAddendum);
      };
    }

    function isCheckable(elem) {
      var type = elem.type;
      var nodeName = elem.nodeName;
      return nodeName && nodeName.toLowerCase() === 'input' && (type === 'checkbox' || type === 'radio');
    }

    function getTracker(node) {
      return node._valueTracker;
    }

    function detachTracker(node) {
      node._valueTracker = null;
    }

    function getValueFromNode(node) {
      var value = '';

      if (!node) {
        return value;
      }

      if (isCheckable(node)) {
        value = node.checked ? 'true' : 'false';
      } else {
        value = node.value;
      }

      return value;
    }

    function trackValueOnNode(node) {
      var valueField = isCheckable(node) ? 'checked' : 'value';
      var descriptor = Object.getOwnPropertyDescriptor(node.constructor.prototype, valueField);
      var currentValue = '' + node[valueField]; // if someone has already defined a value or Safari, then bail
      // and don't track value will cause over reporting of changes,
      // but it's better then a hard failure
      // (needed for certain tests that spyOn input values and Safari)

      if (node.hasOwnProperty(valueField) || typeof descriptor === 'undefined' || typeof descriptor.get !== 'function' || typeof descriptor.set !== 'function') {
        return;
      }

      var get = descriptor.get,
          set = descriptor.set;
      Object.defineProperty(node, valueField, {
        configurable: true,
        get: function () {
          return get.call(this);
        },
        set: function (value) {
          currentValue = '' + value;
          set.call(this, value);
        }
      }); // We could've passed this the first time
      // but it triggers a bug in IE11 and Edge 14/15.
      // Calling defineProperty() again should be equivalent.
      // https://github.com/facebook/react/issues/11768

      Object.defineProperty(node, valueField, {
        enumerable: descriptor.enumerable
      });
      var tracker = {
        getValue: function () {
          return currentValue;
        },
        setValue: function (value) {
          currentValue = '' + value;
        },
        stopTracking: function () {
          detachTracker(node);
          delete node[valueField];
        }
      };
      return tracker;
    }

    function track(node) {
      if (getTracker(node)) {
        return;
      } // TODO: Once it's just Fiber we can move this to node._wrapperState


      node._valueTracker = trackValueOnNode(node);
    }

    function updateValueIfChanged(node) {
      if (!node) {
        return false;
      }

      var tracker = getTracker(node); // if there is no tracker at this point it's unlikely
      // that trying again will succeed

      if (!tracker) {
        return true;
      }

      var lastValue = tracker.getValue();
      var nextValue = getValueFromNode(node);

      if (nextValue !== lastValue) {
        tracker.setValue(nextValue);
        return true;
      }

      return false;
    }

    var didWarnValueDefaultValue = false;
    var didWarnCheckedDefaultChecked = false;
    var didWarnControlledToUncontrolled = false;
    var didWarnUncontrolledToControlled = false;

    function isControlled(props) {
      var usesChecked = props.type === 'checkbox' || props.type === 'radio';
      return usesChecked ? props.checked != null : props.value != null;
    }
    /**
     * Implements an <input> host component that allows setting these optional
     * props: `checked`, `value`, `defaultChecked`, and `defaultValue`.
     *
     * If `checked` or `value` are not supplied (or null/undefined), user actions
     * that affect the checked state or value will trigger updates to the element.
     *
     * If they are supplied (and not null/undefined), the rendered element will not
     * trigger updates to the element. Instead, the props must change in order for
     * the rendered element to be updated.
     *
     * The rendered element will be initialized as unchecked (or `defaultChecked`)
     * with an empty value (or `defaultValue`).
     *
     * See http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html
     */


    function getHostProps(element, props) {
      var node = element;
      var checked = props.checked;

      var hostProps = _assign({}, props, {
        defaultChecked: undefined,
        defaultValue: undefined,
        value: undefined,
        checked: checked != null ? checked : node._wrapperState.initialChecked
      });

      return hostProps;
    }

    function initWrapperState(element, props) {
      {
        ReactControlledValuePropTypes.checkPropTypes('input', props);

        if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnCheckedDefaultChecked) {
          error('%s contains an input of type %s with both checked and defaultChecked props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component', props.type);
          didWarnCheckedDefaultChecked = true;
        }

        if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) {
          error('%s contains an input of type %s with both value and defaultValue props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component', props.type);
          didWarnValueDefaultValue = true;
        }
      }
      var node = element;
      var defaultValue = props.defaultValue == null ? '' : props.defaultValue;
      node._wrapperState = {
        initialChecked: props.checked != null ? props.checked : props.defaultChecked,
        initialValue: getToStringValue(props.value != null ? props.value : defaultValue),
        controlled: isControlled(props)
      };
    }

    function updateChecked(element, props) {
      var node = element;
      var checked = props.checked;

      if (checked != null) {
        setValueForProperty(node, 'checked', checked, false);
      }
    }

    function updateWrapper(element, props) {
      var node = element;
      {
        var controlled = isControlled(props);

        if (!node._wrapperState.controlled && controlled && !didWarnUncontrolledToControlled) {
          error('A component is changing an uncontrolled input of type %s to be controlled. ' + 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components', props.type);
          didWarnUncontrolledToControlled = true;
        }

        if (node._wrapperState.controlled && !controlled && !didWarnControlledToUncontrolled) {
          error('A component is changing a controlled input of type %s to be uncontrolled. ' + 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components', props.type);
          didWarnControlledToUncontrolled = true;
        }
      }
      updateChecked(element, props);
      var value = getToStringValue(props.value);
      var type = props.type;

      if (value != null) {
        if (type === 'number') {
          if (value === 0 && node.value === '' || // We explicitly want to coerce to number here if possible.
          // eslint-disable-next-line
          node.value != value) {
            node.value = toString(value);
          }
        } else if (node.value !== toString(value)) {
          node.value = toString(value);
        }
      } else if (type === 'submit' || type === 'reset') {
        // Submit/reset inputs need the attribute removed completely to avoid
        // blank-text buttons.
        node.removeAttribute('value');
        return;
      }

      {
        // When syncing the value attribute, the value comes from a cascade of
        // properties:
        //  1. The value React property
        //  2. The defaultValue React property
        //  3. Otherwise there should be no change
        if (props.hasOwnProperty('value')) {
          setDefaultValue(node, props.type, value);
        } else if (props.hasOwnProperty('defaultValue')) {
          setDefaultValue(node, props.type, getToStringValue(props.defaultValue));
        }
      }
      {
        // When syncing the checked attribute, it only changes when it needs
        // to be removed, such as transitioning from a checkbox into a text input
        if (props.checked == null && props.defaultChecked != null) {
          node.defaultChecked = !!props.defaultChecked;
        }
      }
    }

    function postMountWrapper(element, props, isHydrating) {
      var node = element; // Do not assign value if it is already set. This prevents user text input
      // from being lost during SSR hydration.

      if (props.hasOwnProperty('value') || props.hasOwnProperty('defaultValue')) {
        var type = props.type;
        var isButton = type === 'submit' || type === 'reset'; // Avoid setting value attribute on submit/reset inputs as it overrides the
        // default value provided by the browser. See: #12872

        if (isButton && (props.value === undefined || props.value === null)) {
          return;
        }

        var initialValue = toString(node._wrapperState.initialValue); // Do not assign value if it is already set. This prevents user text input
        // from being lost during SSR hydration.

        if (!isHydrating) {
          {
            // When syncing the value attribute, the value property should use
            // the wrapperState._initialValue property. This uses:
            //
            //   1. The value React property when present
            //   2. The defaultValue React property when present
            //   3. An empty string
            if (initialValue !== node.value) {
              node.value = initialValue;
            }
          }
        }

        {
          // Otherwise, the value attribute is synchronized to the property,
          // so we assign defaultValue to the same thing as the value property
          // assignment step above.
          node.defaultValue = initialValue;
        }
      } // Normally, we'd just do `node.checked = node.checked` upon initial mount, less this bug
      // this is needed to work around a chrome bug where setting defaultChecked
      // will sometimes influence the value of checked (even after detachment).
      // Reference: https://bugs.chromium.org/p/chromium/issues/detail?id=608416
      // We need to temporarily unset name to avoid disrupting radio button groups.


      var name = node.name;

      if (name !== '') {
        node.name = '';
      }

      {
        // When syncing the checked attribute, both the checked property and
        // attribute are assigned at the same time using defaultChecked. This uses:
        //
        //   1. The checked React property when present
        //   2. The defaultChecked React property when present
        //   3. Otherwise, false
        node.defaultChecked = !node.defaultChecked;
        node.defaultChecked = !!node._wrapperState.initialChecked;
      }

      if (name !== '') {
        node.name = name;
      }
    }

    function restoreControlledState(element, props) {
      var node = element;
      updateWrapper(node, props);
      updateNamedCousins(node, props);
    }

    function updateNamedCousins(rootNode, props) {
      var name = props.name;

      if (props.type === 'radio' && name != null) {
        var queryRoot = rootNode;

        while (queryRoot.parentNode) {
          queryRoot = queryRoot.parentNode;
        } // If `rootNode.form` was non-null, then we could try `form.elements`,
        // but that sometimes behaves strangely in IE8. We could also try using
        // `form.getElementsByName`, but that will only return direct children
        // and won't include inputs that use the HTML5 `form=` attribute. Since
        // the input might not even be in a form. It might not even be in the
        // document. Let's just use the local `querySelectorAll` to ensure we don't
        // miss anything.


        var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type="radio"]');

        for (var i = 0; i < group.length; i++) {
          var otherNode = group[i];

          if (otherNode === rootNode || otherNode.form !== rootNode.form) {
            continue;
          } // This will throw if radio buttons rendered by different copies of React
          // and the same name are rendered into the same form (same as #1939).
          // That's probably okay; we don't support it just as we don't support
          // mixing React radio buttons with non-React ones.


          var otherProps = getFiberCurrentPropsFromNode$1(otherNode);

          if (!otherProps) {
            {
              throw Error("ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported.");
            }
          } // We need update the tracked value on the named cousin since the value
          // was changed but the input saw no event or value set


          updateValueIfChanged(otherNode); // If this is a controlled radio button group, forcing the input that
          // was previously checked to update will cause it to be come re-checked
          // as appropriate.

          updateWrapper(otherNode, otherProps);
        }
      }
    } // In Chrome, assigning defaultValue to certain input types triggers input validation.
    // For number inputs, the display value loses trailing decimal points. For email inputs,
    // Chrome raises "The specified value <x> is not a valid email address".
    //
    // Here we check to see if the defaultValue has actually changed, avoiding these problems
    // when the user is inputting text
    //
    // https://github.com/facebook/react/issues/7253


    function setDefaultValue(node, type, value) {
      if ( // Focused number inputs synchronize on blur. See ChangeEventPlugin.js
      type !== 'number' || node.ownerDocument.activeElement !== node) {
        if (value == null) {
          node.defaultValue = toString(node._wrapperState.initialValue);
        } else if (node.defaultValue !== toString(value)) {
          node.defaultValue = toString(value);
        }
      }
    }

    var didWarnSelectedSetOnOption = false;
    var didWarnInvalidChild = false;

    function flattenChildren(children) {
      var content = ''; // Flatten children. We'll warn if they are invalid
      // during validateProps() which runs for hydration too.
      // Note that this would throw on non-element objects.
      // Elements are stringified (which is normally irrelevant
      // but matters for <fbt>).

      React.Children.forEach(children, function (child) {
        if (child == null) {
          return;
        }

        content += child; // Note: we don't warn about invalid children here.
        // Instead, this is done separately below so that
        // it happens during the hydration codepath too.
      });
      return content;
    }
    /**
     * Implements an <option> host component that warns when `selected` is set.
     */


    function validateProps(element, props) {
      {
        // This mirrors the codepath above, but runs for hydration too.
        // Warn about invalid children here so that client and hydration are consistent.
        // TODO: this seems like it could cause a DEV-only throw for hydration
        // if children contains a non-element object. We should try to avoid that.
        if (typeof props.children === 'object' && props.children !== null) {
          React.Children.forEach(props.children, function (child) {
            if (child == null) {
              return;
            }

            if (typeof child === 'string' || typeof child === 'number') {
              return;
            }

            if (typeof child.type !== 'string') {
              return;
            }

            if (!didWarnInvalidChild) {
              didWarnInvalidChild = true;
              error('Only strings and numbers are supported as <option> children.');
            }
          });
        } // TODO: Remove support for `selected` in <option>.


        if (props.selected != null && !didWarnSelectedSetOnOption) {
          error('Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.');
          didWarnSelectedSetOnOption = true;
        }
      }
    }

    function postMountWrapper$1(element, props) {
      // value="" should make a value attribute (#6219)
      if (props.value != null) {
        element.setAttribute('value', toString(getToStringValue(props.value)));
      }
    }

    function getHostProps$1(element, props) {
      var hostProps = _assign({
        children: undefined
      }, props);

      var content = flattenChildren(props.children);

      if (content) {
        hostProps.children = content;
      }

      return hostProps;
    }

    var didWarnValueDefaultValue$1;
    {
      didWarnValueDefaultValue$1 = false;
    }

    function getDeclarationErrorAddendum() {
      var ownerName = getCurrentFiberOwnerNameInDevOrNull();

      if (ownerName) {
        return '\n\nCheck the render method of `' + ownerName + '`.';
      }

      return '';
    }

    var valuePropNames = ['value', 'defaultValue'];
    /**
     * Validation function for `value` and `defaultValue`.
     */

    function checkSelectPropTypes(props) {
      {
        ReactControlledValuePropTypes.checkPropTypes('select', props);

        for (var i = 0; i < valuePropNames.length; i++) {
          var propName = valuePropNames[i];

          if (props[propName] == null) {
            continue;
          }

          var isArray = Array.isArray(props[propName]);

          if (props.multiple && !isArray) {
            error('The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, getDeclarationErrorAddendum());
          } else if (!props.multiple && isArray) {
            error('The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, getDeclarationErrorAddendum());
          }
        }
      }
    }

    function updateOptions(node, multiple, propValue, setDefaultSelected) {
      var options = node.options;

      if (multiple) {
        var selectedValues = propValue;
        var selectedValue = {};

        for (var i = 0; i < selectedValues.length; i++) {
          // Prefix to avoid chaos with special keys.
          selectedValue['$' + selectedValues[i]] = true;
        }

        for (var _i = 0; _i < options.length; _i++) {
          var selected = selectedValue.hasOwnProperty('$' + options[_i].value);

          if (options[_i].selected !== selected) {
            options[_i].selected = selected;
          }

          if (selected && setDefaultSelected) {
            options[_i].defaultSelected = true;
          }
        }
      } else {
        // Do not set `select.value` as exact behavior isn't consistent across all
        // browsers for all cases.
        var _selectedValue = toString(getToStringValue(propValue));

        var defaultSelected = null;

        for (var _i2 = 0; _i2 < options.length; _i2++) {
          if (options[_i2].value === _selectedValue) {
            options[_i2].selected = true;

            if (setDefaultSelected) {
              options[_i2].defaultSelected = true;
            }

            return;
          }

          if (defaultSelected === null && !options[_i2].disabled) {
            defaultSelected = options[_i2];
          }
        }

        if (defaultSelected !== null) {
          defaultSelected.selected = true;
        }
      }
    }
    /**
     * Implements a <select> host component that allows optionally setting the
     * props `value` and `defaultValue`. If `multiple` is false, the prop must be a
     * stringable. If `multiple` is true, the prop must be an array of stringables.
     *
     * If `value` is not supplied (or null/undefined), user actions that change the
     * selected option will trigger updates to the rendered options.
     *
     * If it is supplied (and not null/undefined), the rendered options will not
     * update in response to user actions. Instead, the `value` prop must change in
     * order for the rendered options to update.
     *
     * If `defaultValue` is provided, any options with the supplied values will be
     * selected.
     */


    function getHostProps$2(element, props) {
      return _assign({}, props, {
        value: undefined
      });
    }

    function initWrapperState$1(element, props) {
      var node = element;
      {
        checkSelectPropTypes(props);
      }
      node._wrapperState = {
        wasMultiple: !!props.multiple
      };
      {
        if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue$1) {
          error('Select elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled select ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components');
          didWarnValueDefaultValue$1 = true;
        }
      }
    }

    function postMountWrapper$2(element, props) {
      var node = element;
      node.multiple = !!props.multiple;
      var value = props.value;

      if (value != null) {
        updateOptions(node, !!props.multiple, value, false);
      } else if (props.defaultValue != null) {
        updateOptions(node, !!props.multiple, props.defaultValue, true);
      }
    }

    function postUpdateWrapper(element, props) {
      var node = element;
      var wasMultiple = node._wrapperState.wasMultiple;
      node._wrapperState.wasMultiple = !!props.multiple;
      var value = props.value;

      if (value != null) {
        updateOptions(node, !!props.multiple, value, false);
      } else if (wasMultiple !== !!props.multiple) {
        // For simplicity, reapply `defaultValue` if `multiple` is toggled.
        if (props.defaultValue != null) {
          updateOptions(node, !!props.multiple, props.defaultValue, true);
        } else {
          // Revert the select back to its default unselected state.
          updateOptions(node, !!props.multiple, props.multiple ? [] : '', false);
        }
      }
    }

    function restoreControlledState$1(element, props) {
      var node = element;
      var value = props.value;

      if (value != null) {
        updateOptions(node, !!props.multiple, value, false);
      }
    }

    var didWarnValDefaultVal = false;
    /**
     * Implements a <textarea> host component that allows setting `value`, and
     * `defaultValue`. This differs from the traditional DOM API because value is
     * usually set as PCDATA children.
     *
     * If `value` is not supplied (or null/undefined), user actions that affect the
     * value will trigger updates to the element.
     *
     * If `value` is supplied (and not null/undefined), the rendered element will
     * not trigger updates to the element. Instead, the `value` prop must change in
     * order for the rendered element to be updated.
     *
     * The rendered element will be initialized with an empty value, the prop
     * `defaultValue` if specified, or the children content (deprecated).
     */

    function getHostProps$3(element, props) {
      var node = element;

      if (!(props.dangerouslySetInnerHTML == null)) {
        {
          throw Error("`dangerouslySetInnerHTML` does not make sense on <textarea>.");
        }
      } // Always set children to the same thing. In IE9, the selection range will
      // get reset if `textContent` is mutated.  We could add a check in setTextContent
      // to only set the value if/when the value differs from the node value (which would
      // completely solve this IE9 bug), but Sebastian+Sophie seemed to like this
      // solution. The value can be a boolean or object so that's why it's forced
      // to be a string.


      var hostProps = _assign({}, props, {
        value: undefined,
        defaultValue: undefined,
        children: toString(node._wrapperState.initialValue)
      });

      return hostProps;
    }

    function initWrapperState$2(element, props) {
      var node = element;
      {
        ReactControlledValuePropTypes.checkPropTypes('textarea', props);

        if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValDefaultVal) {
          error('%s contains a textarea with both value and defaultValue props. ' + 'Textarea elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled textarea ' + 'and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component');
          didWarnValDefaultVal = true;
        }
      }
      var initialValue = props.value; // Only bother fetching default value if we're going to use it

      if (initialValue == null) {
        var children = props.children,
            defaultValue = props.defaultValue;

        if (children != null) {
          {
            error('Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.');
          }
          {
            if (!(defaultValue == null)) {
              {
                throw Error("If you supply `defaultValue` on a <textarea>, do not pass children.");
              }
            }

            if (Array.isArray(children)) {
              if (!(children.length <= 1)) {
                {
                  throw Error("<textarea> can only have at most one child.");
                }
              }

              children = children[0];
            }

            defaultValue = children;
          }
        }

        if (defaultValue == null) {
          defaultValue = '';
        }

        initialValue = defaultValue;
      }

      node._wrapperState = {
        initialValue: getToStringValue(initialValue)
      };
    }

    function updateWrapper$1(element, props) {
      var node = element;
      var value = getToStringValue(props.value);
      var defaultValue = getToStringValue(props.defaultValue);

      if (value != null) {
        // Cast `value` to a string to ensure the value is set correctly. While
        // browsers typically do this as necessary, jsdom doesn't.
        var newValue = toString(value); // To avoid side effects (such as losing text selection), only set value if changed

        if (newValue !== node.value) {
          node.value = newValue;
        }

        if (props.defaultValue == null && node.defaultValue !== newValue) {
          node.defaultValue = newValue;
        }
      }

      if (defaultValue != null) {
        node.defaultValue = toString(defaultValue);
      }
    }

    function postMountWrapper$3(element, props) {
      var node = element; // This is in postMount because we need access to the DOM node, which is not
      // available until after the component has mounted.

      var textContent = node.textContent; // Only set node.value if textContent is equal to the expected
      // initial value. In IE10/IE11 there is a bug where the placeholder attribute
      // will populate textContent as well.
      // https://developer.microsoft.com/microsoft-edge/platform/issues/101525/

      if (textContent === node._wrapperState.initialValue) {
        if (textContent !== '' && textContent !== null) {
          node.value = textContent;
        }
      }
    }

    function restoreControlledState$2(element, props) {
      // DOM component is still mounted; update
      updateWrapper$1(element, props);
    }

    var HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
    var MATH_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
    var SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
    var Namespaces = {
      html: HTML_NAMESPACE,
      mathml: MATH_NAMESPACE,
      svg: SVG_NAMESPACE
    }; // Assumes there is no parent namespace.

    function getIntrinsicNamespace(type) {
      switch (type) {
        case 'svg':
          return SVG_NAMESPACE;

        case 'math':
          return MATH_NAMESPACE;

        default:
          return HTML_NAMESPACE;
      }
    }

    function getChildNamespace(parentNamespace, type) {
      if (parentNamespace == null || parentNamespace === HTML_NAMESPACE) {
        // No (or default) parent namespace: potential entry point.
        return getIntrinsicNamespace(type);
      }

      if (parentNamespace === SVG_NAMESPACE && type === 'foreignObject') {
        // We're leaving SVG.
        return HTML_NAMESPACE;
      } // By default, pass namespace below.


      return parentNamespace;
    }
    /* globals MSApp */

    /**
     * Create a function which has 'unsafe' privileges (required by windows8 apps)
     */


    var createMicrosoftUnsafeLocalFunction = function (func) {
      if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) {
        return function (arg0, arg1, arg2, arg3) {
          MSApp.execUnsafeLocalFunction(function () {
            return func(arg0, arg1, arg2, arg3);
          });
        };
      } else {
        return func;
      }
    };

    var reusableSVGContainer;
    /**
     * Set the innerHTML property of a node
     *
     * @param {DOMElement} node
     * @param {string} html
     * @internal
     */

    var setInnerHTML = createMicrosoftUnsafeLocalFunction(function (node, html) {
      if (node.namespaceURI === Namespaces.svg) {
        if (!('innerHTML' in node)) {
          // IE does not have innerHTML for SVG nodes, so instead we inject the
          // new markup in a temp node and then move the child nodes across into
          // the target node
          reusableSVGContainer = reusableSVGContainer || document.createElement('div');
          reusableSVGContainer.innerHTML = '<svg>' + html.valueOf().toString() + '</svg>';
          var svgNode = reusableSVGContainer.firstChild;

          while (node.firstChild) {
            node.removeChild(node.firstChild);
          }

          while (svgNode.firstChild) {
            node.appendChild(svgNode.firstChild);
          }

          return;
        }
      }

      node.innerHTML = html;
    });
    /**
     * HTML nodeType values that represent the type of the node
     */

    var ELEMENT_NODE = 1;
    var TEXT_NODE = 3;
    var COMMENT_NODE = 8;
    var DOCUMENT_NODE = 9;
    var DOCUMENT_FRAGMENT_NODE = 11;
    /**
     * Set the textContent property of a node. For text updates, it's faster
     * to set the `nodeValue` of the Text node directly instead of using
     * `.textContent` which will remove the existing node and create a new one.
     *
     * @param {DOMElement} node
     * @param {string} text
     * @internal
     */

    var setTextContent = function (node, text) {
      if (text) {
        var firstChild = node.firstChild;

        if (firstChild && firstChild === node.lastChild && firstChild.nodeType === TEXT_NODE) {
          firstChild.nodeValue = text;
          return;
        }
      }

      node.textContent = text;
    }; // Do not use the below two methods directly!
    // Instead use constants exported from DOMTopLevelEventTypes in ReactDOM.
    // (It is the only module that is allowed to access these methods.)


    function unsafeCastStringToDOMTopLevelType(topLevelType) {
      return topLevelType;
    }

    function unsafeCastDOMTopLevelTypeToString(topLevelType) {
      return topLevelType;
    }
    /**
     * Generate a mapping of standard vendor prefixes using the defined style property and event name.
     *
     * @param {string} styleProp
     * @param {string} eventName
     * @returns {object}
     */


    function makePrefixMap(styleProp, eventName) {
      var prefixes = {};
      prefixes[styleProp.toLowerCase()] = eventName.toLowerCase();
      prefixes['Webkit' + styleProp] = 'webkit' + eventName;
      prefixes['Moz' + styleProp] = 'moz' + eventName;
      return prefixes;
    }
    /**
     * A list of event names to a configurable list of vendor prefixes.
     */


    var vendorPrefixes = {
      animationend: makePrefixMap('Animation', 'AnimationEnd'),
      animationiteration: makePrefixMap('Animation', 'AnimationIteration'),
      animationstart: makePrefixMap('Animation', 'AnimationStart'),
      transitionend: makePrefixMap('Transition', 'TransitionEnd')
    };
    /**
     * Event names that have already been detected and prefixed (if applicable).
     */

    var prefixedEventNames = {};
    /**
     * Element to check for prefixes on.
     */

    var style = {};
    /**
     * Bootstrap if a DOM exists.
     */

    if (canUseDOM) {
      style = document.createElement('div').style; // On some platforms, in particular some releases of Android 4.x,
      // the un-prefixed "animation" and "transition" properties are defined on the
      // style object but the events that fire will still be prefixed, so we need
      // to check if the un-prefixed events are usable, and if not remove them from the map.

      if (!('AnimationEvent' in window)) {
        delete vendorPrefixes.animationend.animation;
        delete vendorPrefixes.animationiteration.animation;
        delete vendorPrefixes.animationstart.animation;
      } // Same as above


      if (!('TransitionEvent' in window)) {
        delete vendorPrefixes.transitionend.transition;
      }
    }
    /**
     * Attempts to determine the correct vendor prefixed event name.
     *
     * @param {string} eventName
     * @returns {string}
     */


    function getVendorPrefixedEventName(eventName) {
      if (prefixedEventNames[eventName]) {
        return prefixedEventNames[eventName];
      } else if (!vendorPrefixes[eventName]) {
        return eventName;
      }

      var prefixMap = vendorPrefixes[eventName];

      for (var styleProp in prefixMap) {
        if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) {
          return prefixedEventNames[eventName] = prefixMap[styleProp];
        }
      }

      return eventName;
    }
    /**
     * To identify top level events in ReactDOM, we use constants defined by this
     * module. This is the only module that uses the unsafe* methods to express
     * that the constants actually correspond to the browser event names. This lets
     * us save some bundle size by avoiding a top level type -> event name map.
     * The rest of ReactDOM code should import top level types from this file.
     */


    var TOP_ABORT = unsafeCastStringToDOMTopLevelType('abort');
    var TOP_ANIMATION_END = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationend'));
    var TOP_ANIMATION_ITERATION = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationiteration'));
    var TOP_ANIMATION_START = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationstart'));
    var TOP_BLUR = unsafeCastStringToDOMTopLevelType('blur');
    var TOP_CAN_PLAY = unsafeCastStringToDOMTopLevelType('canplay');
    var TOP_CAN_PLAY_THROUGH = unsafeCastStringToDOMTopLevelType('canplaythrough');
    var TOP_CANCEL = unsafeCastStringToDOMTopLevelType('cancel');
    var TOP_CHANGE = unsafeCastStringToDOMTopLevelType('change');
    var TOP_CLICK = unsafeCastStringToDOMTopLevelType('click');
    var TOP_CLOSE = unsafeCastStringToDOMTopLevelType('close');
    var TOP_COMPOSITION_END = unsafeCastStringToDOMTopLevelType('compositionend');
    var TOP_COMPOSITION_START = unsafeCastStringToDOMTopLevelType('compositionstart');
    var TOP_COMPOSITION_UPDATE = unsafeCastStringToDOMTopLevelType('compositionupdate');
    var TOP_CONTEXT_MENU = unsafeCastStringToDOMTopLevelType('contextmenu');
    var TOP_COPY = unsafeCastStringToDOMTopLevelType('copy');
    var TOP_CUT = unsafeCastStringToDOMTopLevelType('cut');
    var TOP_DOUBLE_CLICK = unsafeCastStringToDOMTopLevelType('dblclick');
    var TOP_AUX_CLICK = unsafeCastStringToDOMTopLevelType('auxclick');
    var TOP_DRAG = unsafeCastStringToDOMTopLevelType('drag');
    var TOP_DRAG_END = unsafeCastStringToDOMTopLevelType('dragend');
    var TOP_DRAG_ENTER = unsafeCastStringToDOMTopLevelType('dragenter');
    var TOP_DRAG_EXIT = unsafeCastStringToDOMTopLevelType('dragexit');
    var TOP_DRAG_LEAVE = unsafeCastStringToDOMTopLevelType('dragleave');
    var TOP_DRAG_OVER = unsafeCastStringToDOMTopLevelType('dragover');
    var TOP_DRAG_START = unsafeCastStringToDOMTopLevelType('dragstart');
    var TOP_DROP = unsafeCastStringToDOMTopLevelType('drop');
    var TOP_DURATION_CHANGE = unsafeCastStringToDOMTopLevelType('durationchange');
    var TOP_EMPTIED = unsafeCastStringToDOMTopLevelType('emptied');
    var TOP_ENCRYPTED = unsafeCastStringToDOMTopLevelType('encrypted');
    var TOP_ENDED = unsafeCastStringToDOMTopLevelType('ended');
    var TOP_ERROR = unsafeCastStringToDOMTopLevelType('error');
    var TOP_FOCUS = unsafeCastStringToDOMTopLevelType('focus');
    var TOP_GOT_POINTER_CAPTURE = unsafeCastStringToDOMTopLevelType('gotpointercapture');
    var TOP_INPUT = unsafeCastStringToDOMTopLevelType('input');
    var TOP_INVALID = unsafeCastStringToDOMTopLevelType('invalid');
    var TOP_KEY_DOWN = unsafeCastStringToDOMTopLevelType('keydown');
    var TOP_KEY_PRESS = unsafeCastStringToDOMTopLevelType('keypress');
    var TOP_KEY_UP = unsafeCastStringToDOMTopLevelType('keyup');
    var TOP_LOAD = unsafeCastStringToDOMTopLevelType('load');
    var TOP_LOAD_START = unsafeCastStringToDOMTopLevelType('loadstart');
    var TOP_LOADED_DATA = unsafeCastStringToDOMTopLevelType('loadeddata');
    var TOP_LOADED_METADATA = unsafeCastStringToDOMTopLevelType('loadedmetadata');
    var TOP_LOST_POINTER_CAPTURE = unsafeCastStringToDOMTopLevelType('lostpointercapture');
    var TOP_MOUSE_DOWN = unsafeCastStringToDOMTopLevelType('mousedown');
    var TOP_MOUSE_MOVE = unsafeCastStringToDOMTopLevelType('mousemove');
    var TOP_MOUSE_OUT = unsafeCastStringToDOMTopLevelType('mouseout');
    var TOP_MOUSE_OVER = unsafeCastStringToDOMTopLevelType('mouseover');
    var TOP_MOUSE_UP = unsafeCastStringToDOMTopLevelType('mouseup');
    var TOP_PASTE = unsafeCastStringToDOMTopLevelType('paste');
    var TOP_PAUSE = unsafeCastStringToDOMTopLevelType('pause');
    var TOP_PLAY = unsafeCastStringToDOMTopLevelType('play');
    var TOP_PLAYING = unsafeCastStringToDOMTopLevelType('playing');
    var TOP_POINTER_CANCEL = unsafeCastStringToDOMTopLevelType('pointercancel');
    var TOP_POINTER_DOWN = unsafeCastStringToDOMTopLevelType('pointerdown');
    var TOP_POINTER_MOVE = unsafeCastStringToDOMTopLevelType('pointermove');
    var TOP_POINTER_OUT = unsafeCastStringToDOMTopLevelType('pointerout');
    var TOP_POINTER_OVER = unsafeCastStringToDOMTopLevelType('pointerover');
    var TOP_POINTER_UP = unsafeCastStringToDOMTopLevelType('pointerup');
    var TOP_PROGRESS = unsafeCastStringToDOMTopLevelType('progress');
    var TOP_RATE_CHANGE = unsafeCastStringToDOMTopLevelType('ratechange');
    var TOP_RESET = unsafeCastStringToDOMTopLevelType('reset');
    var TOP_SCROLL = unsafeCastStringToDOMTopLevelType('scroll');
    var TOP_SEEKED = unsafeCastStringToDOMTopLevelType('seeked');
    var TOP_SEEKING = unsafeCastStringToDOMTopLevelType('seeking');
    var TOP_SELECTION_CHANGE = unsafeCastStringToDOMTopLevelType('selectionchange');
    var TOP_STALLED = unsafeCastStringToDOMTopLevelType('stalled');
    var TOP_SUBMIT = unsafeCastStringToDOMTopLevelType('submit');
    var TOP_SUSPEND = unsafeCastStringToDOMTopLevelType('suspend');
    var TOP_TEXT_INPUT = unsafeCastStringToDOMTopLevelType('textInput');
    var TOP_TIME_UPDATE = unsafeCastStringToDOMTopLevelType('timeupdate');
    var TOP_TOGGLE = unsafeCastStringToDOMTopLevelType('toggle');
    var TOP_TOUCH_CANCEL = unsafeCastStringToDOMTopLevelType('touchcancel');
    var TOP_TOUCH_END = unsafeCastStringToDOMTopLevelType('touchend');
    var TOP_TOUCH_MOVE = unsafeCastStringToDOMTopLevelType('touchmove');
    var TOP_TOUCH_START = unsafeCastStringToDOMTopLevelType('touchstart');
    var TOP_TRANSITION_END = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('transitionend'));
    var TOP_VOLUME_CHANGE = unsafeCastStringToDOMTopLevelType('volumechange');
    var TOP_WAITING = unsafeCastStringToDOMTopLevelType('waiting');
    var TOP_WHEEL = unsafeCastStringToDOMTopLevelType('wheel'); // List of events that need to be individually attached to media elements.
    // Note that events in this list will *not* be listened to at the top level
    // unless they're explicitly whitelisted in `ReactBrowserEventEmitter.listenTo`.

    var mediaEventTypes = [TOP_ABORT, TOP_CAN_PLAY, TOP_CAN_PLAY_THROUGH, TOP_DURATION_CHANGE, TOP_EMPTIED, TOP_ENCRYPTED, TOP_ENDED, TOP_ERROR, TOP_LOADED_DATA, TOP_LOADED_METADATA, TOP_LOAD_START, TOP_PAUSE, TOP_PLAY, TOP_PLAYING, TOP_PROGRESS, TOP_RATE_CHANGE, TOP_SEEKED, TOP_SEEKING, TOP_STALLED, TOP_SUSPEND, TOP_TIME_UPDATE, TOP_VOLUME_CHANGE, TOP_WAITING];

    function getRawEventName(topLevelType) {
      return unsafeCastDOMTopLevelTypeToString(topLevelType);
    }

    var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map; // prettier-ignore

    var elementListenerMap = new PossiblyWeakMap();

    function getListenerMapForElement(element) {
      var listenerMap = elementListenerMap.get(element);

      if (listenerMap === undefined) {
        listenerMap = new Map();
        elementListenerMap.set(element, listenerMap);
      }

      return listenerMap;
    }
    /**
     * `ReactInstanceMap` maintains a mapping from a public facing stateful
     * instance (key) and the internal representation (value). This allows public
     * methods to accept the user facing instance as an argument and map them back
     * to internal methods.
     *
     * Note that this module is currently shared and assumed to be stateless.
     * If this becomes an actual Map, that will break.
     */


    function get(key) {
      return key._reactInternalFiber;
    }

    function has(key) {
      return key._reactInternalFiber !== undefined;
    }

    function set(key, value) {
      key._reactInternalFiber = value;
    } // Don't change these two values. They're used by React Dev Tools.


    var NoEffect =
    /*              */
    0;
    var PerformedWork =
    /*         */
    1; // You can change the rest (and add more).

    var Placement =
    /*             */
    2;
    var Update =
    /*                */
    4;
    var PlacementAndUpdate =
    /*    */
    6;
    var Deletion =
    /*              */
    8;
    var ContentReset =
    /*          */
    16;
    var Callback =
    /*              */
    32;
    var DidCapture =
    /*            */
    64;
    var Ref =
    /*                   */
    128;
    var Snapshot =
    /*              */
    256;
    var Passive =
    /*               */
    512;
    var Hydrating =
    /*             */
    1024;
    var HydratingAndUpdate =
    /*    */
    1028; // Passive & Update & Callback & Ref & Snapshot

    var LifecycleEffectMask =
    /*   */
    932; // Union of all host effects

    var HostEffectMask =
    /*        */
    2047;
    var Incomplete =
    /*            */
    2048;
    var ShouldCapture =
    /*         */
    4096;
    var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;

    function getNearestMountedFiber(fiber) {
      var node = fiber;
      var nearestMounted = fiber;

      if (!fiber.alternate) {
        // If there is no alternate, this might be a new tree that isn't inserted
        // yet. If it is, then it will have a pending insertion effect on it.
        var nextNode = node;

        do {
          node = nextNode;

          if ((node.effectTag & (Placement | Hydrating)) !== NoEffect) {
            // This is an insertion or in-progress hydration. The nearest possible
            // mounted fiber is the parent but we need to continue to figure out
            // if that one is still mounted.
            nearestMounted = node.return;
          }

          nextNode = node.return;
        } while (nextNode);
      } else {
        while (node.return) {
          node = node.return;
        }
      }

      if (node.tag === HostRoot) {
        // TODO: Check if this was a nested HostRoot when used with
        // renderContainerIntoSubtree.
        return nearestMounted;
      } // If we didn't hit the root, that means that we're in an disconnected tree
      // that has been unmounted.


      return null;
    }

    function getSuspenseInstanceFromFiber(fiber) {
      if (fiber.tag === SuspenseComponent) {
        var suspenseState = fiber.memoizedState;

        if (suspenseState === null) {
          var current = fiber.alternate;

          if (current !== null) {
            suspenseState = current.memoizedState;
          }
        }

        if (suspenseState !== null) {
          return suspenseState.dehydrated;
        }
      }

      return null;
    }

    function getContainerFromFiber(fiber) {
      return fiber.tag === HostRoot ? fiber.stateNode.containerInfo : null;
    }

    function isFiberMounted(fiber) {
      return getNearestMountedFiber(fiber) === fiber;
    }

    function isMounted(component) {
      {
        var owner = ReactCurrentOwner.current;

        if (owner !== null && owner.tag === ClassComponent) {
          var ownerFiber = owner;
          var instance = ownerFiber.stateNode;

          if (!instance._warnedAboutRefsInRender) {
            error('%s is accessing isMounted inside its render() function. ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', getComponentName(ownerFiber.type) || 'A component');
          }

          instance._warnedAboutRefsInRender = true;
        }
      }
      var fiber = get(component);

      if (!fiber) {
        return false;
      }

      return getNearestMountedFiber(fiber) === fiber;
    }

    function assertIsMounted(fiber) {
      if (!(getNearestMountedFiber(fiber) === fiber)) {
        {
          throw Error("Unable to find node on an unmounted component.");
        }
      }
    }

    function findCurrentFiberUsingSlowPath(fiber) {
      var alternate = fiber.alternate;

      if (!alternate) {
        // If there is no alternate, then we only need to check if it is mounted.
        var nearestMounted = getNearestMountedFiber(fiber);

        if (!(nearestMounted !== null)) {
          {
            throw Error("Unable to find node on an unmounted component.");
          }
        }

        if (nearestMounted !== fiber) {
          return null;
        }

        return fiber;
      } // If we have two possible branches, we'll walk backwards up to the root
      // to see what path the root points to. On the way we may hit one of the
      // special cases and we'll deal with them.


      var a = fiber;
      var b = alternate;

      while (true) {
        var parentA = a.return;

        if (parentA === null) {
          // We're at the root.
          break;
        }

        var parentB = parentA.alternate;

        if (parentB === null) {
          // There is no alternate. This is an unusual case. Currently, it only
          // happens when a Suspense component is hidden. An extra fragment fiber
          // is inserted in between the Suspense fiber and its children. Skip
          // over this extra fragment fiber and proceed to the next parent.
          var nextParent = parentA.return;

          if (nextParent !== null) {
            a = b = nextParent;
            continue;
          } // If there's no parent, we're at the root.


          break;
        } // If both copies of the parent fiber point to the same child, we can
        // assume that the child is current. This happens when we bailout on low
        // priority: the bailed out fiber's child reuses the current child.


        if (parentA.child === parentB.child) {
          var child = parentA.child;

          while (child) {
            if (child === a) {
              // We've determined that A is the current branch.
              assertIsMounted(parentA);
              return fiber;
            }

            if (child === b) {
              // We've determined that B is the current branch.
              assertIsMounted(parentA);
              return alternate;
            }

            child = child.sibling;
          } // We should never have an alternate for any mounting node. So the only
          // way this could possibly happen is if this was unmounted, if at all.


          {
            {
              throw Error("Unable to find node on an unmounted component.");
            }
          }
        }

        if (a.return !== b.return) {
          // The return pointer of A and the return pointer of B point to different
          // fibers. We assume that return pointers never criss-cross, so A must
          // belong to the child set of A.return, and B must belong to the child
          // set of B.return.
          a = parentA;
          b = parentB;
        } else {
          // The return pointers point to the same fiber. We'll have to use the
          // default, slow path: scan the child sets of each parent alternate to see
          // which child belongs to which set.
          //
          // Search parent A's child set
          var didFindChild = false;
          var _child = parentA.child;

          while (_child) {
            if (_child === a) {
              didFindChild = true;
              a = parentA;
              b = parentB;
              break;
            }

            if (_child === b) {
              didFindChild = true;
              b = parentA;
              a = parentB;
              break;
            }

            _child = _child.sibling;
          }

          if (!didFindChild) {
            // Search parent B's child set
            _child = parentB.child;

            while (_child) {
              if (_child === a) {
                didFindChild = true;
                a = parentB;
                b = parentA;
                break;
              }

              if (_child === b) {
                didFindChild = true;
                b = parentB;
                a = parentA;
                break;
              }

              _child = _child.sibling;
            }

            if (!didFindChild) {
              {
                throw Error("Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue.");
              }
            }
          }
        }

        if (!(a.alternate === b)) {
          {
            throw Error("Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue.");
          }
        }
      } // If the root is not a host container, we're in a disconnected tree. I.e.
      // unmounted.


      if (!(a.tag === HostRoot)) {
        {
          throw Error("Unable to find node on an unmounted component.");
        }
      }

      if (a.stateNode.current === a) {
        // We've determined that A is the current branch.
        return fiber;
      } // Otherwise B has to be current branch.


      return alternate;
    }

    function findCurrentHostFiber(parent) {
      var currentParent = findCurrentFiberUsingSlowPath(parent);

      if (!currentParent) {
        return null;
      } // Next we'll drill down this component to find the first HostComponent/Text.


      var node = currentParent;

      while (true) {
        if (node.tag === HostComponent || node.tag === HostText) {
          return node;
        } else if (node.child) {
          node.child.return = node;
          node = node.child;
          continue;
        }

        if (node === currentParent) {
          return null;
        }

        while (!node.sibling) {
          if (!node.return || node.return === currentParent) {
            return null;
          }

          node = node.return;
        }

        node.sibling.return = node.return;
        node = node.sibling;
      } // Flow needs the return null here, but ESLint complains about it.
      // eslint-disable-next-line no-unreachable


      return null;
    }

    function findCurrentHostFiberWithNoPortals(parent) {
      var currentParent = findCurrentFiberUsingSlowPath(parent);

      if (!currentParent) {
        return null;
      } // Next we'll drill down this component to find the first HostComponent/Text.


      var node = currentParent;

      while (true) {
        if (node.tag === HostComponent || node.tag === HostText || enableFundamentalAPI) {
          return node;
        } else if (node.child && node.tag !== HostPortal) {
          node.child.return = node;
          node = node.child;
          continue;
        }

        if (node === currentParent) {
          return null;
        }

        while (!node.sibling) {
          if (!node.return || node.return === currentParent) {
            return null;
          }

          node = node.return;
        }

        node.sibling.return = node.return;
        node = node.sibling;
      } // Flow needs the return null here, but ESLint complains about it.
      // eslint-disable-next-line no-unreachable


      return null;
    }
    /**
     * Accumulates items that must not be null or undefined into the first one. This
     * is used to conserve memory by avoiding array allocations, and thus sacrifices
     * API cleanness. Since `current` can be null before being passed in and not
     * null after this function, make sure to assign it back to `current`:
     *
     * `a = accumulateInto(a, b);`
     *
     * This API should be sparingly used. Try `accumulate` for something cleaner.
     *
     * @return {*|array<*>} An accumulation of items.
     */


    function accumulateInto(current, next) {
      if (!(next != null)) {
        {
          throw Error("accumulateInto(...): Accumulated items must not be null or undefined.");
        }
      }

      if (current == null) {
        return next;
      } // Both are not empty. Warning: Never call x.concat(y) when you are not
      // certain that x is an Array (x could be a string with concat method).


      if (Array.isArray(current)) {
        if (Array.isArray(next)) {
          current.push.apply(current, next);
          return current;
        }

        current.push(next);
        return current;
      }

      if (Array.isArray(next)) {
        // A bit too dangerous to mutate `next`.
        return [current].concat(next);
      }

      return [current, next];
    }
    /**
     * @param {array} arr an "accumulation" of items which is either an Array or
     * a single item. Useful when paired with the `accumulate` module. This is a
     * simple utility that allows us to reason about a collection of items, but
     * handling the case when there is exactly one item (and we do not need to
     * allocate an array).
     * @param {function} cb Callback invoked with each element or a collection.
     * @param {?} [scope] Scope used as `this` in a callback.
     */


    function forEachAccumulated(arr, cb, scope) {
      if (Array.isArray(arr)) {
        arr.forEach(cb, scope);
      } else if (arr) {
        cb.call(scope, arr);
      }
    }
    /**
     * Internal queue of events that have accumulated their dispatches and are
     * waiting to have their dispatches executed.
     */


    var eventQueue = null;
    /**
     * Dispatches an event and releases it back into the pool, unless persistent.
     *
     * @param {?object} event Synthetic event to be dispatched.
     * @private
     */

    var executeDispatchesAndRelease = function (event) {
      if (event) {
        executeDispatchesInOrder(event);

        if (!event.isPersistent()) {
          event.constructor.release(event);
        }
      }
    };

    var executeDispatchesAndReleaseTopLevel = function (e) {
      return executeDispatchesAndRelease(e);
    };

    function runEventsInBatch(events) {
      if (events !== null) {
        eventQueue = accumulateInto(eventQueue, events);
      } // Set `eventQueue` to null before processing it so that we can tell if more
      // events get enqueued while processing.


      var processingEventQueue = eventQueue;
      eventQueue = null;

      if (!processingEventQueue) {
        return;
      }

      forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel);

      if (!!eventQueue) {
        {
          throw Error("processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented.");
        }
      } // This would be a good time to rethrow if any of the event handlers threw.


      rethrowCaughtError();
    }
    /**
     * Gets the target node from a native browser event by accounting for
     * inconsistencies in browser DOM APIs.
     *
     * @param {object} nativeEvent Native browser event.
     * @return {DOMEventTarget} Target node.
     */


    function getEventTarget(nativeEvent) {
      // Fallback to nativeEvent.srcElement for IE9
      // https://github.com/facebook/react/issues/12506
      var target = nativeEvent.target || nativeEvent.srcElement || window; // Normalize SVG <use> element events #4963

      if (target.correspondingUseElement) {
        target = target.correspondingUseElement;
      } // Safari may fire events on text nodes (Node.TEXT_NODE is 3).
      // @see http://www.quirksmode.org/js/events_properties.html


      return target.nodeType === TEXT_NODE ? target.parentNode : target;
    }
    /**
     * Checks if an event is supported in the current execution environment.
     *
     * NOTE: This will not work correctly for non-generic events such as `change`,
     * `reset`, `load`, `error`, and `select`.
     *
     * Borrows from Modernizr.
     *
     * @param {string} eventNameSuffix Event name, e.g. "click".
     * @return {boolean} True if the event is supported.
     * @internal
     * @license Modernizr 3.0.0pre (Custom Build) | MIT
     */


    function isEventSupported(eventNameSuffix) {
      if (!canUseDOM) {
        return false;
      }

      var eventName = 'on' + eventNameSuffix;
      var isSupported = (eventName in document);

      if (!isSupported) {
        var element = document.createElement('div');
        element.setAttribute(eventName, 'return;');
        isSupported = typeof element[eventName] === 'function';
      }

      return isSupported;
    }
    /**
     * Summary of `DOMEventPluginSystem` event handling:
     *
     *  - Top-level delegation is used to trap most native browser events. This
     *    may only occur in the main thread and is the responsibility of
     *    ReactDOMEventListener, which is injected and can therefore support
     *    pluggable event sources. This is the only work that occurs in the main
     *    thread.
     *
     *  - We normalize and de-duplicate events to account for browser quirks. This
     *    may be done in the worker thread.
     *
     *  - Forward these native events (with the associated top-level type used to
     *    trap it) to `EventPluginRegistry`, which in turn will ask plugins if they want
     *    to extract any synthetic events.
     *
     *  - The `EventPluginRegistry` will then process each event by annotating them with
     *    "dispatches", a sequence of listeners and IDs that care about that event.
     *
     *  - The `EventPluginRegistry` then dispatches the events.
     *
     * Overview of React and the event system:
     *
     * +------------+    .
     * |    DOM     |    .
     * +------------+    .
     *       |           .
     *       v           .
     * +------------+    .
     * | ReactEvent |    .
     * |  Listener  |    .
     * +------------+    .                         +-----------+
     *       |           .               +--------+|SimpleEvent|
     *       |           .               |         |Plugin     |
     * +-----|------+    .               v         +-----------+
     * |     |      |    .    +--------------+                    +------------+
     * |     +-----------.--->|PluginRegistry|                    |    Event   |
     * |            |    .    |              |     +-----------+  | Propagators|
     * | ReactEvent |    .    |              |     |TapEvent   |  |------------|
     * |  Emitter   |    .    |              |<---+|Plugin     |  |other plugin|
     * |            |    .    |              |     +-----------+  |  utilities |
     * |     +-----------.--->|              |                    +------------+
     * |     |      |    .    +--------------+
     * +-----|------+    .                ^        +-----------+
     *       |           .                |        |Enter/Leave|
     *       +           .                +-------+|Plugin     |
     * +-------------+   .                         +-----------+
     * | application |   .
     * |-------------|   .
     * |             |   .
     * |             |   .
     * +-------------+   .
     *                   .
     *    React Core     .  General Purpose Event Plugin System
     */


    var CALLBACK_BOOKKEEPING_POOL_SIZE = 10;
    var callbackBookkeepingPool = [];

    function releaseTopLevelCallbackBookKeeping(instance) {
      instance.topLevelType = null;
      instance.nativeEvent = null;
      instance.targetInst = null;
      instance.ancestors.length = 0;

      if (callbackBookkeepingPool.length < CALLBACK_BOOKKEEPING_POOL_SIZE) {
        callbackBookkeepingPool.push(instance);
      }
    } // Used to store ancestor hierarchy in top level callback


    function getTopLevelCallbackBookKeeping(topLevelType, nativeEvent, targetInst, eventSystemFlags) {
      if (callbackBookkeepingPool.length) {
        var instance = callbackBookkeepingPool.pop();
        instance.topLevelType = topLevelType;
        instance.eventSystemFlags = eventSystemFlags;
        instance.nativeEvent = nativeEvent;
        instance.targetInst = targetInst;
        return instance;
      }

      return {
        topLevelType: topLevelType,
        eventSystemFlags: eventSystemFlags,
        nativeEvent: nativeEvent,
        targetInst: targetInst,
        ancestors: []
      };
    }
    /**
     * Find the deepest React component completely containing the root of the
     * passed-in instance (for use when entire React trees are nested within each
     * other). If React trees are not nested, returns null.
     */


    function findRootContainerNode(inst) {
      if (inst.tag === HostRoot) {
        return inst.stateNode.containerInfo;
      } // TODO: It may be a good idea to cache this to prevent unnecessary DOM
      // traversal, but caching is difficult to do correctly without using a
      // mutation observer to listen for all DOM changes.


      while (inst.return) {
        inst = inst.return;
      }

      if (inst.tag !== HostRoot) {
        // This can happen if we're in a detached tree.
        return null;
      }

      return inst.stateNode.containerInfo;
    }
    /**
     * Allows registered plugins an opportunity to extract events from top-level
     * native browser events.
     *
     * @return {*} An accumulation of synthetic events.
     * @internal
     */


    function extractPluginEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {
      var events = null;

      for (var i = 0; i < plugins.length; i++) {
        // Not every plugin in the ordering may be loaded at runtime.
        var possiblePlugin = plugins[i];

        if (possiblePlugin) {
          var extractedEvents = possiblePlugin.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags);

          if (extractedEvents) {
            events = accumulateInto(events, extractedEvents);
          }
        }
      }

      return events;
    }

    function runExtractedPluginEventsInBatch(topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {
      var events = extractPluginEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags);
      runEventsInBatch(events);
    }

    function handleTopLevel(bookKeeping) {
      var targetInst = bookKeeping.targetInst; // Loop through the hierarchy, in case there's any nested components.
      // It's important that we build the array of ancestors before calling any
      // event handlers, because event handlers can modify the DOM, leading to
      // inconsistencies with ReactMount's node cache. See #1105.

      var ancestor = targetInst;

      do {
        if (!ancestor) {
          var ancestors = bookKeeping.ancestors;
          ancestors.push(ancestor);
          break;
        }

        var root = findRootContainerNode(ancestor);

        if (!root) {
          break;
        }

        var tag = ancestor.tag;

        if (tag === HostComponent || tag === HostText) {
          bookKeeping.ancestors.push(ancestor);
        }

        ancestor = getClosestInstanceFromNode(root);
      } while (ancestor);

      for (var i = 0; i < bookKeeping.ancestors.length; i++) {
        targetInst = bookKeeping.ancestors[i];
        var eventTarget = getEventTarget(bookKeeping.nativeEvent);
        var topLevelType = bookKeeping.topLevelType;
        var nativeEvent = bookKeeping.nativeEvent;
        var eventSystemFlags = bookKeeping.eventSystemFlags; // If this is the first ancestor, we mark it on the system flags

        if (i === 0) {
          eventSystemFlags |= IS_FIRST_ANCESTOR;
        }

        runExtractedPluginEventsInBatch(topLevelType, targetInst, nativeEvent, eventTarget, eventSystemFlags);
      }
    }

    function dispatchEventForLegacyPluginEventSystem(topLevelType, eventSystemFlags, nativeEvent, targetInst) {
      var bookKeeping = getTopLevelCallbackBookKeeping(topLevelType, nativeEvent, targetInst, eventSystemFlags);

      try {
        // Event queue being processed in the same cycle allows
        // `preventDefault`.
        batchedEventUpdates(handleTopLevel, bookKeeping);
      } finally {
        releaseTopLevelCallbackBookKeeping(bookKeeping);
      }
    }
    /**
     * We listen for bubbled touch events on the document object.
     *
     * Firefox v8.01 (and possibly others) exhibited strange behavior when
     * mounting `onmousemove` events at some node that was not the document
     * element. The symptoms were that if your mouse is not moving over something
     * contained within that mount point (for example on the background) the
     * top-level listeners for `onmousemove` won't be called. However, if you
     * register the `mousemove` on the document object, then it will of course
     * catch all `mousemove`s. This along with iOS quirks, justifies restricting
     * top-level listeners to the document object only, at least for these
     * movement types of events and possibly all events.
     *
     * @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
     *
     * Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but
     * they bubble to document.
     *
     * @param {string} registrationName Name of listener (e.g. `onClick`).
     * @param {object} mountAt Container where to mount the listener
     */


    function legacyListenToEvent(registrationName, mountAt) {
      var listenerMap = getListenerMapForElement(mountAt);
      var dependencies = registrationNameDependencies[registrationName];

      for (var i = 0; i < dependencies.length; i++) {
        var dependency = dependencies[i];
        legacyListenToTopLevelEvent(dependency, mountAt, listenerMap);
      }
    }

    function legacyListenToTopLevelEvent(topLevelType, mountAt, listenerMap) {
      if (!listenerMap.has(topLevelType)) {
        switch (topLevelType) {
          case TOP_SCROLL:
            trapCapturedEvent(TOP_SCROLL, mountAt);
            break;

          case TOP_FOCUS:
          case TOP_BLUR:
            trapCapturedEvent(TOP_FOCUS, mountAt);
            trapCapturedEvent(TOP_BLUR, mountAt); // We set the flag for a single dependency later in this function,
            // but this ensures we mark both as attached rather than just one.

            listenerMap.set(TOP_BLUR, null);
            listenerMap.set(TOP_FOCUS, null);
            break;

          case TOP_CANCEL:
          case TOP_CLOSE:
            if (isEventSupported(getRawEventName(topLevelType))) {
              trapCapturedEvent(topLevelType, mountAt);
            }

            break;

          case TOP_INVALID:
          case TOP_SUBMIT:
          case TOP_RESET:
            // We listen to them on the target DOM elements.
            // Some of them bubble so we don't want them to fire twice.
            break;

          default:
            // By default, listen on the top level to all non-media events.
            // Media events don't bubble so adding the listener wouldn't do anything.
            var isMediaEvent = mediaEventTypes.indexOf(topLevelType) !== -1;

            if (!isMediaEvent) {
              trapBubbledEvent(topLevelType, mountAt);
            }

            break;
        }

        listenerMap.set(topLevelType, null);
      }
    }

    function isListeningToAllDependencies(registrationName, mountAt) {
      var listenerMap = getListenerMapForElement(mountAt);
      var dependencies = registrationNameDependencies[registrationName];

      for (var i = 0; i < dependencies.length; i++) {
        var dependency = dependencies[i];

        if (!listenerMap.has(dependency)) {
          return false;
        }
      }

      return true;
    }

    var attemptUserBlockingHydration;

    function setAttemptUserBlockingHydration(fn) {
      attemptUserBlockingHydration = fn;
    }

    var attemptContinuousHydration;

    function setAttemptContinuousHydration(fn) {
      attemptContinuousHydration = fn;
    }

    var attemptHydrationAtCurrentPriority;

    function setAttemptHydrationAtCurrentPriority(fn) {
      attemptHydrationAtCurrentPriority = fn;
    } // TODO: Upgrade this definition once we're on a newer version of Flow that


    var hasScheduledReplayAttempt = false; // The queue of discrete events to be replayed.

    var queuedDiscreteEvents = []; // Indicates if any continuous event targets are non-null for early bailout.
    // if the last target was dehydrated.

    var queuedFocus = null;
    var queuedDrag = null;
    var queuedMouse = null; // For pointer events there can be one latest event per pointerId.

    var queuedPointers = new Map();
    var queuedPointerCaptures = new Map(); // We could consider replaying selectionchange and touchmoves too.

    var queuedExplicitHydrationTargets = [];

    function hasQueuedDiscreteEvents() {
      return queuedDiscreteEvents.length > 0;
    }

    var discreteReplayableEvents = [TOP_MOUSE_DOWN, TOP_MOUSE_UP, TOP_TOUCH_CANCEL, TOP_TOUCH_END, TOP_TOUCH_START, TOP_AUX_CLICK, TOP_DOUBLE_CLICK, TOP_POINTER_CANCEL, TOP_POINTER_DOWN, TOP_POINTER_UP, TOP_DRAG_END, TOP_DRAG_START, TOP_DROP, TOP_COMPOSITION_END, TOP_COMPOSITION_START, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_INPUT, TOP_TEXT_INPUT, TOP_CLOSE, TOP_CANCEL, TOP_COPY, TOP_CUT, TOP_PASTE, TOP_CLICK, TOP_CHANGE, TOP_CONTEXT_MENU, TOP_RESET, TOP_SUBMIT];
    var continuousReplayableEvents = [TOP_FOCUS, TOP_BLUR, TOP_DRAG_ENTER, TOP_DRAG_LEAVE, TOP_MOUSE_OVER, TOP_MOUSE_OUT, TOP_POINTER_OVER, TOP_POINTER_OUT, TOP_GOT_POINTER_CAPTURE, TOP_LOST_POINTER_CAPTURE];

    function isReplayableDiscreteEvent(eventType) {
      return discreteReplayableEvents.indexOf(eventType) > -1;
    }

    function trapReplayableEventForDocument(topLevelType, document, listenerMap) {
      legacyListenToTopLevelEvent(topLevelType, document, listenerMap);
    }

    function eagerlyTrapReplayableEvents(container, document) {
      var listenerMapForDoc = getListenerMapForElement(document); // Discrete

      discreteReplayableEvents.forEach(function (topLevelType) {
        trapReplayableEventForDocument(topLevelType, document, listenerMapForDoc);
      }); // Continuous

      continuousReplayableEvents.forEach(function (topLevelType) {
        trapReplayableEventForDocument(topLevelType, document, listenerMapForDoc);
      });
    }

    function createQueuedReplayableEvent(blockedOn, topLevelType, eventSystemFlags, container, nativeEvent) {
      return {
        blockedOn: blockedOn,
        topLevelType: topLevelType,
        eventSystemFlags: eventSystemFlags | IS_REPLAYED,
        nativeEvent: nativeEvent,
        container: container
      };
    }

    function queueDiscreteEvent(blockedOn, topLevelType, eventSystemFlags, container, nativeEvent) {
      var queuedEvent = createQueuedReplayableEvent(blockedOn, topLevelType, eventSystemFlags, container, nativeEvent);
      queuedDiscreteEvents.push(queuedEvent);
    } // Resets the replaying for this type of continuous event to no event.


    function clearIfContinuousEvent(topLevelType, nativeEvent) {
      switch (topLevelType) {
        case TOP_FOCUS:
        case TOP_BLUR:
          queuedFocus = null;
          break;

        case TOP_DRAG_ENTER:
        case TOP_DRAG_LEAVE:
          queuedDrag = null;
          break;

        case TOP_MOUSE_OVER:
        case TOP_MOUSE_OUT:
          queuedMouse = null;
          break;

        case TOP_POINTER_OVER:
        case TOP_POINTER_OUT:
          {
            var pointerId = nativeEvent.pointerId;
            queuedPointers.delete(pointerId);
            break;
          }

        case TOP_GOT_POINTER_CAPTURE:
        case TOP_LOST_POINTER_CAPTURE:
          {
            var _pointerId = nativeEvent.pointerId;
            queuedPointerCaptures.delete(_pointerId);
            break;
          }
      }
    }

    function accumulateOrCreateContinuousQueuedReplayableEvent(existingQueuedEvent, blockedOn, topLevelType, eventSystemFlags, container, nativeEvent) {
      if (existingQueuedEvent === null || existingQueuedEvent.nativeEvent !== nativeEvent) {
        var queuedEvent = createQueuedReplayableEvent(blockedOn, topLevelType, eventSystemFlags, container, nativeEvent);

        if (blockedOn !== null) {
          var _fiber2 = getInstanceFromNode$1(blockedOn);

          if (_fiber2 !== null) {
            // Attempt to increase the priority of this target.
            attemptContinuousHydration(_fiber2);
          }
        }

        return queuedEvent;
      } // If we have already queued this exact event, then it's because
      // the different event systems have different DOM event listeners.
      // We can accumulate the flags and store a single event to be
      // replayed.


      existingQueuedEvent.eventSystemFlags |= eventSystemFlags;
      return existingQueuedEvent;
    }

    function queueIfContinuousEvent(blockedOn, topLevelType, eventSystemFlags, container, nativeEvent) {
      // These set relatedTarget to null because the replayed event will be treated as if we
      // moved from outside the window (no target) onto the target once it hydrates.
      // Instead of mutating we could clone the event.
      switch (topLevelType) {
        case TOP_FOCUS:
          {
            var focusEvent = nativeEvent;
            queuedFocus = accumulateOrCreateContinuousQueuedReplayableEvent(queuedFocus, blockedOn, topLevelType, eventSystemFlags, container, focusEvent);
            return true;
          }

        case TOP_DRAG_ENTER:
          {
            var dragEvent = nativeEvent;
            queuedDrag = accumulateOrCreateContinuousQueuedReplayableEvent(queuedDrag, blockedOn, topLevelType, eventSystemFlags, container, dragEvent);
            return true;
          }

        case TOP_MOUSE_OVER:
          {
            var mouseEvent = nativeEvent;
            queuedMouse = accumulateOrCreateContinuousQueuedReplayableEvent(queuedMouse, blockedOn, topLevelType, eventSystemFlags, container, mouseEvent);
            return true;
          }

        case TOP_POINTER_OVER:
          {
            var pointerEvent = nativeEvent;
            var pointerId = pointerEvent.pointerId;
            queuedPointers.set(pointerId, accumulateOrCreateContinuousQueuedReplayableEvent(queuedPointers.get(pointerId) || null, blockedOn, topLevelType, eventSystemFlags, container, pointerEvent));
            return true;
          }

        case TOP_GOT_POINTER_CAPTURE:
          {
            var _pointerEvent = nativeEvent;
            var _pointerId2 = _pointerEvent.pointerId;
            queuedPointerCaptures.set(_pointerId2, accumulateOrCreateContinuousQueuedReplayableEvent(queuedPointerCaptures.get(_pointerId2) || null, blockedOn, topLevelType, eventSystemFlags, container, _pointerEvent));
            return true;
          }
      }

      return false;
    } // Check if this target is unblocked. Returns true if it's unblocked.


    function attemptExplicitHydrationTarget(queuedTarget) {
      // TODO: This function shares a lot of logic with attemptToDispatchEvent.
      // Try to unify them. It's a bit tricky since it would require two return
      // values.
      var targetInst = getClosestInstanceFromNode(queuedTarget.target);

      if (targetInst !== null) {
        var nearestMounted = getNearestMountedFiber(targetInst);

        if (nearestMounted !== null) {
          var tag = nearestMounted.tag;

          if (tag === SuspenseComponent) {
            var instance = getSuspenseInstanceFromFiber(nearestMounted);

            if (instance !== null) {
              // We're blocked on hydrating this boundary.
              // Increase its priority.
              queuedTarget.blockedOn = instance;
              Scheduler.unstable_runWithPriority(queuedTarget.priority, function () {
                attemptHydrationAtCurrentPriority(nearestMounted);
              });
              return;
            }
          } else if (tag === HostRoot) {
            var root = nearestMounted.stateNode;

            if (root.hydrate) {
              queuedTarget.blockedOn = getContainerFromFiber(nearestMounted); // We don't currently have a way to increase the priority of
              // a root other than sync.

              return;
            }
          }
        }
      }

      queuedTarget.blockedOn = null;
    }

    function attemptReplayContinuousQueuedEvent(queuedEvent) {
      if (queuedEvent.blockedOn !== null) {
        return false;
      }

      var nextBlockedOn = attemptToDispatchEvent(queuedEvent.topLevelType, queuedEvent.eventSystemFlags, queuedEvent.container, queuedEvent.nativeEvent);

      if (nextBlockedOn !== null) {
        // We're still blocked. Try again later.
        var _fiber3 = getInstanceFromNode$1(nextBlockedOn);

        if (_fiber3 !== null) {
          attemptContinuousHydration(_fiber3);
        }

        queuedEvent.blockedOn = nextBlockedOn;
        return false;
      }

      return true;
    }

    function attemptReplayContinuousQueuedEventInMap(queuedEvent, key, map) {
      if (attemptReplayContinuousQueuedEvent(queuedEvent)) {
        map.delete(key);
      }
    }

    function replayUnblockedEvents() {
      hasScheduledReplayAttempt = false; // First replay discrete events.

      while (queuedDiscreteEvents.length > 0) {
        var nextDiscreteEvent = queuedDiscreteEvents[0];

        if (nextDiscreteEvent.blockedOn !== null) {
          // We're still blocked.
          // Increase the priority of this boundary to unblock
          // the next discrete event.
          var _fiber4 = getInstanceFromNode$1(nextDiscreteEvent.blockedOn);

          if (_fiber4 !== null) {
            attemptUserBlockingHydration(_fiber4);
          }

          break;
        }

        var nextBlockedOn = attemptToDispatchEvent(nextDiscreteEvent.topLevelType, nextDiscreteEvent.eventSystemFlags, nextDiscreteEvent.container, nextDiscreteEvent.nativeEvent);

        if (nextBlockedOn !== null) {
          // We're still blocked. Try again later.
          nextDiscreteEvent.blockedOn = nextBlockedOn;
        } else {
          // We've successfully replayed the first event. Let's try the next one.
          queuedDiscreteEvents.shift();
        }
      } // Next replay any continuous events.


      if (queuedFocus !== null && attemptReplayContinuousQueuedEvent(queuedFocus)) {
        queuedFocus = null;
      }

      if (queuedDrag !== null && attemptReplayContinuousQueuedEvent(queuedDrag)) {
        queuedDrag = null;
      }

      if (queuedMouse !== null && attemptReplayContinuousQueuedEvent(queuedMouse)) {
        queuedMouse = null;
      }

      queuedPointers.forEach(attemptReplayContinuousQueuedEventInMap);
      queuedPointerCaptures.forEach(attemptReplayContinuousQueuedEventInMap);
    }

    function scheduleCallbackIfUnblocked(queuedEvent, unblocked) {
      if (queuedEvent.blockedOn === unblocked) {
        queuedEvent.blockedOn = null;

        if (!hasScheduledReplayAttempt) {
          hasScheduledReplayAttempt = true; // Schedule a callback to attempt replaying as many events as are
          // now unblocked. This first might not actually be unblocked yet.
          // We could check it early to avoid scheduling an unnecessary callback.

          Scheduler.unstable_scheduleCallback(Scheduler.unstable_NormalPriority, replayUnblockedEvents);
        }
      }
    }

    function retryIfBlockedOn(unblocked) {
      // Mark anything that was blocked on this as no longer blocked
      // and eligible for a replay.
      if (queuedDiscreteEvents.length > 0) {
        scheduleCallbackIfUnblocked(queuedDiscreteEvents[0], unblocked); // This is a exponential search for each boundary that commits. I think it's
        // worth it because we expect very few discrete events to queue up and once
        // we are actually fully unblocked it will be fast to replay them.

        for (var i = 1; i < queuedDiscreteEvents.length; i++) {
          var queuedEvent = queuedDiscreteEvents[i];

          if (queuedEvent.blockedOn === unblocked) {
            queuedEvent.blockedOn = null;
          }
        }
      }

      if (queuedFocus !== null) {
        scheduleCallbackIfUnblocked(queuedFocus, unblocked);
      }

      if (queuedDrag !== null) {
        scheduleCallbackIfUnblocked(queuedDrag, unblocked);
      }

      if (queuedMouse !== null) {
        scheduleCallbackIfUnblocked(queuedMouse, unblocked);
      }

      var unblock = function (queuedEvent) {
        return scheduleCallbackIfUnblocked(queuedEvent, unblocked);
      };

      queuedPointers.forEach(unblock);
      queuedPointerCaptures.forEach(unblock);

      for (var _i = 0; _i < queuedExplicitHydrationTargets.length; _i++) {
        var queuedTarget = queuedExplicitHydrationTargets[_i];

        if (queuedTarget.blockedOn === unblocked) {
          queuedTarget.blockedOn = null;
        }
      }

      while (queuedExplicitHydrationTargets.length > 0) {
        var nextExplicitTarget = queuedExplicitHydrationTargets[0];

        if (nextExplicitTarget.blockedOn !== null) {
          // We're still blocked.
          break;
        } else {
          attemptExplicitHydrationTarget(nextExplicitTarget);

          if (nextExplicitTarget.blockedOn === null) {
            // We're unblocked.
            queuedExplicitHydrationTargets.shift();
          }
        }
      }
    }

    function addEventBubbleListener(element, eventType, listener) {
      element.addEventListener(eventType, listener, false);
    }

    function addEventCaptureListener(element, eventType, listener) {
      element.addEventListener(eventType, listener, true);
    } // do it in two places, which duplicates logic
    // and increases the bundle size, we do it all
    // here once. If we remove or refactor the
    // SimpleEventPlugin, we should also remove or
    // update the below line.


    var simpleEventPluginEventTypes = {};
    var topLevelEventsToDispatchConfig = new Map();
    var eventPriorities = new Map(); // We store most of the events in this module in pairs of two strings so we can re-use
    // the code required to apply the same logic for event prioritization and that of the
    // SimpleEventPlugin. This complicates things slightly, but the aim is to reduce code
    // duplication (for which there would be quite a bit). For the events that are not needed
    // for the SimpleEventPlugin (otherDiscreteEvents) we process them separately as an
    // array of top level events.
    // Lastly, we ignore prettier so we can keep the formatting sane.
    // prettier-ignore

    var discreteEventPairsForSimpleEventPlugin = [TOP_BLUR, 'blur', TOP_CANCEL, 'cancel', TOP_CLICK, 'click', TOP_CLOSE, 'close', TOP_CONTEXT_MENU, 'contextMenu', TOP_COPY, 'copy', TOP_CUT, 'cut', TOP_AUX_CLICK, 'auxClick', TOP_DOUBLE_CLICK, 'doubleClick', TOP_DRAG_END, 'dragEnd', TOP_DRAG_START, 'dragStart', TOP_DROP, 'drop', TOP_FOCUS, 'focus', TOP_INPUT, 'input', TOP_INVALID, 'invalid', TOP_KEY_DOWN, 'keyDown', TOP_KEY_PRESS, 'keyPress', TOP_KEY_UP, 'keyUp', TOP_MOUSE_DOWN, 'mouseDown', TOP_MOUSE_UP, 'mouseUp', TOP_PASTE, 'paste', TOP_PAUSE, 'pause', TOP_PLAY, 'play', TOP_POINTER_CANCEL, 'pointerCancel', TOP_POINTER_DOWN, 'pointerDown', TOP_POINTER_UP, 'pointerUp', TOP_RATE_CHANGE, 'rateChange', TOP_RESET, 'reset', TOP_SEEKED, 'seeked', TOP_SUBMIT, 'submit', TOP_TOUCH_CANCEL, 'touchCancel', TOP_TOUCH_END, 'touchEnd', TOP_TOUCH_START, 'touchStart', TOP_VOLUME_CHANGE, 'volumeChange'];
    var otherDiscreteEvents = [TOP_CHANGE, TOP_SELECTION_CHANGE, TOP_TEXT_INPUT, TOP_COMPOSITION_START, TOP_COMPOSITION_END, TOP_COMPOSITION_UPDATE]; // prettier-ignore

    var userBlockingPairsForSimpleEventPlugin = [TOP_DRAG, 'drag', TOP_DRAG_ENTER, 'dragEnter', TOP_DRAG_EXIT, 'dragExit', TOP_DRAG_LEAVE, 'dragLeave', TOP_DRAG_OVER, 'dragOver', TOP_MOUSE_MOVE, 'mouseMove', TOP_MOUSE_OUT, 'mouseOut', TOP_MOUSE_OVER, 'mouseOver', TOP_POINTER_MOVE, 'pointerMove', TOP_POINTER_OUT, 'pointerOut', TOP_POINTER_OVER, 'pointerOver', TOP_SCROLL, 'scroll', TOP_TOGGLE, 'toggle', TOP_TOUCH_MOVE, 'touchMove', TOP_WHEEL, 'wheel']; // prettier-ignore

    var continuousPairsForSimpleEventPlugin = [TOP_ABORT, 'abort', TOP_ANIMATION_END, 'animationEnd', TOP_ANIMATION_ITERATION, 'animationIteration', TOP_ANIMATION_START, 'animationStart', TOP_CAN_PLAY, 'canPlay', TOP_CAN_PLAY_THROUGH, 'canPlayThrough', TOP_DURATION_CHANGE, 'durationChange', TOP_EMPTIED, 'emptied', TOP_ENCRYPTED, 'encrypted', TOP_ENDED, 'ended', TOP_ERROR, 'error', TOP_GOT_POINTER_CAPTURE, 'gotPointerCapture', TOP_LOAD, 'load', TOP_LOADED_DATA, 'loadedData', TOP_LOADED_METADATA, 'loadedMetadata', TOP_LOAD_START, 'loadStart', TOP_LOST_POINTER_CAPTURE, 'lostPointerCapture', TOP_PLAYING, 'playing', TOP_PROGRESS, 'progress', TOP_SEEKING, 'seeking', TOP_STALLED, 'stalled', TOP_SUSPEND, 'suspend', TOP_TIME_UPDATE, 'timeUpdate', TOP_TRANSITION_END, 'transitionEnd', TOP_WAITING, 'waiting'];
    /**
     * Turns
     * ['abort', ...]
     * into
     * eventTypes = {
     *   'abort': {
     *     phasedRegistrationNames: {
     *       bubbled: 'onAbort',
     *       captured: 'onAbortCapture',
     *     },
     *     dependencies: [TOP_ABORT],
     *   },
     *   ...
     * };
     * topLevelEventsToDispatchConfig = new Map([
     *   [TOP_ABORT, { sameConfig }],
     * ]);
     */

    function processSimpleEventPluginPairsByPriority(eventTypes, priority) {
      // As the event types are in pairs of two, we need to iterate
      // through in twos. The events are in pairs of two to save code
      // and improve init perf of processing this array, as it will
      // result in far fewer object allocations and property accesses
      // if we only use three arrays to process all the categories of
      // instead of tuples.
      for (var i = 0; i < eventTypes.length; i += 2) {
        var topEvent = eventTypes[i];
        var event = eventTypes[i + 1];
        var capitalizedEvent = event[0].toUpperCase() + event.slice(1);
        var onEvent = 'on' + capitalizedEvent;
        var config = {
          phasedRegistrationNames: {
            bubbled: onEvent,
            captured: onEvent + 'Capture'
          },
          dependencies: [topEvent],
          eventPriority: priority
        };
        eventPriorities.set(topEvent, priority);
        topLevelEventsToDispatchConfig.set(topEvent, config);
        simpleEventPluginEventTypes[event] = config;
      }
    }

    function processTopEventPairsByPriority(eventTypes, priority) {
      for (var i = 0; i < eventTypes.length; i++) {
        eventPriorities.set(eventTypes[i], priority);
      }
    } // SimpleEventPlugin


    processSimpleEventPluginPairsByPriority(discreteEventPairsForSimpleEventPlugin, DiscreteEvent);
    processSimpleEventPluginPairsByPriority(userBlockingPairsForSimpleEventPlugin, UserBlockingEvent);
    processSimpleEventPluginPairsByPriority(continuousPairsForSimpleEventPlugin, ContinuousEvent); // Not used by SimpleEventPlugin

    processTopEventPairsByPriority(otherDiscreteEvents, DiscreteEvent);

    function getEventPriorityForPluginSystem(topLevelType) {
      var priority = eventPriorities.get(topLevelType); // Default to a ContinuousEvent. Note: we might
      // want to warn if we can't detect the priority
      // for the event.

      return priority === undefined ? ContinuousEvent : priority;
    } // Intentionally not named imports because Rollup would use dynamic dispatch for


    var UserBlockingPriority = Scheduler.unstable_UserBlockingPriority,
        runWithPriority = Scheduler.unstable_runWithPriority; // TODO: can we stop exporting these?

    var _enabled = true;

    function setEnabled(enabled) {
      _enabled = !!enabled;
    }

    function isEnabled() {
      return _enabled;
    }

    function trapBubbledEvent(topLevelType, element) {
      trapEventForPluginEventSystem(element, topLevelType, false);
    }

    function trapCapturedEvent(topLevelType, element) {
      trapEventForPluginEventSystem(element, topLevelType, true);
    }

    function trapEventForPluginEventSystem(container, topLevelType, capture) {
      var listener;

      switch (getEventPriorityForPluginSystem(topLevelType)) {
        case DiscreteEvent:
          listener = dispatchDiscreteEvent.bind(null, topLevelType, PLUGIN_EVENT_SYSTEM, container);
          break;

        case UserBlockingEvent:
          listener = dispatchUserBlockingUpdate.bind(null, topLevelType, PLUGIN_EVENT_SYSTEM, container);
          break;

        case ContinuousEvent:
        default:
          listener = dispatchEvent.bind(null, topLevelType, PLUGIN_EVENT_SYSTEM, container);
          break;
      }

      var rawEventName = getRawEventName(topLevelType);

      if (capture) {
        addEventCaptureListener(container, rawEventName, listener);
      } else {
        addEventBubbleListener(container, rawEventName, listener);
      }
    }

    function dispatchDiscreteEvent(topLevelType, eventSystemFlags, container, nativeEvent) {
      flushDiscreteUpdatesIfNeeded(nativeEvent.timeStamp);
      discreteUpdates(dispatchEvent, topLevelType, eventSystemFlags, container, nativeEvent);
    }

    function dispatchUserBlockingUpdate(topLevelType, eventSystemFlags, container, nativeEvent) {
      runWithPriority(UserBlockingPriority, dispatchEvent.bind(null, topLevelType, eventSystemFlags, container, nativeEvent));
    }

    function dispatchEvent(topLevelType, eventSystemFlags, container, nativeEvent) {
      if (!_enabled) {
        return;
      }

      if (hasQueuedDiscreteEvents() && isReplayableDiscreteEvent(topLevelType)) {
        // If we already have a queue of discrete events, and this is another discrete
        // event, then we can't dispatch it regardless of its target, since they
        // need to dispatch in order.
        queueDiscreteEvent(null, // Flags that we're not actually blocked on anything as far as we know.
        topLevelType, eventSystemFlags, container, nativeEvent);
        return;
      }

      var blockedOn = attemptToDispatchEvent(topLevelType, eventSystemFlags, container, nativeEvent);

      if (blockedOn === null) {
        // We successfully dispatched this event.
        clearIfContinuousEvent(topLevelType, nativeEvent);
        return;
      }

      if (isReplayableDiscreteEvent(topLevelType)) {
        // This this to be replayed later once the target is available.
        queueDiscreteEvent(blockedOn, topLevelType, eventSystemFlags, container, nativeEvent);
        return;
      }

      if (queueIfContinuousEvent(blockedOn, topLevelType, eventSystemFlags, container, nativeEvent)) {
        return;
      } // We need to clear only if we didn't queue because
      // queueing is accummulative.


      clearIfContinuousEvent(topLevelType, nativeEvent); // This is not replayable so we'll invoke it but without a target,
      // in case the event system needs to trace it.

      {
        dispatchEventForLegacyPluginEventSystem(topLevelType, eventSystemFlags, nativeEvent, null);
      }
    } // Attempt dispatching an event. Returns a SuspenseInstance or Container if it's blocked.


    function attemptToDispatchEvent(topLevelType, eventSystemFlags, container, nativeEvent) {
      // TODO: Warn if _enabled is false.
      var nativeEventTarget = getEventTarget(nativeEvent);
      var targetInst = getClosestInstanceFromNode(nativeEventTarget);

      if (targetInst !== null) {
        var nearestMounted = getNearestMountedFiber(targetInst);

        if (nearestMounted === null) {
          // This tree has been unmounted already. Dispatch without a target.
          targetInst = null;
        } else {
          var tag = nearestMounted.tag;

          if (tag === SuspenseComponent) {
            var instance = getSuspenseInstanceFromFiber(nearestMounted);

            if (instance !== null) {
              // Queue the event to be replayed later. Abort dispatching since we
              // don't want this event dispatched twice through the event system.
              // TODO: If this is the first discrete event in the queue. Schedule an increased
              // priority for this boundary.
              return instance;
            } // This shouldn't happen, something went wrong but to avoid blocking
            // the whole system, dispatch the event without a target.
            // TODO: Warn.


            targetInst = null;
          } else if (tag === HostRoot) {
            var root = nearestMounted.stateNode;

            if (root.hydrate) {
              // If this happens during a replay something went wrong and it might block
              // the whole system.
              return getContainerFromFiber(nearestMounted);
            }

            targetInst = null;
          } else if (nearestMounted !== targetInst) {
            // If we get an event (ex: img onload) before committing that
            // component's mount, ignore it for now (that is, treat it as if it was an
            // event on a non-React tree). We might also consider queueing events and
            // dispatching them after the mount.
            targetInst = null;
          }
        }
      }

      {
        dispatchEventForLegacyPluginEventSystem(topLevelType, eventSystemFlags, nativeEvent, targetInst);
      } // We're not blocked on anything.

      return null;
    } // List derived from Gecko source code:
    // https://github.com/mozilla/gecko-dev/blob/4e638efc71/layout/style/test/property_database.js


    var shorthandToLonghand = {
      animation: ['animationDelay', 'animationDirection', 'animationDuration', 'animationFillMode', 'animationIterationCount', 'animationName', 'animationPlayState', 'animationTimingFunction'],
      background: ['backgroundAttachment', 'backgroundClip', 'backgroundColor', 'backgroundImage', 'backgroundOrigin', 'backgroundPositionX', 'backgroundPositionY', 'backgroundRepeat', 'backgroundSize'],
      backgroundPosition: ['backgroundPositionX', 'backgroundPositionY'],
      border: ['borderBottomColor', 'borderBottomStyle', 'borderBottomWidth', 'borderImageOutset', 'borderImageRepeat', 'borderImageSlice', 'borderImageSource', 'borderImageWidth', 'borderLeftColor', 'borderLeftStyle', 'borderLeftWidth', 'borderRightColor', 'borderRightStyle', 'borderRightWidth', 'borderTopColor', 'borderTopStyle', 'borderTopWidth'],
      borderBlockEnd: ['borderBlockEndColor', 'borderBlockEndStyle', 'borderBlockEndWidth'],
      borderBlockStart: ['borderBlockStartColor', 'borderBlockStartStyle', 'borderBlockStartWidth'],
      borderBottom: ['borderBottomColor', 'borderBottomStyle', 'borderBottomWidth'],
      borderColor: ['borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor'],
      borderImage: ['borderImageOutset', 'borderImageRepeat', 'borderImageSlice', 'borderImageSource', 'borderImageWidth'],
      borderInlineEnd: ['borderInlineEndColor', 'borderInlineEndStyle', 'borderInlineEndWidth'],
      borderInlineStart: ['borderInlineStartColor', 'borderInlineStartStyle', 'borderInlineStartWidth'],
      borderLeft: ['borderLeftColor', 'borderLeftStyle', 'borderLeftWidth'],
      borderRadius: ['borderBottomLeftRadius', 'borderBottomRightRadius', 'borderTopLeftRadius', 'borderTopRightRadius'],
      borderRight: ['borderRightColor', 'borderRightStyle', 'borderRightWidth'],
      borderStyle: ['borderBottomStyle', 'borderLeftStyle', 'borderRightStyle', 'borderTopStyle'],
      borderTop: ['borderTopColor', 'borderTopStyle', 'borderTopWidth'],
      borderWidth: ['borderBottomWidth', 'borderLeftWidth', 'borderRightWidth', 'borderTopWidth'],
      columnRule: ['columnRuleColor', 'columnRuleStyle', 'columnRuleWidth'],
      columns: ['columnCount', 'columnWidth'],
      flex: ['flexBasis', 'flexGrow', 'flexShrink'],
      flexFlow: ['flexDirection', 'flexWrap'],
      font: ['fontFamily', 'fontFeatureSettings', 'fontKerning', 'fontLanguageOverride', 'fontSize', 'fontSizeAdjust', 'fontStretch', 'fontStyle', 'fontVariant', 'fontVariantAlternates', 'fontVariantCaps', 'fontVariantEastAsian', 'fontVariantLigatures', 'fontVariantNumeric', 'fontVariantPosition', 'fontWeight', 'lineHeight'],
      fontVariant: ['fontVariantAlternates', 'fontVariantCaps', 'fontVariantEastAsian', 'fontVariantLigatures', 'fontVariantNumeric', 'fontVariantPosition'],
      gap: ['columnGap', 'rowGap'],
      grid: ['gridAutoColumns', 'gridAutoFlow', 'gridAutoRows', 'gridTemplateAreas', 'gridTemplateColumns', 'gridTemplateRows'],
      gridArea: ['gridColumnEnd', 'gridColumnStart', 'gridRowEnd', 'gridRowStart'],
      gridColumn: ['gridColumnEnd', 'gridColumnStart'],
      gridColumnGap: ['columnGap'],
      gridGap: ['columnGap', 'rowGap'],
      gridRow: ['gridRowEnd', 'gridRowStart'],
      gridRowGap: ['rowGap'],
      gridTemplate: ['gridTemplateAreas', 'gridTemplateColumns', 'gridTemplateRows'],
      listStyle: ['listStyleImage', 'listStylePosition', 'listStyleType'],
      margin: ['marginBottom', 'marginLeft', 'marginRight', 'marginTop'],
      marker: ['markerEnd', 'markerMid', 'markerStart'],
      mask: ['maskClip', 'maskComposite', 'maskImage', 'maskMode', 'maskOrigin', 'maskPositionX', 'maskPositionY', 'maskRepeat', 'maskSize'],
      maskPosition: ['maskPositionX', 'maskPositionY'],
      outline: ['outlineColor', 'outlineStyle', 'outlineWidth'],
      overflow: ['overflowX', 'overflowY'],
      padding: ['paddingBottom', 'paddingLeft', 'paddingRight', 'paddingTop'],
      placeContent: ['alignContent', 'justifyContent'],
      placeItems: ['alignItems', 'justifyItems'],
      placeSelf: ['alignSelf', 'justifySelf'],
      textDecoration: ['textDecorationColor', 'textDecorationLine', 'textDecorationStyle'],
      textEmphasis: ['textEmphasisColor', 'textEmphasisStyle'],
      transition: ['transitionDelay', 'transitionDuration', 'transitionProperty', 'transitionTimingFunction'],
      wordWrap: ['overflowWrap']
    };
    /**
     * CSS properties which accept numbers but are not in units of "px".
     */

    var isUnitlessNumber = {
      animationIterationCount: true,
      borderImageOutset: true,
      borderImageSlice: true,
      borderImageWidth: true,
      boxFlex: true,
      boxFlexGroup: true,
      boxOrdinalGroup: true,
      columnCount: true,
      columns: true,
      flex: true,
      flexGrow: true,
      flexPositive: true,
      flexShrink: true,
      flexNegative: true,
      flexOrder: true,
      gridArea: true,
      gridRow: true,
      gridRowEnd: true,
      gridRowSpan: true,
      gridRowStart: true,
      gridColumn: true,
      gridColumnEnd: true,
      gridColumnSpan: true,
      gridColumnStart: true,
      fontWeight: true,
      lineClamp: true,
      lineHeight: true,
      opacity: true,
      order: true,
      orphans: true,
      tabSize: true,
      widows: true,
      zIndex: true,
      zoom: true,
      // SVG-related properties
      fillOpacity: true,
      floodOpacity: true,
      stopOpacity: true,
      strokeDasharray: true,
      strokeDashoffset: true,
      strokeMiterlimit: true,
      strokeOpacity: true,
      strokeWidth: true
    };
    /**
     * @param {string} prefix vendor-specific prefix, eg: Webkit
     * @param {string} key style name, eg: transitionDuration
     * @return {string} style name prefixed with `prefix`, properly camelCased, eg:
     * WebkitTransitionDuration
     */

    function prefixKey(prefix, key) {
      return prefix + key.charAt(0).toUpperCase() + key.substring(1);
    }
    /**
     * Support style names that may come passed in prefixed by adding permutations
     * of vendor prefixes.
     */


    var prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an
    // infinite loop, because it iterates over the newly added props too.

    Object.keys(isUnitlessNumber).forEach(function (prop) {
      prefixes.forEach(function (prefix) {
        isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop];
      });
    });
    /**
     * Convert a value into the proper css writable value. The style name `name`
     * should be logical (no hyphens), as specified
     * in `CSSProperty.isUnitlessNumber`.
     *
     * @param {string} name CSS property name such as `topMargin`.
     * @param {*} value CSS property value such as `10px`.
     * @return {string} Normalized style value with dimensions applied.
     */

    function dangerousStyleValue(name, value, isCustomProperty) {
      // Note that we've removed escapeTextForBrowser() calls here since the
      // whole string will be escaped when the attribute is injected into
      // the markup. If you provide unsafe user data here they can inject
      // arbitrary CSS which may be problematic (I couldn't repro this):
      // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
      // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
      // This is not an XSS hole but instead a potential CSS injection issue
      // which has lead to a greater discussion about how we're going to
      // trust URLs moving forward. See #2115901
      var isEmpty = value == null || typeof value === 'boolean' || value === '';

      if (isEmpty) {
        return '';
      }

      if (!isCustomProperty && typeof value === 'number' && value !== 0 && !(isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name])) {
        return value + 'px'; // Presumes implicit 'px' suffix for unitless numbers
      }

      return ('' + value).trim();
    }

    var uppercasePattern = /([A-Z])/g;
    var msPattern = /^ms-/;
    /**
     * Hyphenates a camelcased CSS property name, for example:
     *
     *   > hyphenateStyleName('backgroundColor')
     *   < "background-color"
     *   > hyphenateStyleName('MozTransition')
     *   < "-moz-transition"
     *   > hyphenateStyleName('msTransition')
     *   < "-ms-transition"
     *
     * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
     * is converted to `-ms-`.
     */

    function hyphenateStyleName(name) {
      return name.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern, '-ms-');
    }

    var warnValidStyle = function () {};

    {
      // 'msTransform' is correct, but the other prefixes should be capitalized
      var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/;
      var msPattern$1 = /^-ms-/;
      var hyphenPattern = /-(.)/g; // style values shouldn't contain a semicolon

      var badStyleValueWithSemicolonPattern = /;\s*$/;
      var warnedStyleNames = {};
      var warnedStyleValues = {};
      var warnedForNaNValue = false;
      var warnedForInfinityValue = false;

      var camelize = function (string) {
        return string.replace(hyphenPattern, function (_, character) {
          return character.toUpperCase();
        });
      };

      var warnHyphenatedStyleName = function (name) {
        if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
          return;
        }

        warnedStyleNames[name] = true;
        error('Unsupported style property %s. Did you mean %s?', name, // As Andi Smith suggests
        // (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix
        // is converted to lowercase `ms`.
        camelize(name.replace(msPattern$1, 'ms-')));
      };

      var warnBadVendoredStyleName = function (name) {
        if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
          return;
        }

        warnedStyleNames[name] = true;
        error('Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1));
      };

      var warnStyleValueWithSemicolon = function (name, value) {
        if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) {
          return;
        }

        warnedStyleValues[value] = true;
        error("Style property values shouldn't contain a semicolon. " + 'Try "%s: %s" instead.', name, value.replace(badStyleValueWithSemicolonPattern, ''));
      };

      var warnStyleValueIsNaN = function (name, value) {
        if (warnedForNaNValue) {
          return;
        }

        warnedForNaNValue = true;
        error('`NaN` is an invalid value for the `%s` css style property.', name);
      };

      var warnStyleValueIsInfinity = function (name, value) {
        if (warnedForInfinityValue) {
          return;
        }

        warnedForInfinityValue = true;
        error('`Infinity` is an invalid value for the `%s` css style property.', name);
      };

      warnValidStyle = function (name, value) {
        if (name.indexOf('-') > -1) {
          warnHyphenatedStyleName(name);
        } else if (badVendoredStyleNamePattern.test(name)) {
          warnBadVendoredStyleName(name);
        } else if (badStyleValueWithSemicolonPattern.test(value)) {
          warnStyleValueWithSemicolon(name, value);
        }

        if (typeof value === 'number') {
          if (isNaN(value)) {
            warnStyleValueIsNaN(name, value);
          } else if (!isFinite(value)) {
            warnStyleValueIsInfinity(name, value);
          }
        }
      };
    }
    var warnValidStyle$1 = warnValidStyle;
    /**
     * Operations for dealing with CSS properties.
     */

    /**
     * This creates a string that is expected to be equivalent to the style
     * attribute generated by server-side rendering. It by-passes warnings and
     * security checks so it's not safe to use this value for anything other than
     * comparison. It is only used in DEV for SSR validation.
     */

    function createDangerousStringForStyles(styles) {
      {
        var serialized = '';
        var delimiter = '';

        for (var styleName in styles) {
          if (!styles.hasOwnProperty(styleName)) {
            continue;
          }

          var styleValue = styles[styleName];

          if (styleValue != null) {
            var isCustomProperty = styleName.indexOf('--') === 0;
            serialized += delimiter + (isCustomProperty ? styleName : hyphenateStyleName(styleName)) + ':';
            serialized += dangerousStyleValue(styleName, styleValue, isCustomProperty);
            delimiter = ';';
          }
        }

        return serialized || null;
      }
    }
    /**
     * Sets the value for multiple styles on a node.  If a value is specified as
     * '' (empty string), the corresponding style property will be unset.
     *
     * @param {DOMElement} node
     * @param {object} styles
     */


    function setValueForStyles(node, styles) {
      var style = node.style;

      for (var styleName in styles) {
        if (!styles.hasOwnProperty(styleName)) {
          continue;
        }

        var isCustomProperty = styleName.indexOf('--') === 0;
        {
          if (!isCustomProperty) {
            warnValidStyle$1(styleName, styles[styleName]);
          }
        }
        var styleValue = dangerousStyleValue(styleName, styles[styleName], isCustomProperty);

        if (styleName === 'float') {
          styleName = 'cssFloat';
        }

        if (isCustomProperty) {
          style.setProperty(styleName, styleValue);
        } else {
          style[styleName] = styleValue;
        }
      }
    }

    function isValueEmpty(value) {
      return value == null || typeof value === 'boolean' || value === '';
    }
    /**
     * Given {color: 'red', overflow: 'hidden'} returns {
     *   color: 'color',
     *   overflowX: 'overflow',
     *   overflowY: 'overflow',
     * }. This can be read as "the overflowY property was set by the overflow
     * shorthand". That is, the values are the property that each was derived from.
     */


    function expandShorthandMap(styles) {
      var expanded = {};

      for (var key in styles) {
        var longhands = shorthandToLonghand[key] || [key];

        for (var i = 0; i < longhands.length; i++) {
          expanded[longhands[i]] = key;
        }
      }

      return expanded;
    }
    /**
     * When mixing shorthand and longhand property names, we warn during updates if
     * we expect an incorrect result to occur. In particular, we warn for:
     *
     * Updating a shorthand property (longhand gets overwritten):
     *   {font: 'foo', fontVariant: 'bar'} -> {font: 'baz', fontVariant: 'bar'}
     *   becomes .style.font = 'baz'
     * Removing a shorthand property (longhand gets lost too):
     *   {font: 'foo', fontVariant: 'bar'} -> {fontVariant: 'bar'}
     *   becomes .style.font = ''
     * Removing a longhand property (should revert to shorthand; doesn't):
     *   {font: 'foo', fontVariant: 'bar'} -> {font: 'foo'}
     *   becomes .style.fontVariant = ''
     */


    function validateShorthandPropertyCollisionInDev(styleUpdates, nextStyles) {
      {
        if (!nextStyles) {
          return;
        }

        var expandedUpdates = expandShorthandMap(styleUpdates);
        var expandedStyles = expandShorthandMap(nextStyles);
        var warnedAbout = {};

        for (var key in expandedUpdates) {
          var originalKey = expandedUpdates[key];
          var correctOriginalKey = expandedStyles[key];

          if (correctOriginalKey && originalKey !== correctOriginalKey) {
            var warningKey = originalKey + ',' + correctOriginalKey;

            if (warnedAbout[warningKey]) {
              continue;
            }

            warnedAbout[warningKey] = true;
            error('%s a style property during rerender (%s) when a ' + 'conflicting property is set (%s) can lead to styling bugs. To ' + "avoid this, don't mix shorthand and non-shorthand properties " + 'for the same value; instead, replace the shorthand with ' + 'separate values.', isValueEmpty(styleUpdates[originalKey]) ? 'Removing' : 'Updating', originalKey, correctOriginalKey);
          }
        }
      }
    } // For HTML, certain tags should omit their close tag. We keep a whitelist for
    // those special-case tags.


    var omittedCloseTags = {
      area: true,
      base: true,
      br: true,
      col: true,
      embed: true,
      hr: true,
      img: true,
      input: true,
      keygen: true,
      link: true,
      meta: true,
      param: true,
      source: true,
      track: true,
      wbr: true // NOTE: menuitem's close tag should be omitted, but that causes problems.

    }; // `omittedCloseTags` except that `menuitem` should still have its closing tag.

    var voidElementTags = _assign({
      menuitem: true
    }, omittedCloseTags);

    var HTML = '__html';
    var ReactDebugCurrentFrame$3 = null;
    {
      ReactDebugCurrentFrame$3 = ReactSharedInternals.ReactDebugCurrentFrame;
    }

    function assertValidProps(tag, props) {
      if (!props) {
        return;
      } // Note the use of `==` which checks for null or undefined.


      if (voidElementTags[tag]) {
        if (!(props.children == null && props.dangerouslySetInnerHTML == null)) {
          {
            throw Error(tag + " is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`." + ReactDebugCurrentFrame$3.getStackAddendum());
          }
        }
      }

      if (props.dangerouslySetInnerHTML != null) {
        if (!(props.children == null)) {
          {
            throw Error("Can only set one of `children` or `props.dangerouslySetInnerHTML`.");
          }
        }

        if (!(typeof props.dangerouslySetInnerHTML === 'object' && HTML in props.dangerouslySetInnerHTML)) {
          {
            throw Error("`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://fb.me/react-invariant-dangerously-set-inner-html for more information.");
          }
        }
      }

      {
        if (!props.suppressContentEditableWarning && props.contentEditable && props.children != null) {
          error('A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of ' + 'those nodes are unexpectedly modified or duplicated. This is ' + 'probably not intentional.');
        }
      }

      if (!(props.style == null || typeof props.style === 'object')) {
        {
          throw Error("The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX." + ReactDebugCurrentFrame$3.getStackAddendum());
        }
      }
    }

    function isCustomComponent(tagName, props) {
      if (tagName.indexOf('-') === -1) {
        return typeof props.is === 'string';
      }

      switch (tagName) {
        // These are reserved SVG and MathML elements.
        // We don't mind this whitelist too much because we expect it to never grow.
        // The alternative is to track the namespace in a few places which is convoluted.
        // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts
        case 'annotation-xml':
        case 'color-profile':
        case 'font-face':
        case 'font-face-src':
        case 'font-face-uri':
        case 'font-face-format':
        case 'font-face-name':
        case 'missing-glyph':
          return false;

        default:
          return true;
      }
    } // When adding attributes to the HTML or SVG whitelist, be sure to
    // also add them to this module to ensure casing and incorrect name
    // warnings.


    var possibleStandardNames = {
      // HTML
      accept: 'accept',
      acceptcharset: 'acceptCharset',
      'accept-charset': 'acceptCharset',
      accesskey: 'accessKey',
      action: 'action',
      allowfullscreen: 'allowFullScreen',
      alt: 'alt',
      as: 'as',
      async: 'async',
      autocapitalize: 'autoCapitalize',
      autocomplete: 'autoComplete',
      autocorrect: 'autoCorrect',
      autofocus: 'autoFocus',
      autoplay: 'autoPlay',
      autosave: 'autoSave',
      capture: 'capture',
      cellpadding: 'cellPadding',
      cellspacing: 'cellSpacing',
      challenge: 'challenge',
      charset: 'charSet',
      checked: 'checked',
      children: 'children',
      cite: 'cite',
      class: 'className',
      classid: 'classID',
      classname: 'className',
      cols: 'cols',
      colspan: 'colSpan',
      content: 'content',
      contenteditable: 'contentEditable',
      contextmenu: 'contextMenu',
      controls: 'controls',
      controlslist: 'controlsList',
      coords: 'coords',
      crossorigin: 'crossOrigin',
      dangerouslysetinnerhtml: 'dangerouslySetInnerHTML',
      data: 'data',
      datetime: 'dateTime',
      default: 'default',
      defaultchecked: 'defaultChecked',
      defaultvalue: 'defaultValue',
      defer: 'defer',
      dir: 'dir',
      disabled: 'disabled',
      disablepictureinpicture: 'disablePictureInPicture',
      download: 'download',
      draggable: 'draggable',
      enctype: 'encType',
      for: 'htmlFor',
      form: 'form',
      formmethod: 'formMethod',
      formaction: 'formAction',
      formenctype: 'formEncType',
      formnovalidate: 'formNoValidate',
      formtarget: 'formTarget',
      frameborder: 'frameBorder',
      headers: 'headers',
      height: 'height',
      hidden: 'hidden',
      high: 'high',
      href: 'href',
      hreflang: 'hrefLang',
      htmlfor: 'htmlFor',
      httpequiv: 'httpEquiv',
      'http-equiv': 'httpEquiv',
      icon: 'icon',
      id: 'id',
      innerhtml: 'innerHTML',
      inputmode: 'inputMode',
      integrity: 'integrity',
      is: 'is',
      itemid: 'itemID',
      itemprop: 'itemProp',
      itemref: 'itemRef',
      itemscope: 'itemScope',
      itemtype: 'itemType',
      keyparams: 'keyParams',
      keytype: 'keyType',
      kind: 'kind',
      label: 'label',
      lang: 'lang',
      list: 'list',
      loop: 'loop',
      low: 'low',
      manifest: 'manifest',
      marginwidth: 'marginWidth',
      marginheight: 'marginHeight',
      max: 'max',
      maxlength: 'maxLength',
      media: 'media',
      mediagroup: 'mediaGroup',
      method: 'method',
      min: 'min',
      minlength: 'minLength',
      multiple: 'multiple',
      muted: 'muted',
      name: 'name',
      nomodule: 'noModule',
      nonce: 'nonce',
      novalidate: 'noValidate',
      open: 'open',
      optimum: 'optimum',
      pattern: 'pattern',
      placeholder: 'placeholder',
      playsinline: 'playsInline',
      poster: 'poster',
      preload: 'preload',
      profile: 'profile',
      radiogroup: 'radioGroup',
      readonly: 'readOnly',
      referrerpolicy: 'referrerPolicy',
      rel: 'rel',
      required: 'required',
      reversed: 'reversed',
      role: 'role',
      rows: 'rows',
      rowspan: 'rowSpan',
      sandbox: 'sandbox',
      scope: 'scope',
      scoped: 'scoped',
      scrolling: 'scrolling',
      seamless: 'seamless',
      selected: 'selected',
      shape: 'shape',
      size: 'size',
      sizes: 'sizes',
      span: 'span',
      spellcheck: 'spellCheck',
      src: 'src',
      srcdoc: 'srcDoc',
      srclang: 'srcLang',
      srcset: 'srcSet',
      start: 'start',
      step: 'step',
      style: 'style',
      summary: 'summary',
      tabindex: 'tabIndex',
      target: 'target',
      title: 'title',
      type: 'type',
      usemap: 'useMap',
      value: 'value',
      width: 'width',
      wmode: 'wmode',
      wrap: 'wrap',
      // SVG
      about: 'about',
      accentheight: 'accentHeight',
      'accent-height': 'accentHeight',
      accumulate: 'accumulate',
      additive: 'additive',
      alignmentbaseline: 'alignmentBaseline',
      'alignment-baseline': 'alignmentBaseline',
      allowreorder: 'allowReorder',
      alphabetic: 'alphabetic',
      amplitude: 'amplitude',
      arabicform: 'arabicForm',
      'arabic-form': 'arabicForm',
      ascent: 'ascent',
      attributename: 'attributeName',
      attributetype: 'attributeType',
      autoreverse: 'autoReverse',
      azimuth: 'azimuth',
      basefrequency: 'baseFrequency',
      baselineshift: 'baselineShift',
      'baseline-shift': 'baselineShift',
      baseprofile: 'baseProfile',
      bbox: 'bbox',
      begin: 'begin',
      bias: 'bias',
      by: 'by',
      calcmode: 'calcMode',
      capheight: 'capHeight',
      'cap-height': 'capHeight',
      clip: 'clip',
      clippath: 'clipPath',
      'clip-path': 'clipPath',
      clippathunits: 'clipPathUnits',
      cliprule: 'clipRule',
      'clip-rule': 'clipRule',
      color: 'color',
      colorinterpolation: 'colorInterpolation',
      'color-interpolation': 'colorInterpolation',
      colorinterpolationfilters: 'colorInterpolationFilters',
      'color-interpolation-filters': 'colorInterpolationFilters',
      colorprofile: 'colorProfile',
      'color-profile': 'colorProfile',
      colorrendering: 'colorRendering',
      'color-rendering': 'colorRendering',
      contentscripttype: 'contentScriptType',
      contentstyletype: 'contentStyleType',
      cursor: 'cursor',
      cx: 'cx',
      cy: 'cy',
      d: 'd',
      datatype: 'datatype',
      decelerate: 'decelerate',
      descent: 'descent',
      diffuseconstant: 'diffuseConstant',
      direction: 'direction',
      display: 'display',
      divisor: 'divisor',
      dominantbaseline: 'dominantBaseline',
      'dominant-baseline': 'dominantBaseline',
      dur: 'dur',
      dx: 'dx',
      dy: 'dy',
      edgemode: 'edgeMode',
      elevation: 'elevation',
      enablebackground: 'enableBackground',
      'enable-background': 'enableBackground',
      end: 'end',
      exponent: 'exponent',
      externalresourcesrequired: 'externalResourcesRequired',
      fill: 'fill',
      fillopacity: 'fillOpacity',
      'fill-opacity': 'fillOpacity',
      fillrule: 'fillRule',
      'fill-rule': 'fillRule',
      filter: 'filter',
      filterres: 'filterRes',
      filterunits: 'filterUnits',
      floodopacity: 'floodOpacity',
      'flood-opacity': 'floodOpacity',
      floodcolor: 'floodColor',
      'flood-color': 'floodColor',
      focusable: 'focusable',
      fontfamily: 'fontFamily',
      'font-family': 'fontFamily',
      fontsize: 'fontSize',
      'font-size': 'fontSize',
      fontsizeadjust: 'fontSizeAdjust',
      'font-size-adjust': 'fontSizeAdjust',
      fontstretch: 'fontStretch',
      'font-stretch': 'fontStretch',
      fontstyle: 'fontStyle',
      'font-style': 'fontStyle',
      fontvariant: 'fontVariant',
      'font-variant': 'fontVariant',
      fontweight: 'fontWeight',
      'font-weight': 'fontWeight',
      format: 'format',
      from: 'from',
      fx: 'fx',
      fy: 'fy',
      g1: 'g1',
      g2: 'g2',
      glyphname: 'glyphName',
      'glyph-name': 'glyphName',
      glyphorientationhorizontal: 'glyphOrientationHorizontal',
      'glyph-orientation-horizontal': 'glyphOrientationHorizontal',
      glyphorientationvertical: 'glyphOrientationVertical',
      'glyph-orientation-vertical': 'glyphOrientationVertical',
      glyphref: 'glyphRef',
      gradienttransform: 'gradientTransform',
      gradientunits: 'gradientUnits',
      hanging: 'hanging',
      horizadvx: 'horizAdvX',
      'horiz-adv-x': 'horizAdvX',
      horizoriginx: 'horizOriginX',
      'horiz-origin-x': 'horizOriginX',
      ideographic: 'ideographic',
      imagerendering: 'imageRendering',
      'image-rendering': 'imageRendering',
      in2: 'in2',
      in: 'in',
      inlist: 'inlist',
      intercept: 'intercept',
      k1: 'k1',
      k2: 'k2',
      k3: 'k3',
      k4: 'k4',
      k: 'k',
      kernelmatrix: 'kernelMatrix',
      kernelunitlength: 'kernelUnitLength',
      kerning: 'kerning',
      keypoints: 'keyPoints',
      keysplines: 'keySplines',
      keytimes: 'keyTimes',
      lengthadjust: 'lengthAdjust',
      letterspacing: 'letterSpacing',
      'letter-spacing': 'letterSpacing',
      lightingcolor: 'lightingColor',
      'lighting-color': 'lightingColor',
      limitingconeangle: 'limitingConeAngle',
      local: 'local',
      markerend: 'markerEnd',
      'marker-end': 'markerEnd',
      markerheight: 'markerHeight',
      markermid: 'markerMid',
      'marker-mid': 'markerMid',
      markerstart: 'markerStart',
      'marker-start': 'markerStart',
      markerunits: 'markerUnits',
      markerwidth: 'markerWidth',
      mask: 'mask',
      maskcontentunits: 'maskContentUnits',
      maskunits: 'maskUnits',
      mathematical: 'mathematical',
      mode: 'mode',
      numoctaves: 'numOctaves',
      offset: 'offset',
      opacity: 'opacity',
      operator: 'operator',
      order: 'order',
      orient: 'orient',
      orientation: 'orientation',
      origin: 'origin',
      overflow: 'overflow',
      overlineposition: 'overlinePosition',
      'overline-position': 'overlinePosition',
      overlinethickness: 'overlineThickness',
      'overline-thickness': 'overlineThickness',
      paintorder: 'paintOrder',
      'paint-order': 'paintOrder',
      panose1: 'panose1',
      'panose-1': 'panose1',
      pathlength: 'pathLength',
      patterncontentunits: 'patternContentUnits',
      patterntransform: 'patternTransform',
      patternunits: 'patternUnits',
      pointerevents: 'pointerEvents',
      'pointer-events': 'pointerEvents',
      points: 'points',
      pointsatx: 'pointsAtX',
      pointsaty: 'pointsAtY',
      pointsatz: 'pointsAtZ',
      prefix: 'prefix',
      preservealpha: 'preserveAlpha',
      preserveaspectratio: 'preserveAspectRatio',
      primitiveunits: 'primitiveUnits',
      property: 'property',
      r: 'r',
      radius: 'radius',
      refx: 'refX',
      refy: 'refY',
      renderingintent: 'renderingIntent',
      'rendering-intent': 'renderingIntent',
      repeatcount: 'repeatCount',
      repeatdur: 'repeatDur',
      requiredextensions: 'requiredExtensions',
      requiredfeatures: 'requiredFeatures',
      resource: 'resource',
      restart: 'restart',
      result: 'result',
      results: 'results',
      rotate: 'rotate',
      rx: 'rx',
      ry: 'ry',
      scale: 'scale',
      security: 'security',
      seed: 'seed',
      shaperendering: 'shapeRendering',
      'shape-rendering': 'shapeRendering',
      slope: 'slope',
      spacing: 'spacing',
      specularconstant: 'specularConstant',
      specularexponent: 'specularExponent',
      speed: 'speed',
      spreadmethod: 'spreadMethod',
      startoffset: 'startOffset',
      stddeviation: 'stdDeviation',
      stemh: 'stemh',
      stemv: 'stemv',
      stitchtiles: 'stitchTiles',
      stopcolor: 'stopColor',
      'stop-color': 'stopColor',
      stopopacity: 'stopOpacity',
      'stop-opacity': 'stopOpacity',
      strikethroughposition: 'strikethroughPosition',
      'strikethrough-position': 'strikethroughPosition',
      strikethroughthickness: 'strikethroughThickness',
      'strikethrough-thickness': 'strikethroughThickness',
      string: 'string',
      stroke: 'stroke',
      strokedasharray: 'strokeDasharray',
      'stroke-dasharray': 'strokeDasharray',
      strokedashoffset: 'strokeDashoffset',
      'stroke-dashoffset': 'strokeDashoffset',
      strokelinecap: 'strokeLinecap',
      'stroke-linecap': 'strokeLinecap',
      strokelinejoin: 'strokeLinejoin',
      'stroke-linejoin': 'strokeLinejoin',
      strokemiterlimit: 'strokeMiterlimit',
      'stroke-miterlimit': 'strokeMiterlimit',
      strokewidth: 'strokeWidth',
      'stroke-width': 'strokeWidth',
      strokeopacity: 'strokeOpacity',
      'stroke-opacity': 'strokeOpacity',
      suppresscontenteditablewarning: 'suppressContentEditableWarning',
      suppresshydrationwarning: 'suppressHydrationWarning',
      surfacescale: 'surfaceScale',
      systemlanguage: 'systemLanguage',
      tablevalues: 'tableValues',
      targetx: 'targetX',
      targety: 'targetY',
      textanchor: 'textAnchor',
      'text-anchor': 'textAnchor',
      textdecoration: 'textDecoration',
      'text-decoration': 'textDecoration',
      textlength: 'textLength',
      textrendering: 'textRendering',
      'text-rendering': 'textRendering',
      to: 'to',
      transform: 'transform',
      typeof: 'typeof',
      u1: 'u1',
      u2: 'u2',
      underlineposition: 'underlinePosition',
      'underline-position': 'underlinePosition',
      underlinethickness: 'underlineThickness',
      'underline-thickness': 'underlineThickness',
      unicode: 'unicode',
      unicodebidi: 'unicodeBidi',
      'unicode-bidi': 'unicodeBidi',
      unicoderange: 'unicodeRange',
      'unicode-range': 'unicodeRange',
      unitsperem: 'unitsPerEm',
      'units-per-em': 'unitsPerEm',
      unselectable: 'unselectable',
      valphabetic: 'vAlphabetic',
      'v-alphabetic': 'vAlphabetic',
      values: 'values',
      vectoreffect: 'vectorEffect',
      'vector-effect': 'vectorEffect',
      version: 'version',
      vertadvy: 'vertAdvY',
      'vert-adv-y': 'vertAdvY',
      vertoriginx: 'vertOriginX',
      'vert-origin-x': 'vertOriginX',
      vertoriginy: 'vertOriginY',
      'vert-origin-y': 'vertOriginY',
      vhanging: 'vHanging',
      'v-hanging': 'vHanging',
      videographic: 'vIdeographic',
      'v-ideographic': 'vIdeographic',
      viewbox: 'viewBox',
      viewtarget: 'viewTarget',
      visibility: 'visibility',
      vmathematical: 'vMathematical',
      'v-mathematical': 'vMathematical',
      vocab: 'vocab',
      widths: 'widths',
      wordspacing: 'wordSpacing',
      'word-spacing': 'wordSpacing',
      writingmode: 'writingMode',
      'writing-mode': 'writingMode',
      x1: 'x1',
      x2: 'x2',
      x: 'x',
      xchannelselector: 'xChannelSelector',
      xheight: 'xHeight',
      'x-height': 'xHeight',
      xlinkactuate: 'xlinkActuate',
      'xlink:actuate': 'xlinkActuate',
      xlinkarcrole: 'xlinkArcrole',
      'xlink:arcrole': 'xlinkArcrole',
      xlinkhref: 'xlinkHref',
      'xlink:href': 'xlinkHref',
      xlinkrole: 'xlinkRole',
      'xlink:role': 'xlinkRole',
      xlinkshow: 'xlinkShow',
      'xlink:show': 'xlinkShow',
      xlinktitle: 'xlinkTitle',
      'xlink:title': 'xlinkTitle',
      xlinktype: 'xlinkType',
      'xlink:type': 'xlinkType',
      xmlbase: 'xmlBase',
      'xml:base': 'xmlBase',
      xmllang: 'xmlLang',
      'xml:lang': 'xmlLang',
      xmlns: 'xmlns',
      'xml:space': 'xmlSpace',
      xmlnsxlink: 'xmlnsXlink',
      'xmlns:xlink': 'xmlnsXlink',
      xmlspace: 'xmlSpace',
      y1: 'y1',
      y2: 'y2',
      y: 'y',
      ychannelselector: 'yChannelSelector',
      z: 'z',
      zoomandpan: 'zoomAndPan'
    };
    var ariaProperties = {
      'aria-current': 0,
      // state
      'aria-details': 0,
      'aria-disabled': 0,
      // state
      'aria-hidden': 0,
      // state
      'aria-invalid': 0,
      // state
      'aria-keyshortcuts': 0,
      'aria-label': 0,
      'aria-roledescription': 0,
      // Widget Attributes
      'aria-autocomplete': 0,
      'aria-checked': 0,
      'aria-expanded': 0,
      'aria-haspopup': 0,
      'aria-level': 0,
      'aria-modal': 0,
      'aria-multiline': 0,
      'aria-multiselectable': 0,
      'aria-orientation': 0,
      'aria-placeholder': 0,
      'aria-pressed': 0,
      'aria-readonly': 0,
      'aria-required': 0,
      'aria-selected': 0,
      'aria-sort': 0,
      'aria-valuemax': 0,
      'aria-valuemin': 0,
      'aria-valuenow': 0,
      'aria-valuetext': 0,
      // Live Region Attributes
      'aria-atomic': 0,
      'aria-busy': 0,
      'aria-live': 0,
      'aria-relevant': 0,
      // Drag-and-Drop Attributes
      'aria-dropeffect': 0,
      'aria-grabbed': 0,
      // Relationship Attributes
      'aria-activedescendant': 0,
      'aria-colcount': 0,
      'aria-colindex': 0,
      'aria-colspan': 0,
      'aria-controls': 0,
      'aria-describedby': 0,
      'aria-errormessage': 0,
      'aria-flowto': 0,
      'aria-labelledby': 0,
      'aria-owns': 0,
      'aria-posinset': 0,
      'aria-rowcount': 0,
      'aria-rowindex': 0,
      'aria-rowspan': 0,
      'aria-setsize': 0
    };
    var warnedProperties = {};
    var rARIA = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
    var rARIACamel = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');
    var hasOwnProperty$1 = Object.prototype.hasOwnProperty;

    function validateProperty(tagName, name) {
      {
        if (hasOwnProperty$1.call(warnedProperties, name) && warnedProperties[name]) {
          return true;
        }

        if (rARIACamel.test(name)) {
          var ariaName = 'aria-' + name.slice(4).toLowerCase();
          var correctName = ariaProperties.hasOwnProperty(ariaName) ? ariaName : null; // If this is an aria-* attribute, but is not listed in the known DOM
          // DOM properties, then it is an invalid aria-* attribute.

          if (correctName == null) {
            error('Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.', name);
            warnedProperties[name] = true;
            return true;
          } // aria-* attributes should be lowercase; suggest the lowercase version.


          if (name !== correctName) {
            error('Invalid ARIA attribute `%s`. Did you mean `%s`?', name, correctName);
            warnedProperties[name] = true;
            return true;
          }
        }

        if (rARIA.test(name)) {
          var lowerCasedName = name.toLowerCase();
          var standardName = ariaProperties.hasOwnProperty(lowerCasedName) ? lowerCasedName : null; // If this is an aria-* attribute, but is not listed in the known DOM
          // DOM properties, then it is an invalid aria-* attribute.

          if (standardName == null) {
            warnedProperties[name] = true;
            return false;
          } // aria-* attributes should be lowercase; suggest the lowercase version.


          if (name !== standardName) {
            error('Unknown ARIA attribute `%s`. Did you mean `%s`?', name, standardName);
            warnedProperties[name] = true;
            return true;
          }
        }
      }
      return true;
    }

    function warnInvalidARIAProps(type, props) {
      {
        var invalidProps = [];

        for (var key in props) {
          var isValid = validateProperty(type, key);

          if (!isValid) {
            invalidProps.push(key);
          }
        }

        var unknownPropString = invalidProps.map(function (prop) {
          return '`' + prop + '`';
        }).join(', ');

        if (invalidProps.length === 1) {
          error('Invalid aria prop %s on <%s> tag. ' + 'For details, see https://fb.me/invalid-aria-prop', unknownPropString, type);
        } else if (invalidProps.length > 1) {
          error('Invalid aria props %s on <%s> tag. ' + 'For details, see https://fb.me/invalid-aria-prop', unknownPropString, type);
        }
      }
    }

    function validateProperties(type, props) {
      if (isCustomComponent(type, props)) {
        return;
      }

      warnInvalidARIAProps(type, props);
    }

    var didWarnValueNull = false;

    function validateProperties$1(type, props) {
      {
        if (type !== 'input' && type !== 'textarea' && type !== 'select') {
          return;
        }

        if (props != null && props.value === null && !didWarnValueNull) {
          didWarnValueNull = true;

          if (type === 'select' && props.multiple) {
            error('`value` prop on `%s` should not be null. ' + 'Consider using an empty array when `multiple` is set to `true` ' + 'to clear the component or `undefined` for uncontrolled components.', type);
          } else {
            error('`value` prop on `%s` should not be null. ' + 'Consider using an empty string to clear the component or `undefined` ' + 'for uncontrolled components.', type);
          }
        }
      }
    }

    var validateProperty$1 = function () {};

    {
      var warnedProperties$1 = {};
      var _hasOwnProperty = Object.prototype.hasOwnProperty;
      var EVENT_NAME_REGEX = /^on./;
      var INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/;
      var rARIA$1 = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
      var rARIACamel$1 = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');

      validateProperty$1 = function (tagName, name, value, canUseEventSystem) {
        if (_hasOwnProperty.call(warnedProperties$1, name) && warnedProperties$1[name]) {
          return true;
        }

        var lowerCasedName = name.toLowerCase();

        if (lowerCasedName === 'onfocusin' || lowerCasedName === 'onfocusout') {
          error('React uses onFocus and onBlur instead of onFocusIn and onFocusOut. ' + 'All React events are normalized to bubble, so onFocusIn and onFocusOut ' + 'are not needed/supported by React.');
          warnedProperties$1[name] = true;
          return true;
        } // We can't rely on the event system being injected on the server.


        if (canUseEventSystem) {
          if (registrationNameModules.hasOwnProperty(name)) {
            return true;
          }

          var registrationName = possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? possibleRegistrationNames[lowerCasedName] : null;

          if (registrationName != null) {
            error('Invalid event handler property `%s`. Did you mean `%s`?', name, registrationName);
            warnedProperties$1[name] = true;
            return true;
          }

          if (EVENT_NAME_REGEX.test(name)) {
            error('Unknown event handler property `%s`. It will be ignored.', name);
            warnedProperties$1[name] = true;
            return true;
          }
        } else if (EVENT_NAME_REGEX.test(name)) {
          // If no event plugins have been injected, we are in a server environment.
          // So we can't tell if the event name is correct for sure, but we can filter
          // out known bad ones like `onclick`. We can't suggest a specific replacement though.
          if (INVALID_EVENT_NAME_REGEX.test(name)) {
            error('Invalid event handler property `%s`. ' + 'React events use the camelCase naming convention, for example `onClick`.', name);
          }

          warnedProperties$1[name] = true;
          return true;
        } // Let the ARIA attribute hook validate ARIA attributes


        if (rARIA$1.test(name) || rARIACamel$1.test(name)) {
          return true;
        }

        if (lowerCasedName === 'innerhtml') {
          error('Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.');
          warnedProperties$1[name] = true;
          return true;
        }

        if (lowerCasedName === 'aria') {
          error('The `aria` attribute is reserved for future use in React. ' + 'Pass individual `aria-` attributes instead.');
          warnedProperties$1[name] = true;
          return true;
        }

        if (lowerCasedName === 'is' && value !== null && value !== undefined && typeof value !== 'string') {
          error('Received a `%s` for a string attribute `is`. If this is expected, cast ' + 'the value to a string.', typeof value);
          warnedProperties$1[name] = true;
          return true;
        }

        if (typeof value === 'number' && isNaN(value)) {
          error('Received NaN for the `%s` attribute. If this is expected, cast ' + 'the value to a string.', name);
          warnedProperties$1[name] = true;
          return true;
        }

        var propertyInfo = getPropertyInfo(name);
        var isReserved = propertyInfo !== null && propertyInfo.type === RESERVED; // Known attributes should match the casing specified in the property config.

        if (possibleStandardNames.hasOwnProperty(lowerCasedName)) {
          var standardName = possibleStandardNames[lowerCasedName];

          if (standardName !== name) {
            error('Invalid DOM property `%s`. Did you mean `%s`?', name, standardName);
            warnedProperties$1[name] = true;
            return true;
          }
        } else if (!isReserved && name !== lowerCasedName) {
          // Unknown attributes should have lowercase casing since that's how they
          // will be cased anyway with server rendering.
          error('React does not recognize the `%s` prop on a DOM element. If you ' + 'intentionally want it to appear in the DOM as a custom ' + 'attribute, spell it as lowercase `%s` instead. ' + 'If you accidentally passed it from a parent component, remove ' + 'it from the DOM element.', name, lowerCasedName);
          warnedProperties$1[name] = true;
          return true;
        }

        if (typeof value === 'boolean' && shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
          if (value) {
            error('Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.', value, name, name, value, name);
          } else {
            error('Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.\n\n' + 'If you used to conditionally omit it with %s={condition && value}, ' + 'pass %s={condition ? value : undefined} instead.', value, name, name, value, name, name, name);
          }

          warnedProperties$1[name] = true;
          return true;
        } // Now that we've validated casing, do not validate
        // data types for reserved props


        if (isReserved) {
          return true;
        } // Warn when a known attribute is a bad type


        if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
          warnedProperties$1[name] = true;
          return false;
        } // Warn when passing the strings 'false' or 'true' into a boolean prop


        if ((value === 'false' || value === 'true') && propertyInfo !== null && propertyInfo.type === BOOLEAN) {
          error('Received the string `%s` for the boolean attribute `%s`. ' + '%s ' + 'Did you mean %s={%s}?', value, name, value === 'false' ? 'The browser will interpret it as a truthy value.' : 'Although this works, it will not work as expected if you pass the string "false".', name, value);
          warnedProperties$1[name] = true;
          return true;
        }

        return true;
      };
    }

    var warnUnknownProperties = function (type, props, canUseEventSystem) {
      {
        var unknownProps = [];

        for (var key in props) {
          var isValid = validateProperty$1(type, key, props[key], canUseEventSystem);

          if (!isValid) {
            unknownProps.push(key);
          }
        }

        var unknownPropString = unknownProps.map(function (prop) {
          return '`' + prop + '`';
        }).join(', ');

        if (unknownProps.length === 1) {
          error('Invalid value for prop %s on <%s> tag. Either remove it from the element, ' + 'or pass a string or number value to keep it in the DOM. ' + 'For details, see https://fb.me/react-attribute-behavior', unknownPropString, type);
        } else if (unknownProps.length > 1) {
          error('Invalid values for props %s on <%s> tag. Either remove them from the element, ' + 'or pass a string or number value to keep them in the DOM. ' + 'For details, see https://fb.me/react-attribute-behavior', unknownPropString, type);
        }
      }
    };

    function validateProperties$2(type, props, canUseEventSystem) {
      if (isCustomComponent(type, props)) {
        return;
      }

      warnUnknownProperties(type, props, canUseEventSystem);
    }

    var didWarnInvalidHydration = false;
    var DANGEROUSLY_SET_INNER_HTML = 'dangerouslySetInnerHTML';
    var SUPPRESS_CONTENT_EDITABLE_WARNING = 'suppressContentEditableWarning';
    var SUPPRESS_HYDRATION_WARNING = 'suppressHydrationWarning';
    var AUTOFOCUS = 'autoFocus';
    var CHILDREN = 'children';
    var STYLE = 'style';
    var HTML$1 = '__html';
    var HTML_NAMESPACE$1 = Namespaces.html;
    var warnedUnknownTags;
    var suppressHydrationWarning;
    var validatePropertiesInDevelopment;
    var warnForTextDifference;
    var warnForPropDifference;
    var warnForExtraAttributes;
    var warnForInvalidEventListener;
    var canDiffStyleForHydrationWarning;
    var normalizeMarkupForTextOrAttribute;
    var normalizeHTML;
    {
      warnedUnknownTags = {
        // Chrome is the only major browser not shipping <time>. But as of July
        // 2017 it intends to ship it due to widespread usage. We intentionally
        // *don't* warn for <time> even if it's unrecognized by Chrome because
        // it soon will be, and many apps have been using it anyway.
        time: true,
        // There are working polyfills for <dialog>. Let people use it.
        dialog: true,
        // Electron ships a custom <webview> tag to display external web content in
        // an isolated frame and process.
        // This tag is not present in non Electron environments such as JSDom which
        // is often used for testing purposes.
        // @see https://electronjs.org/docs/api/webview-tag
        webview: true
      };

      validatePropertiesInDevelopment = function (type, props) {
        validateProperties(type, props);
        validateProperties$1(type, props);
        validateProperties$2(type, props,
        /* canUseEventSystem */
        true);
      }; // IE 11 parses & normalizes the style attribute as opposed to other
      // browsers. It adds spaces and sorts the properties in some
      // non-alphabetical order. Handling that would require sorting CSS
      // properties in the client & server versions or applying
      // `expectedStyle` to a temporary DOM node to read its `style` attribute
      // normalized. Since it only affects IE, we're skipping style warnings
      // in that browser completely in favor of doing all that work.
      // See https://github.com/facebook/react/issues/11807


      canDiffStyleForHydrationWarning = canUseDOM && !document.documentMode; // HTML parsing normalizes CR and CRLF to LF.
      // It also can turn \u0000 into \uFFFD inside attributes.
      // https://www.w3.org/TR/html5/single-page.html#preprocessing-the-input-stream
      // If we have a mismatch, it might be caused by that.
      // We will still patch up in this case but not fire the warning.

      var NORMALIZE_NEWLINES_REGEX = /\r\n?/g;
      var NORMALIZE_NULL_AND_REPLACEMENT_REGEX = /\u0000|\uFFFD/g;

      normalizeMarkupForTextOrAttribute = function (markup) {
        var markupString = typeof markup === 'string' ? markup : '' + markup;
        return markupString.replace(NORMALIZE_NEWLINES_REGEX, '\n').replace(NORMALIZE_NULL_AND_REPLACEMENT_REGEX, '');
      };

      warnForTextDifference = function (serverText, clientText) {
        if (didWarnInvalidHydration) {
          return;
        }

        var normalizedClientText = normalizeMarkupForTextOrAttribute(clientText);
        var normalizedServerText = normalizeMarkupForTextOrAttribute(serverText);

        if (normalizedServerText === normalizedClientText) {
          return;
        }

        didWarnInvalidHydration = true;
        error('Text content did not match. Server: "%s" Client: "%s"', normalizedServerText, normalizedClientText);
      };

      warnForPropDifference = function (propName, serverValue, clientValue) {
        if (didWarnInvalidHydration) {
          return;
        }

        var normalizedClientValue = normalizeMarkupForTextOrAttribute(clientValue);
        var normalizedServerValue = normalizeMarkupForTextOrAttribute(serverValue);

        if (normalizedServerValue === normalizedClientValue) {
          return;
        }

        didWarnInvalidHydration = true;
        error('Prop `%s` did not match. Server: %s Client: %s', propName, JSON.stringify(normalizedServerValue), JSON.stringify(normalizedClientValue));
      };

      warnForExtraAttributes = function (attributeNames) {
        if (didWarnInvalidHydration) {
          return;
        }

        didWarnInvalidHydration = true;
        var names = [];
        attributeNames.forEach(function (name) {
          names.push(name);
        });
        error('Extra attributes from the server: %s', names);
      };

      warnForInvalidEventListener = function (registrationName, listener) {
        if (listener === false) {
          error('Expected `%s` listener to be a function, instead got `false`.\n\n' + 'If you used to conditionally omit it with %s={condition && value}, ' + 'pass %s={condition ? value : undefined} instead.', registrationName, registrationName, registrationName);
        } else {
          error('Expected `%s` listener to be a function, instead got a value of `%s` type.', registrationName, typeof listener);
        }
      }; // Parse the HTML and read it back to normalize the HTML string so that it
      // can be used for comparison.


      normalizeHTML = function (parent, html) {
        // We could have created a separate document here to avoid
        // re-initializing custom elements if they exist. But this breaks
        // how <noscript> is being handled. So we use the same document.
        // See the discussion in https://github.com/facebook/react/pull/11157.
        var testElement = parent.namespaceURI === HTML_NAMESPACE$1 ? parent.ownerDocument.createElement(parent.tagName) : parent.ownerDocument.createElementNS(parent.namespaceURI, parent.tagName);
        testElement.innerHTML = html;
        return testElement.innerHTML;
      };
    }

    function ensureListeningTo(rootContainerElement, registrationName) {
      var isDocumentOrFragment = rootContainerElement.nodeType === DOCUMENT_NODE || rootContainerElement.nodeType === DOCUMENT_FRAGMENT_NODE;
      var doc = isDocumentOrFragment ? rootContainerElement : rootContainerElement.ownerDocument;
      legacyListenToEvent(registrationName, doc);
    }

    function getOwnerDocumentFromRootContainer(rootContainerElement) {
      return rootContainerElement.nodeType === DOCUMENT_NODE ? rootContainerElement : rootContainerElement.ownerDocument;
    }

    function noop() {}

    function trapClickOnNonInteractiveElement(node) {
      // Mobile Safari does not fire properly bubble click events on
      // non-interactive elements, which means delegated click listeners do not
      // fire. The workaround for this bug involves attaching an empty click
      // listener on the target node.
      // http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
      // Just set it using the onclick property so that we don't have to manage any
      // bookkeeping for it. Not sure if we need to clear it when the listener is
      // removed.
      // TODO: Only do this for the relevant Safaris maybe?
      node.onclick = noop;
    }

    function setInitialDOMProperties(tag, domElement, rootContainerElement, nextProps, isCustomComponentTag) {
      for (var propKey in nextProps) {
        if (!nextProps.hasOwnProperty(propKey)) {
          continue;
        }

        var nextProp = nextProps[propKey];

        if (propKey === STYLE) {
          {
            if (nextProp) {
              // Freeze the next style object so that we can assume it won't be
              // mutated. We have already warned for this in the past.
              Object.freeze(nextProp);
            }
          } // Relies on `updateStylesByID` not mutating `styleUpdates`.

          setValueForStyles(domElement, nextProp);
        } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
          var nextHtml = nextProp ? nextProp[HTML$1] : undefined;

          if (nextHtml != null) {
            setInnerHTML(domElement, nextHtml);
          }
        } else if (propKey === CHILDREN) {
          if (typeof nextProp === 'string') {
            // Avoid setting initial textContent when the text is empty. In IE11 setting
            // textContent on a <textarea> will cause the placeholder to not
            // show within the <textarea> until it has been focused and blurred again.
            // https://github.com/facebook/react/issues/6731#issuecomment-254874553
            var canSetTextContent = tag !== 'textarea' || nextProp !== '';

            if (canSetTextContent) {
              setTextContent(domElement, nextProp);
            }
          } else if (typeof nextProp === 'number') {
            setTextContent(domElement, '' + nextProp);
          }
        } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING) ;else if (propKey === AUTOFOCUS) ;else if (registrationNameModules.hasOwnProperty(propKey)) {
          if (nextProp != null) {
            if (typeof nextProp !== 'function') {
              warnForInvalidEventListener(propKey, nextProp);
            }

            ensureListeningTo(rootContainerElement, propKey);
          }
        } else if (nextProp != null) {
          setValueForProperty(domElement, propKey, nextProp, isCustomComponentTag);
        }
      }
    }

    function updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag) {
      // TODO: Handle wasCustomComponentTag
      for (var i = 0; i < updatePayload.length; i += 2) {
        var propKey = updatePayload[i];
        var propValue = updatePayload[i + 1];

        if (propKey === STYLE) {
          setValueForStyles(domElement, propValue);
        } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
          setInnerHTML(domElement, propValue);
        } else if (propKey === CHILDREN) {
          setTextContent(domElement, propValue);
        } else {
          setValueForProperty(domElement, propKey, propValue, isCustomComponentTag);
        }
      }
    }

    function createElement(type, props, rootContainerElement, parentNamespace) {
      var isCustomComponentTag; // We create tags in the namespace of their parent container, except HTML
      // tags get no namespace.

      var ownerDocument = getOwnerDocumentFromRootContainer(rootContainerElement);
      var domElement;
      var namespaceURI = parentNamespace;

      if (namespaceURI === HTML_NAMESPACE$1) {
        namespaceURI = getIntrinsicNamespace(type);
      }

      if (namespaceURI === HTML_NAMESPACE$1) {
        {
          isCustomComponentTag = isCustomComponent(type, props); // Should this check be gated by parent namespace? Not sure we want to
          // allow <SVG> or <mATH>.

          if (!isCustomComponentTag && type !== type.toLowerCase()) {
            error('<%s /> is using incorrect casing. ' + 'Use PascalCase for React components, ' + 'or lowercase for HTML elements.', type);
          }
        }

        if (type === 'script') {
          // Create the script via .innerHTML so its "parser-inserted" flag is
          // set to true and it does not execute
          var div = ownerDocument.createElement('div');
          div.innerHTML = '<script><' + '/script>'; // eslint-disable-line
          // This is guaranteed to yield a script element.

          var firstChild = div.firstChild;
          domElement = div.removeChild(firstChild);
        } else if (typeof props.is === 'string') {
          // $FlowIssue `createElement` should be updated for Web Components
          domElement = ownerDocument.createElement(type, {
            is: props.is
          });
        } else {
          // Separate else branch instead of using `props.is || undefined` above because of a Firefox bug.
          // See discussion in https://github.com/facebook/react/pull/6896
          // and discussion in https://bugzilla.mozilla.org/show_bug.cgi?id=1276240
          domElement = ownerDocument.createElement(type); // Normally attributes are assigned in `setInitialDOMProperties`, however the `multiple` and `size`
          // attributes on `select`s needs to be added before `option`s are inserted.
          // This prevents:
          // - a bug where the `select` does not scroll to the correct option because singular
          //  `select` elements automatically pick the first item #13222
          // - a bug where the `select` set the first item as selected despite the `size` attribute #14239
          // See https://github.com/facebook/react/issues/13222
          // and https://github.com/facebook/react/issues/14239

          if (type === 'select') {
            var node = domElement;

            if (props.multiple) {
              node.multiple = true;
            } else if (props.size) {
              // Setting a size greater than 1 causes a select to behave like `multiple=true`, where
              // it is possible that no option is selected.
              //
              // This is only necessary when a select in "single selection mode".
              node.size = props.size;
            }
          }
        }
      } else {
        domElement = ownerDocument.createElementNS(namespaceURI, type);
      }

      {
        if (namespaceURI === HTML_NAMESPACE$1) {
          if (!isCustomComponentTag && Object.prototype.toString.call(domElement) === '[object HTMLUnknownElement]' && !Object.prototype.hasOwnProperty.call(warnedUnknownTags, type)) {
            warnedUnknownTags[type] = true;
            error('The tag <%s> is unrecognized in this browser. ' + 'If you meant to render a React component, start its name with ' + 'an uppercase letter.', type);
          }
        }
      }
      return domElement;
    }

    function createTextNode(text, rootContainerElement) {
      return getOwnerDocumentFromRootContainer(rootContainerElement).createTextNode(text);
    }

    function setInitialProperties(domElement, tag, rawProps, rootContainerElement) {
      var isCustomComponentTag = isCustomComponent(tag, rawProps);
      {
        validatePropertiesInDevelopment(tag, rawProps);
      } // TODO: Make sure that we check isMounted before firing any of these events.

      var props;

      switch (tag) {
        case 'iframe':
        case 'object':
        case 'embed':
          trapBubbledEvent(TOP_LOAD, domElement);
          props = rawProps;
          break;

        case 'video':
        case 'audio':
          // Create listener for each media event
          for (var i = 0; i < mediaEventTypes.length; i++) {
            trapBubbledEvent(mediaEventTypes[i], domElement);
          }

          props = rawProps;
          break;

        case 'source':
          trapBubbledEvent(TOP_ERROR, domElement);
          props = rawProps;
          break;

        case 'img':
        case 'image':
        case 'link':
          trapBubbledEvent(TOP_ERROR, domElement);
          trapBubbledEvent(TOP_LOAD, domElement);
          props = rawProps;
          break;

        case 'form':
          trapBubbledEvent(TOP_RESET, domElement);
          trapBubbledEvent(TOP_SUBMIT, domElement);
          props = rawProps;
          break;

        case 'details':
          trapBubbledEvent(TOP_TOGGLE, domElement);
          props = rawProps;
          break;

        case 'input':
          initWrapperState(domElement, rawProps);
          props = getHostProps(domElement, rawProps);
          trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening
          // to onChange. Even if there is no listener.

          ensureListeningTo(rootContainerElement, 'onChange');
          break;

        case 'option':
          validateProps(domElement, rawProps);
          props = getHostProps$1(domElement, rawProps);
          break;

        case 'select':
          initWrapperState$1(domElement, rawProps);
          props = getHostProps$2(domElement, rawProps);
          trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening
          // to onChange. Even if there is no listener.

          ensureListeningTo(rootContainerElement, 'onChange');
          break;

        case 'textarea':
          initWrapperState$2(domElement, rawProps);
          props = getHostProps$3(domElement, rawProps);
          trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening
          // to onChange. Even if there is no listener.

          ensureListeningTo(rootContainerElement, 'onChange');
          break;

        default:
          props = rawProps;
      }

      assertValidProps(tag, props);
      setInitialDOMProperties(tag, domElement, rootContainerElement, props, isCustomComponentTag);

      switch (tag) {
        case 'input':
          // TODO: Make sure we check if this is still unmounted or do any clean
          // up necessary since we never stop tracking anymore.
          track(domElement);
          postMountWrapper(domElement, rawProps, false);
          break;

        case 'textarea':
          // TODO: Make sure we check if this is still unmounted or do any clean
          // up necessary since we never stop tracking anymore.
          track(domElement);
          postMountWrapper$3(domElement);
          break;

        case 'option':
          postMountWrapper$1(domElement, rawProps);
          break;

        case 'select':
          postMountWrapper$2(domElement, rawProps);
          break;

        default:
          if (typeof props.onClick === 'function') {
            // TODO: This cast may not be sound for SVG, MathML or custom elements.
            trapClickOnNonInteractiveElement(domElement);
          }

          break;
      }
    } // Calculate the diff between the two objects.


    function diffProperties(domElement, tag, lastRawProps, nextRawProps, rootContainerElement) {
      {
        validatePropertiesInDevelopment(tag, nextRawProps);
      }
      var updatePayload = null;
      var lastProps;
      var nextProps;

      switch (tag) {
        case 'input':
          lastProps = getHostProps(domElement, lastRawProps);
          nextProps = getHostProps(domElement, nextRawProps);
          updatePayload = [];
          break;

        case 'option':
          lastProps = getHostProps$1(domElement, lastRawProps);
          nextProps = getHostProps$1(domElement, nextRawProps);
          updatePayload = [];
          break;

        case 'select':
          lastProps = getHostProps$2(domElement, lastRawProps);
          nextProps = getHostProps$2(domElement, nextRawProps);
          updatePayload = [];
          break;

        case 'textarea':
          lastProps = getHostProps$3(domElement, lastRawProps);
          nextProps = getHostProps$3(domElement, nextRawProps);
          updatePayload = [];
          break;

        default:
          lastProps = lastRawProps;
          nextProps = nextRawProps;

          if (typeof lastProps.onClick !== 'function' && typeof nextProps.onClick === 'function') {
            // TODO: This cast may not be sound for SVG, MathML or custom elements.
            trapClickOnNonInteractiveElement(domElement);
          }

          break;
      }

      assertValidProps(tag, nextProps);
      var propKey;
      var styleName;
      var styleUpdates = null;

      for (propKey in lastProps) {
        if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey) || lastProps[propKey] == null) {
          continue;
        }

        if (propKey === STYLE) {
          var lastStyle = lastProps[propKey];

          for (styleName in lastStyle) {
            if (lastStyle.hasOwnProperty(styleName)) {
              if (!styleUpdates) {
                styleUpdates = {};
              }

              styleUpdates[styleName] = '';
            }
          }
        } else if (propKey === DANGEROUSLY_SET_INNER_HTML || propKey === CHILDREN) ;else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING) ;else if (propKey === AUTOFOCUS) ;else if (registrationNameModules.hasOwnProperty(propKey)) {
          // This is a special case. If any listener updates we need to ensure
          // that the "current" fiber pointer gets updated so we need a commit
          // to update this element.
          if (!updatePayload) {
            updatePayload = [];
          }
        } else {
          // For all other deleted properties we add it to the queue. We use
          // the whitelist in the commit phase instead.
          (updatePayload = updatePayload || []).push(propKey, null);
        }
      }

      for (propKey in nextProps) {
        var nextProp = nextProps[propKey];
        var lastProp = lastProps != null ? lastProps[propKey] : undefined;

        if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp || nextProp == null && lastProp == null) {
          continue;
        }

        if (propKey === STYLE) {
          {
            if (nextProp) {
              // Freeze the next style object so that we can assume it won't be
              // mutated. We have already warned for this in the past.
              Object.freeze(nextProp);
            }
          }

          if (lastProp) {
            // Unset styles on `lastProp` but not on `nextProp`.
            for (styleName in lastProp) {
              if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) {
                if (!styleUpdates) {
                  styleUpdates = {};
                }

                styleUpdates[styleName] = '';
              }
            } // Update styles that changed since `lastProp`.


            for (styleName in nextProp) {
              if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) {
                if (!styleUpdates) {
                  styleUpdates = {};
                }

                styleUpdates[styleName] = nextProp[styleName];
              }
            }
          } else {
            // Relies on `updateStylesByID` not mutating `styleUpdates`.
            if (!styleUpdates) {
              if (!updatePayload) {
                updatePayload = [];
              }

              updatePayload.push(propKey, styleUpdates);
            }

            styleUpdates = nextProp;
          }
        } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
          var nextHtml = nextProp ? nextProp[HTML$1] : undefined;
          var lastHtml = lastProp ? lastProp[HTML$1] : undefined;

          if (nextHtml != null) {
            if (lastHtml !== nextHtml) {
              (updatePayload = updatePayload || []).push(propKey, nextHtml);
            }
          }
        } else if (propKey === CHILDREN) {
          if (lastProp !== nextProp && (typeof nextProp === 'string' || typeof nextProp === 'number')) {
            (updatePayload = updatePayload || []).push(propKey, '' + nextProp);
          }
        } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING) ;else if (registrationNameModules.hasOwnProperty(propKey)) {
          if (nextProp != null) {
            // We eagerly listen to this even though we haven't committed yet.
            if (typeof nextProp !== 'function') {
              warnForInvalidEventListener(propKey, nextProp);
            }

            ensureListeningTo(rootContainerElement, propKey);
          }

          if (!updatePayload && lastProp !== nextProp) {
            // This is a special case. If any listener updates we need to ensure
            // that the "current" props pointer gets updated so we need a commit
            // to update this element.
            updatePayload = [];
          }
        } else {
          // For any other property we always add it to the queue and then we
          // filter it out using the whitelist during the commit.
          (updatePayload = updatePayload || []).push(propKey, nextProp);
        }
      }

      if (styleUpdates) {
        {
          validateShorthandPropertyCollisionInDev(styleUpdates, nextProps[STYLE]);
        }
        (updatePayload = updatePayload || []).push(STYLE, styleUpdates);
      }

      return updatePayload;
    } // Apply the diff.


    function updateProperties(domElement, updatePayload, tag, lastRawProps, nextRawProps) {
      // Update checked *before* name.
      // In the middle of an update, it is possible to have multiple checked.
      // When a checked radio tries to change name, browser makes another radio's checked false.
      if (tag === 'input' && nextRawProps.type === 'radio' && nextRawProps.name != null) {
        updateChecked(domElement, nextRawProps);
      }

      var wasCustomComponentTag = isCustomComponent(tag, lastRawProps);
      var isCustomComponentTag = isCustomComponent(tag, nextRawProps); // Apply the diff.

      updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag); // TODO: Ensure that an update gets scheduled if any of the special props
      // changed.

      switch (tag) {
        case 'input':
          // Update the wrapper around inputs *after* updating props. This has to
          // happen after `updateDOMProperties`. Otherwise HTML5 input validations
          // raise warnings and prevent the new value from being assigned.
          updateWrapper(domElement, nextRawProps);
          break;

        case 'textarea':
          updateWrapper$1(domElement, nextRawProps);
          break;

        case 'select':
          // <select> value update needs to occur after <option> children
          // reconciliation
          postUpdateWrapper(domElement, nextRawProps);
          break;
      }
    }

    function getPossibleStandardName(propName) {
      {
        var lowerCasedName = propName.toLowerCase();

        if (!possibleStandardNames.hasOwnProperty(lowerCasedName)) {
          return null;
        }

        return possibleStandardNames[lowerCasedName] || null;
      }
    }

    function diffHydratedProperties(domElement, tag, rawProps, parentNamespace, rootContainerElement) {
      var isCustomComponentTag;
      var extraAttributeNames;
      {
        suppressHydrationWarning = rawProps[SUPPRESS_HYDRATION_WARNING] === true;
        isCustomComponentTag = isCustomComponent(tag, rawProps);
        validatePropertiesInDevelopment(tag, rawProps);
      } // TODO: Make sure that we check isMounted before firing any of these events.

      switch (tag) {
        case 'iframe':
        case 'object':
        case 'embed':
          trapBubbledEvent(TOP_LOAD, domElement);
          break;

        case 'video':
        case 'audio':
          // Create listener for each media event
          for (var i = 0; i < mediaEventTypes.length; i++) {
            trapBubbledEvent(mediaEventTypes[i], domElement);
          }

          break;

        case 'source':
          trapBubbledEvent(TOP_ERROR, domElement);
          break;

        case 'img':
        case 'image':
        case 'link':
          trapBubbledEvent(TOP_ERROR, domElement);
          trapBubbledEvent(TOP_LOAD, domElement);
          break;

        case 'form':
          trapBubbledEvent(TOP_RESET, domElement);
          trapBubbledEvent(TOP_SUBMIT, domElement);
          break;

        case 'details':
          trapBubbledEvent(TOP_TOGGLE, domElement);
          break;

        case 'input':
          initWrapperState(domElement, rawProps);
          trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening
          // to onChange. Even if there is no listener.

          ensureListeningTo(rootContainerElement, 'onChange');
          break;

        case 'option':
          validateProps(domElement, rawProps);
          break;

        case 'select':
          initWrapperState$1(domElement, rawProps);
          trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening
          // to onChange. Even if there is no listener.

          ensureListeningTo(rootContainerElement, 'onChange');
          break;

        case 'textarea':
          initWrapperState$2(domElement, rawProps);
          trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening
          // to onChange. Even if there is no listener.

          ensureListeningTo(rootContainerElement, 'onChange');
          break;
      }

      assertValidProps(tag, rawProps);
      {
        extraAttributeNames = new Set();
        var attributes = domElement.attributes;

        for (var _i = 0; _i < attributes.length; _i++) {
          var name = attributes[_i].name.toLowerCase();

          switch (name) {
            // Built-in SSR attribute is whitelisted
            case 'data-reactroot':
              break;
            // Controlled attributes are not validated
            // TODO: Only ignore them on controlled tags.

            case 'value':
              break;

            case 'checked':
              break;

            case 'selected':
              break;

            default:
              // Intentionally use the original name.
              // See discussion in https://github.com/facebook/react/pull/10676.
              extraAttributeNames.add(attributes[_i].name);
          }
        }
      }
      var updatePayload = null;

      for (var propKey in rawProps) {
        if (!rawProps.hasOwnProperty(propKey)) {
          continue;
        }

        var nextProp = rawProps[propKey];

        if (propKey === CHILDREN) {
          // For text content children we compare against textContent. This
          // might match additional HTML that is hidden when we read it using
          // textContent. E.g. "foo" will match "f<span>oo</span>" but that still
          // satisfies our requirement. Our requirement is not to produce perfect
          // HTML and attributes. Ideally we should preserve structure but it's
          // ok not to if the visible content is still enough to indicate what
          // even listeners these nodes might be wired up to.
          // TODO: Warn if there is more than a single textNode as a child.
          // TODO: Should we use domElement.firstChild.nodeValue to compare?
          if (typeof nextProp === 'string') {
            if (domElement.textContent !== nextProp) {
              if (!suppressHydrationWarning) {
                warnForTextDifference(domElement.textContent, nextProp);
              }

              updatePayload = [CHILDREN, nextProp];
            }
          } else if (typeof nextProp === 'number') {
            if (domElement.textContent !== '' + nextProp) {
              if (!suppressHydrationWarning) {
                warnForTextDifference(domElement.textContent, nextProp);
              }

              updatePayload = [CHILDREN, '' + nextProp];
            }
          }
        } else if (registrationNameModules.hasOwnProperty(propKey)) {
          if (nextProp != null) {
            if (typeof nextProp !== 'function') {
              warnForInvalidEventListener(propKey, nextProp);
            }

            ensureListeningTo(rootContainerElement, propKey);
          }
        } else if ( // Convince Flow we've calculated it (it's DEV-only in this method.)
        typeof isCustomComponentTag === 'boolean') {
          // Validate that the properties correspond to their expected values.
          var serverValue = void 0;
          var propertyInfo = getPropertyInfo(propKey);
          if (suppressHydrationWarning) ;else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING || // Controlled attributes are not validated
          // TODO: Only ignore them on controlled tags.
          propKey === 'value' || propKey === 'checked' || propKey === 'selected') ;else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
            var serverHTML = domElement.innerHTML;
            var nextHtml = nextProp ? nextProp[HTML$1] : undefined;
            var expectedHTML = normalizeHTML(domElement, nextHtml != null ? nextHtml : '');

            if (expectedHTML !== serverHTML) {
              warnForPropDifference(propKey, serverHTML, expectedHTML);
            }
          } else if (propKey === STYLE) {
            // $FlowFixMe - Should be inferred as not undefined.
            extraAttributeNames.delete(propKey);

            if (canDiffStyleForHydrationWarning) {
              var expectedStyle = createDangerousStringForStyles(nextProp);
              serverValue = domElement.getAttribute('style');

              if (expectedStyle !== serverValue) {
                warnForPropDifference(propKey, serverValue, expectedStyle);
              }
            }
          } else if (isCustomComponentTag) {
            // $FlowFixMe - Should be inferred as not undefined.
            extraAttributeNames.delete(propKey.toLowerCase());
            serverValue = getValueForAttribute(domElement, propKey, nextProp);

            if (nextProp !== serverValue) {
              warnForPropDifference(propKey, serverValue, nextProp);
            }
          } else if (!shouldIgnoreAttribute(propKey, propertyInfo, isCustomComponentTag) && !shouldRemoveAttribute(propKey, nextProp, propertyInfo, isCustomComponentTag)) {
            var isMismatchDueToBadCasing = false;

            if (propertyInfo !== null) {
              // $FlowFixMe - Should be inferred as not undefined.
              extraAttributeNames.delete(propertyInfo.attributeName);
              serverValue = getValueForProperty(domElement, propKey, nextProp, propertyInfo);
            } else {
              var ownNamespace = parentNamespace;

              if (ownNamespace === HTML_NAMESPACE$1) {
                ownNamespace = getIntrinsicNamespace(tag);
              }

              if (ownNamespace === HTML_NAMESPACE$1) {
                // $FlowFixMe - Should be inferred as not undefined.
                extraAttributeNames.delete(propKey.toLowerCase());
              } else {
                var standardName = getPossibleStandardName(propKey);

                if (standardName !== null && standardName !== propKey) {
                  // If an SVG prop is supplied with bad casing, it will
                  // be successfully parsed from HTML, but will produce a mismatch
                  // (and would be incorrectly rendered on the client).
                  // However, we already warn about bad casing elsewhere.
                  // So we'll skip the misleading extra mismatch warning in this case.
                  isMismatchDueToBadCasing = true; // $FlowFixMe - Should be inferred as not undefined.

                  extraAttributeNames.delete(standardName);
                } // $FlowFixMe - Should be inferred as not undefined.


                extraAttributeNames.delete(propKey);
              }

              serverValue = getValueForAttribute(domElement, propKey, nextProp);
            }

            if (nextProp !== serverValue && !isMismatchDueToBadCasing) {
              warnForPropDifference(propKey, serverValue, nextProp);
            }
          }
        }
      }

      {
        // $FlowFixMe - Should be inferred as not undefined.
        if (extraAttributeNames.size > 0 && !suppressHydrationWarning) {
          // $FlowFixMe - Should be inferred as not undefined.
          warnForExtraAttributes(extraAttributeNames);
        }
      }

      switch (tag) {
        case 'input':
          // TODO: Make sure we check if this is still unmounted or do any clean
          // up necessary since we never stop tracking anymore.
          track(domElement);
          postMountWrapper(domElement, rawProps, true);
          break;

        case 'textarea':
          // TODO: Make sure we check if this is still unmounted or do any clean
          // up necessary since we never stop tracking anymore.
          track(domElement);
          postMountWrapper$3(domElement);
          break;

        case 'select':
        case 'option':
          // For input and textarea we current always set the value property at
          // post mount to force it to diverge from attributes. However, for
          // option and select we don't quite do the same thing and select
          // is not resilient to the DOM state changing so we don't do that here.
          // TODO: Consider not doing this for input and textarea.
          break;

        default:
          if (typeof rawProps.onClick === 'function') {
            // TODO: This cast may not be sound for SVG, MathML or custom elements.
            trapClickOnNonInteractiveElement(domElement);
          }

          break;
      }

      return updatePayload;
    }

    function diffHydratedText(textNode, text) {
      var isDifferent = textNode.nodeValue !== text;
      return isDifferent;
    }

    function warnForUnmatchedText(textNode, text) {
      {
        warnForTextDifference(textNode.nodeValue, text);
      }
    }

    function warnForDeletedHydratableElement(parentNode, child) {
      {
        if (didWarnInvalidHydration) {
          return;
        }

        didWarnInvalidHydration = true;
        error('Did not expect server HTML to contain a <%s> in <%s>.', child.nodeName.toLowerCase(), parentNode.nodeName.toLowerCase());
      }
    }

    function warnForDeletedHydratableText(parentNode, child) {
      {
        if (didWarnInvalidHydration) {
          return;
        }

        didWarnInvalidHydration = true;
        error('Did not expect server HTML to contain the text node "%s" in <%s>.', child.nodeValue, parentNode.nodeName.toLowerCase());
      }
    }

    function warnForInsertedHydratedElement(parentNode, tag, props) {
      {
        if (didWarnInvalidHydration) {
          return;
        }

        didWarnInvalidHydration = true;
        error('Expected server HTML to contain a matching <%s> in <%s>.', tag, parentNode.nodeName.toLowerCase());
      }
    }

    function warnForInsertedHydratedText(parentNode, text) {
      {
        if (text === '') {
          // We expect to insert empty text nodes since they're not represented in
          // the HTML.
          // TODO: Remove this special case if we can just avoid inserting empty
          // text nodes.
          return;
        }

        if (didWarnInvalidHydration) {
          return;
        }

        didWarnInvalidHydration = true;
        error('Expected server HTML to contain a matching text node for "%s" in <%s>.', text, parentNode.nodeName.toLowerCase());
      }
    }

    function restoreControlledState$3(domElement, tag, props) {
      switch (tag) {
        case 'input':
          restoreControlledState(domElement, props);
          return;

        case 'textarea':
          restoreControlledState$2(domElement, props);
          return;

        case 'select':
          restoreControlledState$1(domElement, props);
          return;
      }
    }

    function getActiveElement(doc) {
      doc = doc || (typeof document !== 'undefined' ? document : undefined);

      if (typeof doc === 'undefined') {
        return null;
      }

      try {
        return doc.activeElement || doc.body;
      } catch (e) {
        return doc.body;
      }
    }
    /**
     * Given any node return the first leaf node without children.
     *
     * @param {DOMElement|DOMTextNode} node
     * @return {DOMElement|DOMTextNode}
     */


    function getLeafNode(node) {
      while (node && node.firstChild) {
        node = node.firstChild;
      }

      return node;
    }
    /**
     * Get the next sibling within a container. This will walk up the
     * DOM if a node's siblings have been exhausted.
     *
     * @param {DOMElement|DOMTextNode} node
     * @return {?DOMElement|DOMTextNode}
     */


    function getSiblingNode(node) {
      while (node) {
        if (node.nextSibling) {
          return node.nextSibling;
        }

        node = node.parentNode;
      }
    }
    /**
     * Get object describing the nodes which contain characters at offset.
     *
     * @param {DOMElement|DOMTextNode} root
     * @param {number} offset
     * @return {?object}
     */


    function getNodeForCharacterOffset(root, offset) {
      var node = getLeafNode(root);
      var nodeStart = 0;
      var nodeEnd = 0;

      while (node) {
        if (node.nodeType === TEXT_NODE) {
          nodeEnd = nodeStart + node.textContent.length;

          if (nodeStart <= offset && nodeEnd >= offset) {
            return {
              node: node,
              offset: offset - nodeStart
            };
          }

          nodeStart = nodeEnd;
        }

        node = getLeafNode(getSiblingNode(node));
      }
    }
    /**
     * @param {DOMElement} outerNode
     * @return {?object}
     */


    function getOffsets(outerNode) {
      var ownerDocument = outerNode.ownerDocument;
      var win = ownerDocument && ownerDocument.defaultView || window;
      var selection = win.getSelection && win.getSelection();

      if (!selection || selection.rangeCount === 0) {
        return null;
      }

      var anchorNode = selection.anchorNode,
          anchorOffset = selection.anchorOffset,
          focusNode = selection.focusNode,
          focusOffset = selection.focusOffset; // In Firefox, anchorNode and focusNode can be "anonymous divs", e.g. the
      // up/down buttons on an <input type="number">. Anonymous divs do not seem to
      // expose properties, triggering a "Permission denied error" if any of its
      // properties are accessed. The only seemingly possible way to avoid erroring
      // is to access a property that typically works for non-anonymous divs and
      // catch any error that may otherwise arise. See
      // https://bugzilla.mozilla.org/show_bug.cgi?id=208427

      try {
        /* eslint-disable no-unused-expressions */
        anchorNode.nodeType;
        focusNode.nodeType;
        /* eslint-enable no-unused-expressions */
      } catch (e) {
        return null;
      }

      return getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset);
    }
    /**
     * Returns {start, end} where `start` is the character/codepoint index of
     * (anchorNode, anchorOffset) within the textContent of `outerNode`, and
     * `end` is the index of (focusNode, focusOffset).
     *
     * Returns null if you pass in garbage input but we should probably just crash.
     *
     * Exported only for testing.
     */


    function getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset) {
      var length = 0;
      var start = -1;
      var end = -1;
      var indexWithinAnchor = 0;
      var indexWithinFocus = 0;
      var node = outerNode;
      var parentNode = null;

      outer: while (true) {
        var next = null;

        while (true) {
          if (node === anchorNode && (anchorOffset === 0 || node.nodeType === TEXT_NODE)) {
            start = length + anchorOffset;
          }

          if (node === focusNode && (focusOffset === 0 || node.nodeType === TEXT_NODE)) {
            end = length + focusOffset;
          }

          if (node.nodeType === TEXT_NODE) {
            length += node.nodeValue.length;
          }

          if ((next = node.firstChild) === null) {
            break;
          } // Moving from `node` to its first child `next`.


          parentNode = node;
          node = next;
        }

        while (true) {
          if (node === outerNode) {
            // If `outerNode` has children, this is always the second time visiting
            // it. If it has no children, this is still the first loop, and the only
            // valid selection is anchorNode and focusNode both equal to this node
            // and both offsets 0, in which case we will have handled above.
            break outer;
          }

          if (parentNode === anchorNode && ++indexWithinAnchor === anchorOffset) {
            start = length;
          }

          if (parentNode === focusNode && ++indexWithinFocus === focusOffset) {
            end = length;
          }

          if ((next = node.nextSibling) !== null) {
            break;
          }

          node = parentNode;
          parentNode = node.parentNode;
        } // Moving from `node` to its next sibling `next`.


        node = next;
      }

      if (start === -1 || end === -1) {
        // This should never happen. (Would happen if the anchor/focus nodes aren't
        // actually inside the passed-in node.)
        return null;
      }

      return {
        start: start,
        end: end
      };
    }
    /**
     * In modern non-IE browsers, we can support both forward and backward
     * selections.
     *
     * Note: IE10+ supports the Selection object, but it does not support
     * the `extend` method, which means that even in modern IE, it's not possible
     * to programmatically create a backward selection. Thus, for all IE
     * versions, we use the old IE API to create our selections.
     *
     * @param {DOMElement|DOMTextNode} node
     * @param {object} offsets
     */


    function setOffsets(node, offsets) {
      var doc = node.ownerDocument || document;
      var win = doc && doc.defaultView || window; // Edge fails with "Object expected" in some scenarios.
      // (For instance: TinyMCE editor used in a list component that supports pasting to add more,
      // fails when pasting 100+ items)

      if (!win.getSelection) {
        return;
      }

      var selection = win.getSelection();
      var length = node.textContent.length;
      var start = Math.min(offsets.start, length);
      var end = offsets.end === undefined ? start : Math.min(offsets.end, length); // IE 11 uses modern selection, but doesn't support the extend method.
      // Flip backward selections, so we can set with a single range.

      if (!selection.extend && start > end) {
        var temp = end;
        end = start;
        start = temp;
      }

      var startMarker = getNodeForCharacterOffset(node, start);
      var endMarker = getNodeForCharacterOffset(node, end);

      if (startMarker && endMarker) {
        if (selection.rangeCount === 1 && selection.anchorNode === startMarker.node && selection.anchorOffset === startMarker.offset && selection.focusNode === endMarker.node && selection.focusOffset === endMarker.offset) {
          return;
        }

        var range = doc.createRange();
        range.setStart(startMarker.node, startMarker.offset);
        selection.removeAllRanges();

        if (start > end) {
          selection.addRange(range);
          selection.extend(endMarker.node, endMarker.offset);
        } else {
          range.setEnd(endMarker.node, endMarker.offset);
          selection.addRange(range);
        }
      }
    }

    function isTextNode(node) {
      return node && node.nodeType === TEXT_NODE;
    }

    function containsNode(outerNode, innerNode) {
      if (!outerNode || !innerNode) {
        return false;
      } else if (outerNode === innerNode) {
        return true;
      } else if (isTextNode(outerNode)) {
        return false;
      } else if (isTextNode(innerNode)) {
        return containsNode(outerNode, innerNode.parentNode);
      } else if ('contains' in outerNode) {
        return outerNode.contains(innerNode);
      } else if (outerNode.compareDocumentPosition) {
        return !!(outerNode.compareDocumentPosition(innerNode) & 16);
      } else {
        return false;
      }
    }

    function isInDocument(node) {
      return node && node.ownerDocument && containsNode(node.ownerDocument.documentElement, node);
    }

    function isSameOriginFrame(iframe) {
      try {
        // Accessing the contentDocument of a HTMLIframeElement can cause the browser
        // to throw, e.g. if it has a cross-origin src attribute.
        // Safari will show an error in the console when the access results in "Blocked a frame with origin". e.g:
        // iframe.contentDocument.defaultView;
        // A safety way is to access one of the cross origin properties: Window or Location
        // Which might result in "SecurityError" DOM Exception and it is compatible to Safari.
        // https://html.spec.whatwg.org/multipage/browsers.html#integration-with-idl
        return typeof iframe.contentWindow.location.href === 'string';
      } catch (err) {
        return false;
      }
    }

    function getActiveElementDeep() {
      var win = window;
      var element = getActiveElement();

      while (element instanceof win.HTMLIFrameElement) {
        if (isSameOriginFrame(element)) {
          win = element.contentWindow;
        } else {
          return element;
        }

        element = getActiveElement(win.document);
      }

      return element;
    }
    /**
     * @ReactInputSelection: React input selection module. Based on Selection.js,
     * but modified to be suitable for react and has a couple of bug fixes (doesn't
     * assume buttons have range selections allowed).
     * Input selection module for React.
     */

    /**
     * @hasSelectionCapabilities: we get the element types that support selection
     * from https://html.spec.whatwg.org/#do-not-apply, looking at `selectionStart`
     * and `selectionEnd` rows.
     */


    function hasSelectionCapabilities(elem) {
      var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
      return nodeName && (nodeName === 'input' && (elem.type === 'text' || elem.type === 'search' || elem.type === 'tel' || elem.type === 'url' || elem.type === 'password') || nodeName === 'textarea' || elem.contentEditable === 'true');
    }

    function getSelectionInformation() {
      var focusedElem = getActiveElementDeep();
      return {
        // Used by Flare
        activeElementDetached: null,
        focusedElem: focusedElem,
        selectionRange: hasSelectionCapabilities(focusedElem) ? getSelection(focusedElem) : null
      };
    }
    /**
     * @restoreSelection: If any selection information was potentially lost,
     * restore it. This is useful when performing operations that could remove dom
     * nodes and place them back in, resulting in focus being lost.
     */


    function restoreSelection(priorSelectionInformation) {
      var curFocusedElem = getActiveElementDeep();
      var priorFocusedElem = priorSelectionInformation.focusedElem;
      var priorSelectionRange = priorSelectionInformation.selectionRange;

      if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) {
        if (priorSelectionRange !== null && hasSelectionCapabilities(priorFocusedElem)) {
          setSelection(priorFocusedElem, priorSelectionRange);
        } // Focusing a node can change the scroll position, which is undesirable


        var ancestors = [];
        var ancestor = priorFocusedElem;

        while (ancestor = ancestor.parentNode) {
          if (ancestor.nodeType === ELEMENT_NODE) {
            ancestors.push({
              element: ancestor,
              left: ancestor.scrollLeft,
              top: ancestor.scrollTop
            });
          }
        }

        if (typeof priorFocusedElem.focus === 'function') {
          priorFocusedElem.focus();
        }

        for (var i = 0; i < ancestors.length; i++) {
          var info = ancestors[i];
          info.element.scrollLeft = info.left;
          info.element.scrollTop = info.top;
        }
      }
    }
    /**
     * @getSelection: Gets the selection bounds of a focused textarea, input or
     * contentEditable node.
     * -@input: Look up selection bounds of this input
     * -@return {start: selectionStart, end: selectionEnd}
     */


    function getSelection(input) {
      var selection;

      if ('selectionStart' in input) {
        // Modern browser with input or textarea.
        selection = {
          start: input.selectionStart,
          end: input.selectionEnd
        };
      } else {
        // Content editable or old IE textarea.
        selection = getOffsets(input);
      }

      return selection || {
        start: 0,
        end: 0
      };
    }
    /**
     * @setSelection: Sets the selection bounds of a textarea or input and focuses
     * the input.
     * -@input     Set selection bounds of this input or textarea
     * -@offsets   Object of same form that is returned from get*
     */


    function setSelection(input, offsets) {
      var start = offsets.start,
          end = offsets.end;

      if (end === undefined) {
        end = start;
      }

      if ('selectionStart' in input) {
        input.selectionStart = start;
        input.selectionEnd = Math.min(end, input.value.length);
      } else {
        setOffsets(input, offsets);
      }
    }

    var validateDOMNesting = function () {};

    var updatedAncestorInfo = function () {};

    {
      // This validation code was written based on the HTML5 parsing spec:
      // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
      //
      // Note: this does not catch all invalid nesting, nor does it try to (as it's
      // not clear what practical benefit doing so provides); instead, we warn only
      // for cases where the parser will give a parse tree differing from what React
      // intended. For example, <b><div></div></b> is invalid but we don't warn
      // because it still parses correctly; we do warn for other cases like nested
      // <p> tags where the beginning of the second element implicitly closes the
      // first, causing a confusing mess.
      // https://html.spec.whatwg.org/multipage/syntax.html#special
      var specialTags = ['address', 'applet', 'area', 'article', 'aside', 'base', 'basefont', 'bgsound', 'blockquote', 'body', 'br', 'button', 'caption', 'center', 'col', 'colgroup', 'dd', 'details', 'dir', 'div', 'dl', 'dt', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'iframe', 'img', 'input', 'isindex', 'li', 'link', 'listing', 'main', 'marquee', 'menu', 'menuitem', 'meta', 'nav', 'noembed', 'noframes', 'noscript', 'object', 'ol', 'p', 'param', 'plaintext', 'pre', 'script', 'section', 'select', 'source', 'style', 'summary', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul', 'wbr', 'xmp']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope

      var inScopeTags = ['applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', 'template', // https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point
      // TODO: Distinguish by namespace here -- for <title>, including it here
      // errs on the side of fewer warnings
      'foreignObject', 'desc', 'title']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope

      var buttonScopeTags = inScopeTags.concat(['button']); // https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags

      var impliedEndTags = ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt'];
      var emptyAncestorInfo = {
        current: null,
        formTag: null,
        aTagInScope: null,
        buttonTagInScope: null,
        nobrTagInScope: null,
        pTagInButtonScope: null,
        listItemTagAutoclosing: null,
        dlItemTagAutoclosing: null
      };

      updatedAncestorInfo = function (oldInfo, tag) {
        var ancestorInfo = _assign({}, oldInfo || emptyAncestorInfo);

        var info = {
          tag: tag
        };

        if (inScopeTags.indexOf(tag) !== -1) {
          ancestorInfo.aTagInScope = null;
          ancestorInfo.buttonTagInScope = null;
          ancestorInfo.nobrTagInScope = null;
        }

        if (buttonScopeTags.indexOf(tag) !== -1) {
          ancestorInfo.pTagInButtonScope = null;
        } // See rules for 'li', 'dd', 'dt' start tags in
        // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody


        if (specialTags.indexOf(tag) !== -1 && tag !== 'address' && tag !== 'div' && tag !== 'p') {
          ancestorInfo.listItemTagAutoclosing = null;
          ancestorInfo.dlItemTagAutoclosing = null;
        }

        ancestorInfo.current = info;

        if (tag === 'form') {
          ancestorInfo.formTag = info;
        }

        if (tag === 'a') {
          ancestorInfo.aTagInScope = info;
        }

        if (tag === 'button') {
          ancestorInfo.buttonTagInScope = info;
        }

        if (tag === 'nobr') {
          ancestorInfo.nobrTagInScope = info;
        }

        if (tag === 'p') {
          ancestorInfo.pTagInButtonScope = info;
        }

        if (tag === 'li') {
          ancestorInfo.listItemTagAutoclosing = info;
        }

        if (tag === 'dd' || tag === 'dt') {
          ancestorInfo.dlItemTagAutoclosing = info;
        }

        return ancestorInfo;
      };
      /**
       * Returns whether
       */


      var isTagValidWithParent = function (tag, parentTag) {
        // First, let's check if we're in an unusual parsing mode...
        switch (parentTag) {
          // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect
          case 'select':
            return tag === 'option' || tag === 'optgroup' || tag === '#text';

          case 'optgroup':
            return tag === 'option' || tag === '#text';
          // Strictly speaking, seeing an <option> doesn't mean we're in a <select>
          // but

          case 'option':
            return tag === '#text';
          // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd
          // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption
          // No special behavior since these rules fall back to "in body" mode for
          // all except special table nodes which cause bad parsing behavior anyway.
          // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr

          case 'tr':
            return tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' || tag === 'template';
          // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody

          case 'tbody':
          case 'thead':
          case 'tfoot':
            return tag === 'tr' || tag === 'style' || tag === 'script' || tag === 'template';
          // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup

          case 'colgroup':
            return tag === 'col' || tag === 'template';
          // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable

          case 'table':
            return tag === 'caption' || tag === 'colgroup' || tag === 'tbody' || tag === 'tfoot' || tag === 'thead' || tag === 'style' || tag === 'script' || tag === 'template';
          // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead

          case 'head':
            return tag === 'base' || tag === 'basefont' || tag === 'bgsound' || tag === 'link' || tag === 'meta' || tag === 'title' || tag === 'noscript' || tag === 'noframes' || tag === 'style' || tag === 'script' || tag === 'template';
          // https://html.spec.whatwg.org/multipage/semantics.html#the-html-element

          case 'html':
            return tag === 'head' || tag === 'body' || tag === 'frameset';

          case 'frameset':
            return tag === 'frame';

          case '#document':
            return tag === 'html';
        } // Probably in the "in body" parsing mode, so we outlaw only tag combos
        // where the parsing rules cause implicit opens or closes to be added.
        // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody


        switch (tag) {
          case 'h1':
          case 'h2':
          case 'h3':
          case 'h4':
          case 'h5':
          case 'h6':
            return parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' && parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6';

          case 'rp':
          case 'rt':
            return impliedEndTags.indexOf(parentTag) === -1;

          case 'body':
          case 'caption':
          case 'col':
          case 'colgroup':
          case 'frameset':
          case 'frame':
          case 'head':
          case 'html':
          case 'tbody':
          case 'td':
          case 'tfoot':
          case 'th':
          case 'thead':
          case 'tr':
            // These tags are only valid with a few parents that have special child
            // parsing rules -- if we're down here, then none of those matched and
            // so we allow it only if we don't know what the parent is, as all other
            // cases are invalid.
            return parentTag == null;
        }

        return true;
      };
      /**
       * Returns whether
       */


      var findInvalidAncestorForTag = function (tag, ancestorInfo) {
        switch (tag) {
          case 'address':
          case 'article':
          case 'aside':
          case 'blockquote':
          case 'center':
          case 'details':
          case 'dialog':
          case 'dir':
          case 'div':
          case 'dl':
          case 'fieldset':
          case 'figcaption':
          case 'figure':
          case 'footer':
          case 'header':
          case 'hgroup':
          case 'main':
          case 'menu':
          case 'nav':
          case 'ol':
          case 'p':
          case 'section':
          case 'summary':
          case 'ul':
          case 'pre':
          case 'listing':
          case 'table':
          case 'hr':
          case 'xmp':
          case 'h1':
          case 'h2':
          case 'h3':
          case 'h4':
          case 'h5':
          case 'h6':
            return ancestorInfo.pTagInButtonScope;

          case 'form':
            return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope;

          case 'li':
            return ancestorInfo.listItemTagAutoclosing;

          case 'dd':
          case 'dt':
            return ancestorInfo.dlItemTagAutoclosing;

          case 'button':
            return ancestorInfo.buttonTagInScope;

          case 'a':
            // Spec says something about storing a list of markers, but it sounds
            // equivalent to this check.
            return ancestorInfo.aTagInScope;

          case 'nobr':
            return ancestorInfo.nobrTagInScope;
        }

        return null;
      };

      var didWarn$1 = {};

      validateDOMNesting = function (childTag, childText, ancestorInfo) {
        ancestorInfo = ancestorInfo || emptyAncestorInfo;
        var parentInfo = ancestorInfo.current;
        var parentTag = parentInfo && parentInfo.tag;

        if (childText != null) {
          if (childTag != null) {
            error('validateDOMNesting: when childText is passed, childTag should be null');
          }

          childTag = '#text';
        }

        var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo;
        var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo);
        var invalidParentOrAncestor = invalidParent || invalidAncestor;

        if (!invalidParentOrAncestor) {
          return;
        }

        var ancestorTag = invalidParentOrAncestor.tag;
        var addendum = getCurrentFiberStackInDev();
        var warnKey = !!invalidParent + '|' + childTag + '|' + ancestorTag + '|' + addendum;

        if (didWarn$1[warnKey]) {
          return;
        }

        didWarn$1[warnKey] = true;
        var tagDisplayName = childTag;
        var whitespaceInfo = '';

        if (childTag === '#text') {
          if (/\S/.test(childText)) {
            tagDisplayName = 'Text nodes';
          } else {
            tagDisplayName = 'Whitespace text nodes';
            whitespaceInfo = " Make sure you don't have any extra whitespace between tags on " + 'each line of your source code.';
          }
        } else {
          tagDisplayName = '<' + childTag + '>';
        }

        if (invalidParent) {
          var info = '';

          if (ancestorTag === 'table' && childTag === 'tr') {
            info += ' Add a <tbody>, <thead> or <tfoot> to your code to match the DOM tree generated by ' + 'the browser.';
          }

          error('validateDOMNesting(...): %s cannot appear as a child of <%s>.%s%s', tagDisplayName, ancestorTag, whitespaceInfo, info);
        } else {
          error('validateDOMNesting(...): %s cannot appear as a descendant of ' + '<%s>.', tagDisplayName, ancestorTag);
        }
      };
    }
    var SUPPRESS_HYDRATION_WARNING$1;
    {
      SUPPRESS_HYDRATION_WARNING$1 = 'suppressHydrationWarning';
    }
    var SUSPENSE_START_DATA = '$';
    var SUSPENSE_END_DATA = '/$';
    var SUSPENSE_PENDING_START_DATA = '$?';
    var SUSPENSE_FALLBACK_START_DATA = '$!';
    var STYLE$1 = 'style';
    var eventsEnabled = null;
    var selectionInformation = null;

    function shouldAutoFocusHostComponent(type, props) {
      switch (type) {
        case 'button':
        case 'input':
        case 'select':
        case 'textarea':
          return !!props.autoFocus;
      }

      return false;
    }

    function getRootHostContext(rootContainerInstance) {
      var type;
      var namespace;
      var nodeType = rootContainerInstance.nodeType;

      switch (nodeType) {
        case DOCUMENT_NODE:
        case DOCUMENT_FRAGMENT_NODE:
          {
            type = nodeType === DOCUMENT_NODE ? '#document' : '#fragment';
            var root = rootContainerInstance.documentElement;
            namespace = root ? root.namespaceURI : getChildNamespace(null, '');
            break;
          }

        default:
          {
            var container = nodeType === COMMENT_NODE ? rootContainerInstance.parentNode : rootContainerInstance;
            var ownNamespace = container.namespaceURI || null;
            type = container.tagName;
            namespace = getChildNamespace(ownNamespace, type);
            break;
          }
      }

      {
        var validatedTag = type.toLowerCase();
        var ancestorInfo = updatedAncestorInfo(null, validatedTag);
        return {
          namespace: namespace,
          ancestorInfo: ancestorInfo
        };
      }
    }

    function getChildHostContext(parentHostContext, type, rootContainerInstance) {
      {
        var parentHostContextDev = parentHostContext;
        var namespace = getChildNamespace(parentHostContextDev.namespace, type);
        var ancestorInfo = updatedAncestorInfo(parentHostContextDev.ancestorInfo, type);
        return {
          namespace: namespace,
          ancestorInfo: ancestorInfo
        };
      }
    }

    function getPublicInstance(instance) {
      return instance;
    }

    function prepareForCommit(containerInfo) {
      eventsEnabled = isEnabled();
      selectionInformation = getSelectionInformation();
      setEnabled(false);
    }

    function resetAfterCommit(containerInfo) {
      restoreSelection(selectionInformation);
      setEnabled(eventsEnabled);
      eventsEnabled = null;
      selectionInformation = null;
    }

    function createInstance(type, props, rootContainerInstance, hostContext, internalInstanceHandle) {
      var parentNamespace;
      {
        // TODO: take namespace into account when validating.
        var hostContextDev = hostContext;
        validateDOMNesting(type, null, hostContextDev.ancestorInfo);

        if (typeof props.children === 'string' || typeof props.children === 'number') {
          var string = '' + props.children;
          var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type);
          validateDOMNesting(null, string, ownAncestorInfo);
        }

        parentNamespace = hostContextDev.namespace;
      }
      var domElement = createElement(type, props, rootContainerInstance, parentNamespace);
      precacheFiberNode(internalInstanceHandle, domElement);
      updateFiberProps(domElement, props);
      return domElement;
    }

    function appendInitialChild(parentInstance, child) {
      parentInstance.appendChild(child);
    }

    function finalizeInitialChildren(domElement, type, props, rootContainerInstance, hostContext) {
      setInitialProperties(domElement, type, props, rootContainerInstance);
      return shouldAutoFocusHostComponent(type, props);
    }

    function prepareUpdate(domElement, type, oldProps, newProps, rootContainerInstance, hostContext) {
      {
        var hostContextDev = hostContext;

        if (typeof newProps.children !== typeof oldProps.children && (typeof newProps.children === 'string' || typeof newProps.children === 'number')) {
          var string = '' + newProps.children;
          var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type);
          validateDOMNesting(null, string, ownAncestorInfo);
        }
      }
      return diffProperties(domElement, type, oldProps, newProps, rootContainerInstance);
    }

    function shouldSetTextContent(type, props) {
      return type === 'textarea' || type === 'option' || type === 'noscript' || typeof props.children === 'string' || typeof props.children === 'number' || typeof props.dangerouslySetInnerHTML === 'object' && props.dangerouslySetInnerHTML !== null && props.dangerouslySetInnerHTML.__html != null;
    }

    function shouldDeprioritizeSubtree(type, props) {
      return !!props.hidden;
    }

    function createTextInstance(text, rootContainerInstance, hostContext, internalInstanceHandle) {
      {
        var hostContextDev = hostContext;
        validateDOMNesting(null, text, hostContextDev.ancestorInfo);
      }
      var textNode = createTextNode(text, rootContainerInstance);
      precacheFiberNode(internalInstanceHandle, textNode);
      return textNode;
    } // if a component just imports ReactDOM (e.g. for findDOMNode).
    // Some environments might not have setTimeout or clearTimeout.


    var scheduleTimeout = typeof setTimeout === 'function' ? setTimeout : undefined;
    var cancelTimeout = typeof clearTimeout === 'function' ? clearTimeout : undefined;
    var noTimeout = -1; // -------------------

    function commitMount(domElement, type, newProps, internalInstanceHandle) {
      // Despite the naming that might imply otherwise, this method only
      // fires if there is an `Update` effect scheduled during mounting.
      // This happens if `finalizeInitialChildren` returns `true` (which it
      // does to implement the `autoFocus` attribute on the client). But
      // there are also other cases when this might happen (such as patching
      // up text content during hydration mismatch). So we'll check this again.
      if (shouldAutoFocusHostComponent(type, newProps)) {
        domElement.focus();
      }
    }

    function commitUpdate(domElement, updatePayload, type, oldProps, newProps, internalInstanceHandle) {
      // Update the props handle so that we know which props are the ones with
      // with current event handlers.
      updateFiberProps(domElement, newProps); // Apply the diff to the DOM node.

      updateProperties(domElement, updatePayload, type, oldProps, newProps);
    }

    function resetTextContent(domElement) {
      setTextContent(domElement, '');
    }

    function commitTextUpdate(textInstance, oldText, newText) {
      textInstance.nodeValue = newText;
    }

    function appendChild(parentInstance, child) {
      parentInstance.appendChild(child);
    }

    function appendChildToContainer(container, child) {
      var parentNode;

      if (container.nodeType === COMMENT_NODE) {
        parentNode = container.parentNode;
        parentNode.insertBefore(child, container);
      } else {
        parentNode = container;
        parentNode.appendChild(child);
      } // This container might be used for a portal.
      // If something inside a portal is clicked, that click should bubble
      // through the React tree. However, on Mobile Safari the click would
      // never bubble through the *DOM* tree unless an ancestor with onclick
      // event exists. So we wouldn't see it and dispatch it.
      // This is why we ensure that non React root containers have inline onclick
      // defined.
      // https://github.com/facebook/react/issues/11918


      var reactRootContainer = container._reactRootContainer;

      if ((reactRootContainer === null || reactRootContainer === undefined) && parentNode.onclick === null) {
        // TODO: This cast may not be sound for SVG, MathML or custom elements.
        trapClickOnNonInteractiveElement(parentNode);
      }
    }

    function insertBefore(parentInstance, child, beforeChild) {
      parentInstance.insertBefore(child, beforeChild);
    }

    function insertInContainerBefore(container, child, beforeChild) {
      if (container.nodeType === COMMENT_NODE) {
        container.parentNode.insertBefore(child, beforeChild);
      } else {
        container.insertBefore(child, beforeChild);
      }
    }

    function removeChild(parentInstance, child) {
      parentInstance.removeChild(child);
    }

    function removeChildFromContainer(container, child) {
      if (container.nodeType === COMMENT_NODE) {
        container.parentNode.removeChild(child);
      } else {
        container.removeChild(child);
      }
    }

    function hideInstance(instance) {
      // pass host context to this method?
      instance = instance;
      var style = instance.style;

      if (typeof style.setProperty === 'function') {
        style.setProperty('display', 'none', 'important');
      } else {
        style.display = 'none';
      }
    }

    function hideTextInstance(textInstance) {
      textInstance.nodeValue = '';
    }

    function unhideInstance(instance, props) {
      instance = instance;
      var styleProp = props[STYLE$1];
      var display = styleProp !== undefined && styleProp !== null && styleProp.hasOwnProperty('display') ? styleProp.display : null;
      instance.style.display = dangerousStyleValue('display', display);
    }

    function unhideTextInstance(textInstance, text) {
      textInstance.nodeValue = text;
    } // -------------------


    function canHydrateInstance(instance, type, props) {
      if (instance.nodeType !== ELEMENT_NODE || type.toLowerCase() !== instance.nodeName.toLowerCase()) {
        return null;
      } // This has now been refined to an element node.


      return instance;
    }

    function canHydrateTextInstance(instance, text) {
      if (text === '' || instance.nodeType !== TEXT_NODE) {
        // Empty strings are not parsed by HTML so there won't be a correct match here.
        return null;
      } // This has now been refined to a text node.


      return instance;
    }

    function isSuspenseInstancePending(instance) {
      return instance.data === SUSPENSE_PENDING_START_DATA;
    }

    function isSuspenseInstanceFallback(instance) {
      return instance.data === SUSPENSE_FALLBACK_START_DATA;
    }

    function getNextHydratable(node) {
      // Skip non-hydratable nodes.
      for (; node != null; node = node.nextSibling) {
        var nodeType = node.nodeType;

        if (nodeType === ELEMENT_NODE || nodeType === TEXT_NODE) {
          break;
        }
      }

      return node;
    }

    function getNextHydratableSibling(instance) {
      return getNextHydratable(instance.nextSibling);
    }

    function getFirstHydratableChild(parentInstance) {
      return getNextHydratable(parentInstance.firstChild);
    }

    function hydrateInstance(instance, type, props, rootContainerInstance, hostContext, internalInstanceHandle) {
      precacheFiberNode(internalInstanceHandle, instance); // TODO: Possibly defer this until the commit phase where all the events
      // get attached.

      updateFiberProps(instance, props);
      var parentNamespace;
      {
        var hostContextDev = hostContext;
        parentNamespace = hostContextDev.namespace;
      }
      return diffHydratedProperties(instance, type, props, parentNamespace, rootContainerInstance);
    }

    function hydrateTextInstance(textInstance, text, internalInstanceHandle) {
      precacheFiberNode(internalInstanceHandle, textInstance);
      return diffHydratedText(textInstance, text);
    }

    function getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance) {
      var node = suspenseInstance.nextSibling; // Skip past all nodes within this suspense boundary.
      // There might be nested nodes so we need to keep track of how
      // deep we are and only break out when we're back on top.

      var depth = 0;

      while (node) {
        if (node.nodeType === COMMENT_NODE) {
          var data = node.data;

          if (data === SUSPENSE_END_DATA) {
            if (depth === 0) {
              return getNextHydratableSibling(node);
            } else {
              depth--;
            }
          } else if (data === SUSPENSE_START_DATA || data === SUSPENSE_FALLBACK_START_DATA || data === SUSPENSE_PENDING_START_DATA) {
            depth++;
          }
        }

        node = node.nextSibling;
      } // TODO: Warn, we didn't find the end comment boundary.


      return null;
    } // Returns the SuspenseInstance if this node is a direct child of a
    // SuspenseInstance. I.e. if its previous sibling is a Comment with
    // SUSPENSE_x_START_DATA. Otherwise, null.


    function getParentSuspenseInstance(targetInstance) {
      var node = targetInstance.previousSibling; // Skip past all nodes within this suspense boundary.
      // There might be nested nodes so we need to keep track of how
      // deep we are and only break out when we're back on top.

      var depth = 0;

      while (node) {
        if (node.nodeType === COMMENT_NODE) {
          var data = node.data;

          if (data === SUSPENSE_START_DATA || data === SUSPENSE_FALLBACK_START_DATA || data === SUSPENSE_PENDING_START_DATA) {
            if (depth === 0) {
              return node;
            } else {
              depth--;
            }
          } else if (data === SUSPENSE_END_DATA) {
            depth++;
          }
        }

        node = node.previousSibling;
      }

      return null;
    }

    function commitHydratedContainer(container) {
      // Retry if any event replaying was blocked on this.
      retryIfBlockedOn(container);
    }

    function commitHydratedSuspenseInstance(suspenseInstance) {
      // Retry if any event replaying was blocked on this.
      retryIfBlockedOn(suspenseInstance);
    }

    function didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, text) {
      {
        warnForUnmatchedText(textInstance, text);
      }
    }

    function didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, text) {
      if (parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {
        warnForUnmatchedText(textInstance, text);
      }
    }

    function didNotHydrateContainerInstance(parentContainer, instance) {
      {
        if (instance.nodeType === ELEMENT_NODE) {
          warnForDeletedHydratableElement(parentContainer, instance);
        } else if (instance.nodeType === COMMENT_NODE) ;else {
          warnForDeletedHydratableText(parentContainer, instance);
        }
      }
    }

    function didNotHydrateInstance(parentType, parentProps, parentInstance, instance) {
      if (parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {
        if (instance.nodeType === ELEMENT_NODE) {
          warnForDeletedHydratableElement(parentInstance, instance);
        } else if (instance.nodeType === COMMENT_NODE) ;else {
          warnForDeletedHydratableText(parentInstance, instance);
        }
      }
    }

    function didNotFindHydratableContainerInstance(parentContainer, type, props) {
      {
        warnForInsertedHydratedElement(parentContainer, type);
      }
    }

    function didNotFindHydratableContainerTextInstance(parentContainer, text) {
      {
        warnForInsertedHydratedText(parentContainer, text);
      }
    }

    function didNotFindHydratableInstance(parentType, parentProps, parentInstance, type, props) {
      if (parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {
        warnForInsertedHydratedElement(parentInstance, type);
      }
    }

    function didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, text) {
      if (parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {
        warnForInsertedHydratedText(parentInstance, text);
      }
    }

    function didNotFindHydratableSuspenseInstance(parentType, parentProps, parentInstance) {
      if (parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) ;
    }

    var randomKey = Math.random().toString(36).slice(2);
    var internalInstanceKey = '__reactInternalInstance$' + randomKey;
    var internalEventHandlersKey = '__reactEventHandlers$' + randomKey;
    var internalContainerInstanceKey = '__reactContainere$' + randomKey;

    function precacheFiberNode(hostInst, node) {
      node[internalInstanceKey] = hostInst;
    }

    function markContainerAsRoot(hostRoot, node) {
      node[internalContainerInstanceKey] = hostRoot;
    }

    function unmarkContainerAsRoot(node) {
      node[internalContainerInstanceKey] = null;
    }

    function isContainerMarkedAsRoot(node) {
      return !!node[internalContainerInstanceKey];
    } // Given a DOM node, return the closest HostComponent or HostText fiber ancestor.
    // If the target node is part of a hydrated or not yet rendered subtree, then
    // this may also return a SuspenseComponent or HostRoot to indicate that.
    // Conceptually the HostRoot fiber is a child of the Container node. So if you
    // pass the Container node as the targetNode, you will not actually get the
    // HostRoot back. To get to the HostRoot, you need to pass a child of it.
    // The same thing applies to Suspense boundaries.


    function getClosestInstanceFromNode(targetNode) {
      var targetInst = targetNode[internalInstanceKey];

      if (targetInst) {
        // Don't return HostRoot or SuspenseComponent here.
        return targetInst;
      } // If the direct event target isn't a React owned DOM node, we need to look
      // to see if one of its parents is a React owned DOM node.


      var parentNode = targetNode.parentNode;

      while (parentNode) {
        // We'll check if this is a container root that could include
        // React nodes in the future. We need to check this first because
        // if we're a child of a dehydrated container, we need to first
        // find that inner container before moving on to finding the parent
        // instance. Note that we don't check this field on  the targetNode
        // itself because the fibers are conceptually between the container
        // node and the first child. It isn't surrounding the container node.
        // If it's not a container, we check if it's an instance.
        targetInst = parentNode[internalContainerInstanceKey] || parentNode[internalInstanceKey];

        if (targetInst) {
          // Since this wasn't the direct target of the event, we might have
          // stepped past dehydrated DOM nodes to get here. However they could
          // also have been non-React nodes. We need to answer which one.
          // If we the instance doesn't have any children, then there can't be
          // a nested suspense boundary within it. So we can use this as a fast
          // bailout. Most of the time, when people add non-React children to
          // the tree, it is using a ref to a child-less DOM node.
          // Normally we'd only need to check one of the fibers because if it
          // has ever gone from having children to deleting them or vice versa
          // it would have deleted the dehydrated boundary nested inside already.
          // However, since the HostRoot starts out with an alternate it might
          // have one on the alternate so we need to check in case this was a
          // root.
          var alternate = targetInst.alternate;

          if (targetInst.child !== null || alternate !== null && alternate.child !== null) {
            // Next we need to figure out if the node that skipped past is
            // nested within a dehydrated boundary and if so, which one.
            var suspenseInstance = getParentSuspenseInstance(targetNode);

            while (suspenseInstance !== null) {
              // We found a suspense instance. That means that we haven't
              // hydrated it yet. Even though we leave the comments in the
              // DOM after hydrating, and there are boundaries in the DOM
              // that could already be hydrated, we wouldn't have found them
              // through this pass since if the target is hydrated it would
              // have had an internalInstanceKey on it.
              // Let's get the fiber associated with the SuspenseComponent
              // as the deepest instance.
              var targetSuspenseInst = suspenseInstance[internalInstanceKey];

              if (targetSuspenseInst) {
                return targetSuspenseInst;
              } // If we don't find a Fiber on the comment, it might be because
              // we haven't gotten to hydrate it yet. There might still be a
              // parent boundary that hasn't above this one so we need to find
              // the outer most that is known.


              suspenseInstance = getParentSuspenseInstance(suspenseInstance); // If we don't find one, then that should mean that the parent
              // host component also hasn't hydrated yet. We can return it
              // below since it will bail out on the isMounted check later.
            }
          }

          return targetInst;
        }

        targetNode = parentNode;
        parentNode = targetNode.parentNode;
      }

      return null;
    }
    /**
     * Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent
     * instance, or null if the node was not rendered by this React.
     */


    function getInstanceFromNode$1(node) {
      var inst = node[internalInstanceKey] || node[internalContainerInstanceKey];

      if (inst) {
        if (inst.tag === HostComponent || inst.tag === HostText || inst.tag === SuspenseComponent || inst.tag === HostRoot) {
          return inst;
        } else {
          return null;
        }
      }

      return null;
    }
    /**
     * Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding
     * DOM node.
     */


    function getNodeFromInstance$1(inst) {
      if (inst.tag === HostComponent || inst.tag === HostText) {
        // In Fiber this, is just the state node right now. We assume it will be
        // a host component or host text.
        return inst.stateNode;
      } // Without this first invariant, passing a non-DOM-component triggers the next
      // invariant for a missing parent, which is super confusing.


      {
        {
          throw Error("getNodeFromInstance: Invalid argument.");
        }
      }
    }

    function getFiberCurrentPropsFromNode$1(node) {
      return node[internalEventHandlersKey] || null;
    }

    function updateFiberProps(node, props) {
      node[internalEventHandlersKey] = props;
    }

    function getParent(inst) {
      do {
        inst = inst.return; // TODO: If this is a HostRoot we might want to bail out.
        // That is depending on if we want nested subtrees (layers) to bubble
        // events to their parent. We could also go through parentNode on the
        // host node but that wouldn't work for React Native and doesn't let us
        // do the portal feature.
      } while (inst && inst.tag !== HostComponent);

      if (inst) {
        return inst;
      }

      return null;
    }
    /**
     * Return the lowest common ancestor of A and B, or null if they are in
     * different trees.
     */


    function getLowestCommonAncestor(instA, instB) {
      var depthA = 0;

      for (var tempA = instA; tempA; tempA = getParent(tempA)) {
        depthA++;
      }

      var depthB = 0;

      for (var tempB = instB; tempB; tempB = getParent(tempB)) {
        depthB++;
      } // If A is deeper, crawl up.


      while (depthA - depthB > 0) {
        instA = getParent(instA);
        depthA--;
      } // If B is deeper, crawl up.


      while (depthB - depthA > 0) {
        instB = getParent(instB);
        depthB--;
      } // Walk in lockstep until we find a match.


      var depth = depthA;

      while (depth--) {
        if (instA === instB || instA === instB.alternate) {
          return instA;
        }

        instA = getParent(instA);
        instB = getParent(instB);
      }

      return null;
    }
    /**
     * Simulates the traversal of a two-phase, capture/bubble event dispatch.
     */


    function traverseTwoPhase(inst, fn, arg) {
      var path = [];

      while (inst) {
        path.push(inst);
        inst = getParent(inst);
      }

      var i;

      for (i = path.length; i-- > 0;) {
        fn(path[i], 'captured', arg);
      }

      for (i = 0; i < path.length; i++) {
        fn(path[i], 'bubbled', arg);
      }
    }
    /**
     * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that
     * should would receive a `mouseEnter` or `mouseLeave` event.
     *
     * Does not invoke the callback on the nearest common ancestor because nothing
     * "entered" or "left" that element.
     */


    function traverseEnterLeave(from, to, fn, argFrom, argTo) {
      var common = from && to ? getLowestCommonAncestor(from, to) : null;
      var pathFrom = [];

      while (true) {
        if (!from) {
          break;
        }

        if (from === common) {
          break;
        }

        var alternate = from.alternate;

        if (alternate !== null && alternate === common) {
          break;
        }

        pathFrom.push(from);
        from = getParent(from);
      }

      var pathTo = [];

      while (true) {
        if (!to) {
          break;
        }

        if (to === common) {
          break;
        }

        var _alternate = to.alternate;

        if (_alternate !== null && _alternate === common) {
          break;
        }

        pathTo.push(to);
        to = getParent(to);
      }

      for (var i = 0; i < pathFrom.length; i++) {
        fn(pathFrom[i], 'bubbled', argFrom);
      }

      for (var _i = pathTo.length; _i-- > 0;) {
        fn(pathTo[_i], 'captured', argTo);
      }
    }

    function isInteractive(tag) {
      return tag === 'button' || tag === 'input' || tag === 'select' || tag === 'textarea';
    }

    function shouldPreventMouseEvent(name, type, props) {
      switch (name) {
        case 'onClick':
        case 'onClickCapture':
        case 'onDoubleClick':
        case 'onDoubleClickCapture':
        case 'onMouseDown':
        case 'onMouseDownCapture':
        case 'onMouseMove':
        case 'onMouseMoveCapture':
        case 'onMouseUp':
        case 'onMouseUpCapture':
        case 'onMouseEnter':
          return !!(props.disabled && isInteractive(type));

        default:
          return false;
      }
    }
    /**
     * @param {object} inst The instance, which is the source of events.
     * @param {string} registrationName Name of listener (e.g. `onClick`).
     * @return {?function} The stored callback.
     */


    function getListener(inst, registrationName) {
      var listener; // TODO: shouldPreventMouseEvent is DOM-specific and definitely should not
      // live here; needs to be moved to a better place soon

      var stateNode = inst.stateNode;

      if (!stateNode) {
        // Work in progress (ex: onload events in incremental mode).
        return null;
      }

      var props = getFiberCurrentPropsFromNode(stateNode);

      if (!props) {
        // Work in progress.
        return null;
      }

      listener = props[registrationName];

      if (shouldPreventMouseEvent(registrationName, inst.type, props)) {
        return null;
      }

      if (!(!listener || typeof listener === 'function')) {
        {
          throw Error("Expected `" + registrationName + "` listener to be a function, instead got a value of `" + typeof listener + "` type.");
        }
      }

      return listener;
    }
    /**
     * Some event types have a notion of different registration names for different
     * "phases" of propagation. This finds listeners by a given phase.
     */


    function listenerAtPhase(inst, event, propagationPhase) {
      var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase];
      return getListener(inst, registrationName);
    }
    /**
     * A small set of propagation patterns, each of which will accept a small amount
     * of information, and generate a set of "dispatch ready event objects" - which
     * are sets of events that have already been annotated with a set of dispatched
     * listener functions/ids. The API is designed this way to discourage these
     * propagation strategies from actually executing the dispatches, since we
     * always want to collect the entire set of dispatches before executing even a
     * single one.
     */

    /**
     * Tags a `SyntheticEvent` with dispatched listeners. Creating this function
     * here, allows us to not have to bind or create functions for each event.
     * Mutating the event's members allows us to not have to create a wrapping
     * "dispatch" object that pairs the event with the listener.
     */


    function accumulateDirectionalDispatches(inst, phase, event) {
      {
        if (!inst) {
          error('Dispatching inst must not be null');
        }
      }
      var listener = listenerAtPhase(inst, event, phase);

      if (listener) {
        event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
        event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);
      }
    }
    /**
     * Collect dispatches (must be entirely collected before dispatching - see unit
     * tests). Lazily allocate the array to conserve memory.  We must loop through
     * each event and perform the traversal for each one. We cannot perform a
     * single traversal for the entire collection of events because each event may
     * have a different target.
     */


    function accumulateTwoPhaseDispatchesSingle(event) {
      if (event && event.dispatchConfig.phasedRegistrationNames) {
        traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event);
      }
    }
    /**
     * Accumulates without regard to direction, does not look for phased
     * registration names. Same as `accumulateDirectDispatchesSingle` but without
     * requiring that the `dispatchMarker` be the same as the dispatched ID.
     */


    function accumulateDispatches(inst, ignoredDirection, event) {
      if (inst && event && event.dispatchConfig.registrationName) {
        var registrationName = event.dispatchConfig.registrationName;
        var listener = getListener(inst, registrationName);

        if (listener) {
          event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
          event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);
        }
      }
    }
    /**
     * Accumulates dispatches on an `SyntheticEvent`, but only for the
     * `dispatchMarker`.
     * @param {SyntheticEvent} event
     */


    function accumulateDirectDispatchesSingle(event) {
      if (event && event.dispatchConfig.registrationName) {
        accumulateDispatches(event._targetInst, null, event);
      }
    }

    function accumulateTwoPhaseDispatches(events) {
      forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle);
    }

    function accumulateEnterLeaveDispatches(leave, enter, from, to) {
      traverseEnterLeave(from, to, accumulateDispatches, leave, enter);
    }

    function accumulateDirectDispatches(events) {
      forEachAccumulated(events, accumulateDirectDispatchesSingle);
    }
    /**
     * These variables store information about text content of a target node,
     * allowing comparison of content before and after a given event.
     *
     * Identify the node where selection currently begins, then observe
     * both its text content and its current position in the DOM. Since the
     * browser may natively replace the target node during composition, we can
     * use its position to find its replacement.
     *
     *
     */


    var root = null;
    var startText = null;
    var fallbackText = null;

    function initialize(nativeEventTarget) {
      root = nativeEventTarget;
      startText = getText();
      return true;
    }

    function reset() {
      root = null;
      startText = null;
      fallbackText = null;
    }

    function getData() {
      if (fallbackText) {
        return fallbackText;
      }

      var start;
      var startValue = startText;
      var startLength = startValue.length;
      var end;
      var endValue = getText();
      var endLength = endValue.length;

      for (start = 0; start < startLength; start++) {
        if (startValue[start] !== endValue[start]) {
          break;
        }
      }

      var minEnd = startLength - start;

      for (end = 1; end <= minEnd; end++) {
        if (startValue[startLength - end] !== endValue[endLength - end]) {
          break;
        }
      }

      var sliceTail = end > 1 ? 1 - end : undefined;
      fallbackText = endValue.slice(start, sliceTail);
      return fallbackText;
    }

    function getText() {
      if ('value' in root) {
        return root.value;
      }

      return root.textContent;
    }

    var EVENT_POOL_SIZE = 10;
    /**
     * @interface Event
     * @see http://www.w3.org/TR/DOM-Level-3-Events/
     */

    var EventInterface = {
      type: null,
      target: null,
      // currentTarget is set when dispatching; no use in copying it here
      currentTarget: function () {
        return null;
      },
      eventPhase: null,
      bubbles: null,
      cancelable: null,
      timeStamp: function (event) {
        return event.timeStamp || Date.now();
      },
      defaultPrevented: null,
      isTrusted: null
    };

    function functionThatReturnsTrue() {
      return true;
    }

    function functionThatReturnsFalse() {
      return false;
    }
    /**
     * Synthetic events are dispatched by event plugins, typically in response to a
     * top-level event delegation handler.
     *
     * These systems should generally use pooling to reduce the frequency of garbage
     * collection. The system should check `isPersistent` to determine whether the
     * event should be released into the pool after being dispatched. Users that
     * need a persisted event should invoke `persist`.
     *
     * Synthetic events (and subclasses) implement the DOM Level 3 Events API by
     * normalizing browser quirks. Subclasses do not necessarily have to implement a
     * DOM interface; custom application-specific events can also subclass this.
     *
     * @param {object} dispatchConfig Configuration used to dispatch this event.
     * @param {*} targetInst Marker identifying the event target.
     * @param {object} nativeEvent Native browser event.
     * @param {DOMEventTarget} nativeEventTarget Target node.
     */


    function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) {
      {
        // these have a getter/setter for warnings
        delete this.nativeEvent;
        delete this.preventDefault;
        delete this.stopPropagation;
        delete this.isDefaultPrevented;
        delete this.isPropagationStopped;
      }
      this.dispatchConfig = dispatchConfig;
      this._targetInst = targetInst;
      this.nativeEvent = nativeEvent;
      var Interface = this.constructor.Interface;

      for (var propName in Interface) {
        if (!Interface.hasOwnProperty(propName)) {
          continue;
        }

        {
          delete this[propName]; // this has a getter/setter for warnings
        }
        var normalize = Interface[propName];

        if (normalize) {
          this[propName] = normalize(nativeEvent);
        } else {
          if (propName === 'target') {
            this.target = nativeEventTarget;
          } else {
            this[propName] = nativeEvent[propName];
          }
        }
      }

      var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false;

      if (defaultPrevented) {
        this.isDefaultPrevented = functionThatReturnsTrue;
      } else {
        this.isDefaultPrevented = functionThatReturnsFalse;
      }

      this.isPropagationStopped = functionThatReturnsFalse;
      return this;
    }

    _assign(SyntheticEvent.prototype, {
      preventDefault: function () {
        this.defaultPrevented = true;
        var event = this.nativeEvent;

        if (!event) {
          return;
        }

        if (event.preventDefault) {
          event.preventDefault();
        } else if (typeof event.returnValue !== 'unknown') {
          event.returnValue = false;
        }

        this.isDefaultPrevented = functionThatReturnsTrue;
      },
      stopPropagation: function () {
        var event = this.nativeEvent;

        if (!event) {
          return;
        }

        if (event.stopPropagation) {
          event.stopPropagation();
        } else if (typeof event.cancelBubble !== 'unknown') {
          // The ChangeEventPlugin registers a "propertychange" event for
          // IE. This event does not support bubbling or cancelling, and
          // any references to cancelBubble throw "Member not found".  A
          // typeof check of "unknown" circumvents this issue (and is also
          // IE specific).
          event.cancelBubble = true;
        }

        this.isPropagationStopped = functionThatReturnsTrue;
      },

      /**
       * We release all dispatched `SyntheticEvent`s after each event loop, adding
       * them back into the pool. This allows a way to hold onto a reference that
       * won't be added back into the pool.
       */
      persist: function () {
        this.isPersistent = functionThatReturnsTrue;
      },

      /**
       * Checks if this event should be released back into the pool.
       *
       * @return {boolean} True if this should not be released, false otherwise.
       */
      isPersistent: functionThatReturnsFalse,

      /**
       * `PooledClass` looks for `destructor` on each instance it releases.
       */
      destructor: function () {
        var Interface = this.constructor.Interface;

        for (var propName in Interface) {
          {
            Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName]));
          }
        }

        this.dispatchConfig = null;
        this._targetInst = null;
        this.nativeEvent = null;
        this.isDefaultPrevented = functionThatReturnsFalse;
        this.isPropagationStopped = functionThatReturnsFalse;
        this._dispatchListeners = null;
        this._dispatchInstances = null;
        {
          Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null));
          Object.defineProperty(this, 'isDefaultPrevented', getPooledWarningPropertyDefinition('isDefaultPrevented', functionThatReturnsFalse));
          Object.defineProperty(this, 'isPropagationStopped', getPooledWarningPropertyDefinition('isPropagationStopped', functionThatReturnsFalse));
          Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', function () {}));
          Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', function () {}));
        }
      }
    });

    SyntheticEvent.Interface = EventInterface;
    /**
     * Helper to reduce boilerplate when creating subclasses.
     */

    SyntheticEvent.extend = function (Interface) {
      var Super = this;

      var E = function () {};

      E.prototype = Super.prototype;
      var prototype = new E();

      function Class() {
        return Super.apply(this, arguments);
      }

      _assign(prototype, Class.prototype);

      Class.prototype = prototype;
      Class.prototype.constructor = Class;
      Class.Interface = _assign({}, Super.Interface, Interface);
      Class.extend = Super.extend;
      addEventPoolingTo(Class);
      return Class;
    };

    addEventPoolingTo(SyntheticEvent);
    /**
     * Helper to nullify syntheticEvent instance properties when destructing
     *
     * @param {String} propName
     * @param {?object} getVal
     * @return {object} defineProperty object
     */

    function getPooledWarningPropertyDefinition(propName, getVal) {
      var isFunction = typeof getVal === 'function';
      return {
        configurable: true,
        set: set,
        get: get
      };

      function set(val) {
        var action = isFunction ? 'setting the method' : 'setting the property';
        warn(action, 'This is effectively a no-op');
        return val;
      }

      function get() {
        var action = isFunction ? 'accessing the method' : 'accessing the property';
        var result = isFunction ? 'This is a no-op function' : 'This is set to null';
        warn(action, result);
        return getVal;
      }

      function warn(action, result) {
        {
          error("This synthetic event is reused for performance reasons. If you're seeing this, " + "you're %s `%s` on a released/nullified synthetic event. %s. " + 'If you must keep the original synthetic event around, use event.persist(). ' + 'See https://fb.me/react-event-pooling for more information.', action, propName, result);
        }
      }
    }

    function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) {
      var EventConstructor = this;

      if (EventConstructor.eventPool.length) {
        var instance = EventConstructor.eventPool.pop();
        EventConstructor.call(instance, dispatchConfig, targetInst, nativeEvent, nativeInst);
        return instance;
      }

      return new EventConstructor(dispatchConfig, targetInst, nativeEvent, nativeInst);
    }

    function releasePooledEvent(event) {
      var EventConstructor = this;

      if (!(event instanceof EventConstructor)) {
        {
          throw Error("Trying to release an event instance into a pool of a different type.");
        }
      }

      event.destructor();

      if (EventConstructor.eventPool.length < EVENT_POOL_SIZE) {
        EventConstructor.eventPool.push(event);
      }
    }

    function addEventPoolingTo(EventConstructor) {
      EventConstructor.eventPool = [];
      EventConstructor.getPooled = getPooledEvent;
      EventConstructor.release = releasePooledEvent;
    }
    /**
     * @interface Event
     * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents
     */


    var SyntheticCompositionEvent = SyntheticEvent.extend({
      data: null
    });
    /**
     * @interface Event
     * @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105
     *      /#events-inputevents
     */

    var SyntheticInputEvent = SyntheticEvent.extend({
      data: null
    });
    var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space

    var START_KEYCODE = 229;
    var canUseCompositionEvent = canUseDOM && 'CompositionEvent' in window;
    var documentMode = null;

    if (canUseDOM && 'documentMode' in document) {
      documentMode = document.documentMode;
    } // Webkit offers a very useful `textInput` event that can be used to
    // directly represent `beforeInput`. The IE `textinput` event is not as
    // useful, so we don't use it.


    var canUseTextInputEvent = canUseDOM && 'TextEvent' in window && !documentMode; // In IE9+, we have access to composition events, but the data supplied
    // by the native compositionend event may be incorrect. Japanese ideographic
    // spaces, for instance (\u3000) are not recorded correctly.

    var useFallbackCompositionData = canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11);
    var SPACEBAR_CODE = 32;
    var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE); // Events and their corresponding property names.

    var eventTypes = {
      beforeInput: {
        phasedRegistrationNames: {
          bubbled: 'onBeforeInput',
          captured: 'onBeforeInputCapture'
        },
        dependencies: [TOP_COMPOSITION_END, TOP_KEY_PRESS, TOP_TEXT_INPUT, TOP_PASTE]
      },
      compositionEnd: {
        phasedRegistrationNames: {
          bubbled: 'onCompositionEnd',
          captured: 'onCompositionEndCapture'
        },
        dependencies: [TOP_BLUR, TOP_COMPOSITION_END, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN]
      },
      compositionStart: {
        phasedRegistrationNames: {
          bubbled: 'onCompositionStart',
          captured: 'onCompositionStartCapture'
        },
        dependencies: [TOP_BLUR, TOP_COMPOSITION_START, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN]
      },
      compositionUpdate: {
        phasedRegistrationNames: {
          bubbled: 'onCompositionUpdate',
          captured: 'onCompositionUpdateCapture'
        },
        dependencies: [TOP_BLUR, TOP_COMPOSITION_UPDATE, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN]
      }
    }; // Track whether we've ever handled a keypress on the space key.

    var hasSpaceKeypress = false;
    /**
     * Return whether a native keypress event is assumed to be a command.
     * This is required because Firefox fires `keypress` events for key commands
     * (cut, copy, select-all, etc.) even though no character is inserted.
     */

    function isKeypressCommand(nativeEvent) {
      return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) && // ctrlKey && altKey is equivalent to AltGr, and is not a command.
      !(nativeEvent.ctrlKey && nativeEvent.altKey);
    }
    /**
     * Translate native top level events into event types.
     *
     * @param {string} topLevelType
     * @return {object}
     */


    function getCompositionEventType(topLevelType) {
      switch (topLevelType) {
        case TOP_COMPOSITION_START:
          return eventTypes.compositionStart;

        case TOP_COMPOSITION_END:
          return eventTypes.compositionEnd;

        case TOP_COMPOSITION_UPDATE:
          return eventTypes.compositionUpdate;
      }
    }
    /**
     * Does our fallback best-guess model think this event signifies that
     * composition has begun?
     *
     * @param {string} topLevelType
     * @param {object} nativeEvent
     * @return {boolean}
     */


    function isFallbackCompositionStart(topLevelType, nativeEvent) {
      return topLevelType === TOP_KEY_DOWN && nativeEvent.keyCode === START_KEYCODE;
    }
    /**
     * Does our fallback mode think that this event is the end of composition?
     *
     * @param {string} topLevelType
     * @param {object} nativeEvent
     * @return {boolean}
     */


    function isFallbackCompositionEnd(topLevelType, nativeEvent) {
      switch (topLevelType) {
        case TOP_KEY_UP:
          // Command keys insert or clear IME input.
          return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1;

        case TOP_KEY_DOWN:
          // Expect IME keyCode on each keydown. If we get any other
          // code we must have exited earlier.
          return nativeEvent.keyCode !== START_KEYCODE;

        case TOP_KEY_PRESS:
        case TOP_MOUSE_DOWN:
        case TOP_BLUR:
          // Events are not possible without cancelling IME.
          return true;

        default:
          return false;
      }
    }
    /**
     * Google Input Tools provides composition data via a CustomEvent,
     * with the `data` property populated in the `detail` object. If this
     * is available on the event object, use it. If not, this is a plain
     * composition event and we have nothing special to extract.
     *
     * @param {object} nativeEvent
     * @return {?string}
     */


    function getDataFromCustomEvent(nativeEvent) {
      var detail = nativeEvent.detail;

      if (typeof detail === 'object' && 'data' in detail) {
        return detail.data;
      }

      return null;
    }
    /**
     * Check if a composition event was triggered by Korean IME.
     * Our fallback mode does not work well with IE's Korean IME,
     * so just use native composition events when Korean IME is used.
     * Although CompositionEvent.locale property is deprecated,
     * it is available in IE, where our fallback mode is enabled.
     *
     * @param {object} nativeEvent
     * @return {boolean}
     */


    function isUsingKoreanIME(nativeEvent) {
      return nativeEvent.locale === 'ko';
    } // Track the current IME composition status, if any.


    var isComposing = false;
    /**
     * @return {?object} A SyntheticCompositionEvent.
     */

    function extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
      var eventType;
      var fallbackData;

      if (canUseCompositionEvent) {
        eventType = getCompositionEventType(topLevelType);
      } else if (!isComposing) {
        if (isFallbackCompositionStart(topLevelType, nativeEvent)) {
          eventType = eventTypes.compositionStart;
        }
      } else if (isFallbackCompositionEnd(topLevelType, nativeEvent)) {
        eventType = eventTypes.compositionEnd;
      }

      if (!eventType) {
        return null;
      }

      if (useFallbackCompositionData && !isUsingKoreanIME(nativeEvent)) {
        // The current composition is stored statically and must not be
        // overwritten while composition continues.
        if (!isComposing && eventType === eventTypes.compositionStart) {
          isComposing = initialize(nativeEventTarget);
        } else if (eventType === eventTypes.compositionEnd) {
          if (isComposing) {
            fallbackData = getData();
          }
        }
      }

      var event = SyntheticCompositionEvent.getPooled(eventType, targetInst, nativeEvent, nativeEventTarget);

      if (fallbackData) {
        // Inject data generated from fallback path into the synthetic event.
        // This matches the property of native CompositionEventInterface.
        event.data = fallbackData;
      } else {
        var customData = getDataFromCustomEvent(nativeEvent);

        if (customData !== null) {
          event.data = customData;
        }
      }

      accumulateTwoPhaseDispatches(event);
      return event;
    }
    /**
     * @param {TopLevelType} topLevelType Number from `TopLevelType`.
     * @param {object} nativeEvent Native browser event.
     * @return {?string} The string corresponding to this `beforeInput` event.
     */


    function getNativeBeforeInputChars(topLevelType, nativeEvent) {
      switch (topLevelType) {
        case TOP_COMPOSITION_END:
          return getDataFromCustomEvent(nativeEvent);

        case TOP_KEY_PRESS:
          /**
           * If native `textInput` events are available, our goal is to make
           * use of them. However, there is a special case: the spacebar key.
           * In Webkit, preventing default on a spacebar `textInput` event
           * cancels character insertion, but it *also* causes the browser
           * to fall back to its default spacebar behavior of scrolling the
           * page.
           *
           * Tracking at:
           * https://code.google.com/p/chromium/issues/detail?id=355103
           *
           * To avoid this issue, use the keypress event as if no `textInput`
           * event is available.
           */
          var which = nativeEvent.which;

          if (which !== SPACEBAR_CODE) {
            return null;
          }

          hasSpaceKeypress = true;
          return SPACEBAR_CHAR;

        case TOP_TEXT_INPUT:
          // Record the characters to be added to the DOM.
          var chars = nativeEvent.data; // If it's a spacebar character, assume that we have already handled
          // it at the keypress level and bail immediately. Android Chrome
          // doesn't give us keycodes, so we need to ignore it.

          if (chars === SPACEBAR_CHAR && hasSpaceKeypress) {
            return null;
          }

          return chars;

        default:
          // For other native event types, do nothing.
          return null;
      }
    }
    /**
     * For browsers that do not provide the `textInput` event, extract the
     * appropriate string to use for SyntheticInputEvent.
     *
     * @param {number} topLevelType Number from `TopLevelEventTypes`.
     * @param {object} nativeEvent Native browser event.
     * @return {?string} The fallback string for this `beforeInput` event.
     */


    function getFallbackBeforeInputChars(topLevelType, nativeEvent) {
      // If we are currently composing (IME) and using a fallback to do so,
      // try to extract the composed characters from the fallback object.
      // If composition event is available, we extract a string only at
      // compositionevent, otherwise extract it at fallback events.
      if (isComposing) {
        if (topLevelType === TOP_COMPOSITION_END || !canUseCompositionEvent && isFallbackCompositionEnd(topLevelType, nativeEvent)) {
          var chars = getData();
          reset();
          isComposing = false;
          return chars;
        }

        return null;
      }

      switch (topLevelType) {
        case TOP_PASTE:
          // If a paste event occurs after a keypress, throw out the input
          // chars. Paste events should not lead to BeforeInput events.
          return null;

        case TOP_KEY_PRESS:
          /**
           * As of v27, Firefox may fire keypress events even when no character
           * will be inserted. A few possibilities:
           *
           * - `which` is `0`. Arrow keys, Esc key, etc.
           *
           * - `which` is the pressed key code, but no char is available.
           *   Ex: 'AltGr + d` in Polish. There is no modified character for
           *   this key combination and no character is inserted into the
           *   document, but FF fires the keypress for char code `100` anyway.
           *   No `input` event will occur.
           *
           * - `which` is the pressed key code, but a command combination is
           *   being used. Ex: `Cmd+C`. No character is inserted, and no
           *   `input` event will occur.
           */
          if (!isKeypressCommand(nativeEvent)) {
            // IE fires the `keypress` event when a user types an emoji via
            // Touch keyboard of Windows.  In such a case, the `char` property
            // holds an emoji character like `\uD83D\uDE0A`.  Because its length
            // is 2, the property `which` does not represent an emoji correctly.
            // In such a case, we directly return the `char` property instead of
            // using `which`.
            if (nativeEvent.char && nativeEvent.char.length > 1) {
              return nativeEvent.char;
            } else if (nativeEvent.which) {
              return String.fromCharCode(nativeEvent.which);
            }
          }

          return null;

        case TOP_COMPOSITION_END:
          return useFallbackCompositionData && !isUsingKoreanIME(nativeEvent) ? null : nativeEvent.data;

        default:
          return null;
      }
    }
    /**
     * Extract a SyntheticInputEvent for `beforeInput`, based on either native
     * `textInput` or fallback behavior.
     *
     * @return {?object} A SyntheticInputEvent.
     */


    function extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
      var chars;

      if (canUseTextInputEvent) {
        chars = getNativeBeforeInputChars(topLevelType, nativeEvent);
      } else {
        chars = getFallbackBeforeInputChars(topLevelType, nativeEvent);
      } // If no characters are being inserted, no BeforeInput event should
      // be fired.


      if (!chars) {
        return null;
      }

      var event = SyntheticInputEvent.getPooled(eventTypes.beforeInput, targetInst, nativeEvent, nativeEventTarget);
      event.data = chars;
      accumulateTwoPhaseDispatches(event);
      return event;
    }
    /**
     * Create an `onBeforeInput` event to match
     * http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents.
     *
     * This event plugin is based on the native `textInput` event
     * available in Chrome, Safari, Opera, and IE. This event fires after
     * `onKeyPress` and `onCompositionEnd`, but before `onInput`.
     *
     * `beforeInput` is spec'd but not implemented in any browsers, and
     * the `input` event does not provide any useful information about what has
     * actually been added, contrary to the spec. Thus, `textInput` is the best
     * available event to identify the characters that have actually been inserted
     * into the target node.
     *
     * This plugin is also responsible for emitting `composition` events, thus
     * allowing us to share composition fallback code for both `beforeInput` and
     * `composition` event types.
     */


    var BeforeInputEventPlugin = {
      eventTypes: eventTypes,
      extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {
        var composition = extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget);
        var beforeInput = extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget);

        if (composition === null) {
          return beforeInput;
        }

        if (beforeInput === null) {
          return composition;
        }

        return [composition, beforeInput];
      }
    };
    /**
     * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary
     */

    var supportedInputTypes = {
      color: true,
      date: true,
      datetime: true,
      'datetime-local': true,
      email: true,
      month: true,
      number: true,
      password: true,
      range: true,
      search: true,
      tel: true,
      text: true,
      time: true,
      url: true,
      week: true
    };

    function isTextInputElement(elem) {
      var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();

      if (nodeName === 'input') {
        return !!supportedInputTypes[elem.type];
      }

      if (nodeName === 'textarea') {
        return true;
      }

      return false;
    }

    var eventTypes$1 = {
      change: {
        phasedRegistrationNames: {
          bubbled: 'onChange',
          captured: 'onChangeCapture'
        },
        dependencies: [TOP_BLUR, TOP_CHANGE, TOP_CLICK, TOP_FOCUS, TOP_INPUT, TOP_KEY_DOWN, TOP_KEY_UP, TOP_SELECTION_CHANGE]
      }
    };

    function createAndAccumulateChangeEvent(inst, nativeEvent, target) {
      var event = SyntheticEvent.getPooled(eventTypes$1.change, inst, nativeEvent, target);
      event.type = 'change'; // Flag this event loop as needing state restore.

      enqueueStateRestore(target);
      accumulateTwoPhaseDispatches(event);
      return event;
    }
    /**
     * For IE shims
     */


    var activeElement = null;
    var activeElementInst = null;
    /**
     * SECTION: handle `change` event
     */

    function shouldUseChangeEvent(elem) {
      var nodeName = elem.nodeName && elem.nodeName.toLowerCase();
      return nodeName === 'select' || nodeName === 'input' && elem.type === 'file';
    }

    function manualDispatchChangeEvent(nativeEvent) {
      var event = createAndAccumulateChangeEvent(activeElementInst, nativeEvent, getEventTarget(nativeEvent)); // If change and propertychange bubbled, we'd just bind to it like all the
      // other events and have it go through ReactBrowserEventEmitter. Since it
      // doesn't, we manually listen for the events and so we have to enqueue and
      // process the abstract event manually.
      //
      // Batching is necessary here in order to ensure that all event handlers run
      // before the next rerender (including event handlers attached to ancestor
      // elements instead of directly on the input). Without this, controlled
      // components don't work properly in conjunction with event bubbling because
      // the component is rerendered and the value reverted before all the event
      // handlers can run. See https://github.com/facebook/react/issues/708.

      batchedUpdates(runEventInBatch, event);
    }

    function runEventInBatch(event) {
      runEventsInBatch(event);
    }

    function getInstIfValueChanged(targetInst) {
      var targetNode = getNodeFromInstance$1(targetInst);

      if (updateValueIfChanged(targetNode)) {
        return targetInst;
      }
    }

    function getTargetInstForChangeEvent(topLevelType, targetInst) {
      if (topLevelType === TOP_CHANGE) {
        return targetInst;
      }
    }
    /**
     * SECTION: handle `input` event
     */


    var isInputEventSupported = false;

    if (canUseDOM) {
      // IE9 claims to support the input event but fails to trigger it when
      // deleting text, so we ignore its input events.
      isInputEventSupported = isEventSupported('input') && (!document.documentMode || document.documentMode > 9);
    }
    /**
     * (For IE <=9) Starts tracking propertychange events on the passed-in element
     * and override the value property so that we can distinguish user events from
     * value changes in JS.
     */


    function startWatchingForValueChange(target, targetInst) {
      activeElement = target;
      activeElementInst = targetInst;
      activeElement.attachEvent('onpropertychange', handlePropertyChange);
    }
    /**
     * (For IE <=9) Removes the event listeners from the currently-tracked element,
     * if any exists.
     */


    function stopWatchingForValueChange() {
      if (!activeElement) {
        return;
      }

      activeElement.detachEvent('onpropertychange', handlePropertyChange);
      activeElement = null;
      activeElementInst = null;
    }
    /**
     * (For IE <=9) Handles a propertychange event, sending a `change` event if
     * the value of the active element has changed.
     */


    function handlePropertyChange(nativeEvent) {
      if (nativeEvent.propertyName !== 'value') {
        return;
      }

      if (getInstIfValueChanged(activeElementInst)) {
        manualDispatchChangeEvent(nativeEvent);
      }
    }

    function handleEventsForInputEventPolyfill(topLevelType, target, targetInst) {
      if (topLevelType === TOP_FOCUS) {
        // In IE9, propertychange fires for most input events but is buggy and
        // doesn't fire when text is deleted, but conveniently, selectionchange
        // appears to fire in all of the remaining cases so we catch those and
        // forward the event if the value has changed
        // In either case, we don't want to call the event handler if the value
        // is changed from JS so we redefine a setter for `.value` that updates
        // our activeElementValue variable, allowing us to ignore those changes
        //
        // stopWatching() should be a noop here but we call it just in case we
        // missed a blur event somehow.
        stopWatchingForValueChange();
        startWatchingForValueChange(target, targetInst);
      } else if (topLevelType === TOP_BLUR) {
        stopWatchingForValueChange();
      }
    } // For IE8 and IE9.


    function getTargetInstForInputEventPolyfill(topLevelType, targetInst) {
      if (topLevelType === TOP_SELECTION_CHANGE || topLevelType === TOP_KEY_UP || topLevelType === TOP_KEY_DOWN) {
        // On the selectionchange event, the target is just document which isn't
        // helpful for us so just check activeElement instead.
        //
        // 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire
        // propertychange on the first input event after setting `value` from a
        // script and fires only keydown, keypress, keyup. Catching keyup usually
        // gets it and catching keydown lets us fire an event for the first
        // keystroke if user does a key repeat (it'll be a little delayed: right
        // before the second keystroke). Other input methods (e.g., paste) seem to
        // fire selectionchange normally.
        return getInstIfValueChanged(activeElementInst);
      }
    }
    /**
     * SECTION: handle `click` event
     */


    function shouldUseClickEvent(elem) {
      // Use the `click` event to detect changes to checkbox and radio inputs.
      // This approach works across all browsers, whereas `change` does not fire
      // until `blur` in IE8.
      var nodeName = elem.nodeName;
      return nodeName && nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio');
    }

    function getTargetInstForClickEvent(topLevelType, targetInst) {
      if (topLevelType === TOP_CLICK) {
        return getInstIfValueChanged(targetInst);
      }
    }

    function getTargetInstForInputOrChangeEvent(topLevelType, targetInst) {
      if (topLevelType === TOP_INPUT || topLevelType === TOP_CHANGE) {
        return getInstIfValueChanged(targetInst);
      }
    }

    function handleControlledInputBlur(node) {
      var state = node._wrapperState;

      if (!state || !state.controlled || node.type !== 'number') {
        return;
      }

      {
        // If controlled, assign the value attribute to the current value on blur
        setDefaultValue(node, 'number', node.value);
      }
    }
    /**
     * This plugin creates an `onChange` event that normalizes change events
     * across form elements. This event fires at a time when it's possible to
     * change the element's value without seeing a flicker.
     *
     * Supported elements are:
     * - input (see `isTextInputElement`)
     * - textarea
     * - select
     */


    var ChangeEventPlugin = {
      eventTypes: eventTypes$1,
      _isInputEventSupported: isInputEventSupported,
      extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {
        var targetNode = targetInst ? getNodeFromInstance$1(targetInst) : window;
        var getTargetInstFunc, handleEventFunc;

        if (shouldUseChangeEvent(targetNode)) {
          getTargetInstFunc = getTargetInstForChangeEvent;
        } else if (isTextInputElement(targetNode)) {
          if (isInputEventSupported) {
            getTargetInstFunc = getTargetInstForInputOrChangeEvent;
          } else {
            getTargetInstFunc = getTargetInstForInputEventPolyfill;
            handleEventFunc = handleEventsForInputEventPolyfill;
          }
        } else if (shouldUseClickEvent(targetNode)) {
          getTargetInstFunc = getTargetInstForClickEvent;
        }

        if (getTargetInstFunc) {
          var inst = getTargetInstFunc(topLevelType, targetInst);

          if (inst) {
            var event = createAndAccumulateChangeEvent(inst, nativeEvent, nativeEventTarget);
            return event;
          }
        }

        if (handleEventFunc) {
          handleEventFunc(topLevelType, targetNode, targetInst);
        } // When blurring, set the value attribute for number inputs


        if (topLevelType === TOP_BLUR) {
          handleControlledInputBlur(targetNode);
        }
      }
    };
    var SyntheticUIEvent = SyntheticEvent.extend({
      view: null,
      detail: null
    });
    /**
     * Translation from modifier key to the associated property in the event.
     * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers
     */

    var modifierKeyToProp = {
      Alt: 'altKey',
      Control: 'ctrlKey',
      Meta: 'metaKey',
      Shift: 'shiftKey'
    }; // Older browsers (Safari <= 10, iOS Safari <= 10.2) do not support
    // getModifierState. If getModifierState is not supported, we map it to a set of
    // modifier keys exposed by the event. In this case, Lock-keys are not supported.

    function modifierStateGetter(keyArg) {
      var syntheticEvent = this;
      var nativeEvent = syntheticEvent.nativeEvent;

      if (nativeEvent.getModifierState) {
        return nativeEvent.getModifierState(keyArg);
      }

      var keyProp = modifierKeyToProp[keyArg];
      return keyProp ? !!nativeEvent[keyProp] : false;
    }

    function getEventModifierState(nativeEvent) {
      return modifierStateGetter;
    }

    var previousScreenX = 0;
    var previousScreenY = 0; // Use flags to signal movementX/Y has already been set

    var isMovementXSet = false;
    var isMovementYSet = false;
    /**
     * @interface MouseEvent
     * @see http://www.w3.org/TR/DOM-Level-3-Events/
     */

    var SyntheticMouseEvent = SyntheticUIEvent.extend({
      screenX: null,
      screenY: null,
      clientX: null,
      clientY: null,
      pageX: null,
      pageY: null,
      ctrlKey: null,
      shiftKey: null,
      altKey: null,
      metaKey: null,
      getModifierState: getEventModifierState,
      button: null,
      buttons: null,
      relatedTarget: function (event) {
        return event.relatedTarget || (event.fromElement === event.srcElement ? event.toElement : event.fromElement);
      },
      movementX: function (event) {
        if ('movementX' in event) {
          return event.movementX;
        }

        var screenX = previousScreenX;
        previousScreenX = event.screenX;

        if (!isMovementXSet) {
          isMovementXSet = true;
          return 0;
        }

        return event.type === 'mousemove' ? event.screenX - screenX : 0;
      },
      movementY: function (event) {
        if ('movementY' in event) {
          return event.movementY;
        }

        var screenY = previousScreenY;
        previousScreenY = event.screenY;

        if (!isMovementYSet) {
          isMovementYSet = true;
          return 0;
        }

        return event.type === 'mousemove' ? event.screenY - screenY : 0;
      }
    });
    /**
     * @interface PointerEvent
     * @see http://www.w3.org/TR/pointerevents/
     */

    var SyntheticPointerEvent = SyntheticMouseEvent.extend({
      pointerId: null,
      width: null,
      height: null,
      pressure: null,
      tangentialPressure: null,
      tiltX: null,
      tiltY: null,
      twist: null,
      pointerType: null,
      isPrimary: null
    });
    var eventTypes$2 = {
      mouseEnter: {
        registrationName: 'onMouseEnter',
        dependencies: [TOP_MOUSE_OUT, TOP_MOUSE_OVER]
      },
      mouseLeave: {
        registrationName: 'onMouseLeave',
        dependencies: [TOP_MOUSE_OUT, TOP_MOUSE_OVER]
      },
      pointerEnter: {
        registrationName: 'onPointerEnter',
        dependencies: [TOP_POINTER_OUT, TOP_POINTER_OVER]
      },
      pointerLeave: {
        registrationName: 'onPointerLeave',
        dependencies: [TOP_POINTER_OUT, TOP_POINTER_OVER]
      }
    };
    var EnterLeaveEventPlugin = {
      eventTypes: eventTypes$2,

      /**
       * For almost every interaction we care about, there will be both a top-level
       * `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that
       * we do not extract duplicate events. However, moving the mouse into the
       * browser from outside will not fire a `mouseout` event. In this case, we use
       * the `mouseover` top-level event.
       */
      extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {
        var isOverEvent = topLevelType === TOP_MOUSE_OVER || topLevelType === TOP_POINTER_OVER;
        var isOutEvent = topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_POINTER_OUT;

        if (isOverEvent && (eventSystemFlags & IS_REPLAYED) === 0 && (nativeEvent.relatedTarget || nativeEvent.fromElement)) {
          // If this is an over event with a target, then we've already dispatched
          // the event in the out event of the other target. If this is replayed,
          // then it's because we couldn't dispatch against this target previously
          // so we have to do it now instead.
          return null;
        }

        if (!isOutEvent && !isOverEvent) {
          // Must not be a mouse or pointer in or out - ignoring.
          return null;
        }

        var win;

        if (nativeEventTarget.window === nativeEventTarget) {
          // `nativeEventTarget` is probably a window object.
          win = nativeEventTarget;
        } else {
          // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
          var doc = nativeEventTarget.ownerDocument;

          if (doc) {
            win = doc.defaultView || doc.parentWindow;
          } else {
            win = window;
          }
        }

        var from;
        var to;

        if (isOutEvent) {
          from = targetInst;
          var related = nativeEvent.relatedTarget || nativeEvent.toElement;
          to = related ? getClosestInstanceFromNode(related) : null;

          if (to !== null) {
            var nearestMounted = getNearestMountedFiber(to);

            if (to !== nearestMounted || to.tag !== HostComponent && to.tag !== HostText) {
              to = null;
            }
          }
        } else {
          // Moving to a node from outside the window.
          from = null;
          to = targetInst;
        }

        if (from === to) {
          // Nothing pertains to our managed components.
          return null;
        }

        var eventInterface, leaveEventType, enterEventType, eventTypePrefix;

        if (topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_MOUSE_OVER) {
          eventInterface = SyntheticMouseEvent;
          leaveEventType = eventTypes$2.mouseLeave;
          enterEventType = eventTypes$2.mouseEnter;
          eventTypePrefix = 'mouse';
        } else if (topLevelType === TOP_POINTER_OUT || topLevelType === TOP_POINTER_OVER) {
          eventInterface = SyntheticPointerEvent;
          leaveEventType = eventTypes$2.pointerLeave;
          enterEventType = eventTypes$2.pointerEnter;
          eventTypePrefix = 'pointer';
        }

        var fromNode = from == null ? win : getNodeFromInstance$1(from);
        var toNode = to == null ? win : getNodeFromInstance$1(to);
        var leave = eventInterface.getPooled(leaveEventType, from, nativeEvent, nativeEventTarget);
        leave.type = eventTypePrefix + 'leave';
        leave.target = fromNode;
        leave.relatedTarget = toNode;
        var enter = eventInterface.getPooled(enterEventType, to, nativeEvent, nativeEventTarget);
        enter.type = eventTypePrefix + 'enter';
        enter.target = toNode;
        enter.relatedTarget = fromNode;
        accumulateEnterLeaveDispatches(leave, enter, from, to); // If we are not processing the first ancestor, then we
        // should not process the same nativeEvent again, as we
        // will have already processed it in the first ancestor.

        if ((eventSystemFlags & IS_FIRST_ANCESTOR) === 0) {
          return [leave];
        }

        return [leave, enter];
      }
    };
    /**
     * inlined Object.is polyfill to avoid requiring consumers ship their own
     * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
     */

    function is(x, y) {
      return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
      ;
    }

    var objectIs = typeof Object.is === 'function' ? Object.is : is;
    var hasOwnProperty$2 = Object.prototype.hasOwnProperty;
    /**
     * Performs equality by iterating through keys on an object and returning false
     * when any key has values which are not strictly equal between the arguments.
     * Returns true when the values of all keys are strictly equal.
     */

    function shallowEqual(objA, objB) {
      if (objectIs(objA, objB)) {
        return true;
      }

      if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
        return false;
      }

      var keysA = Object.keys(objA);
      var keysB = Object.keys(objB);

      if (keysA.length !== keysB.length) {
        return false;
      } // Test for A's keys different from B.


      for (var i = 0; i < keysA.length; i++) {
        if (!hasOwnProperty$2.call(objB, keysA[i]) || !objectIs(objA[keysA[i]], objB[keysA[i]])) {
          return false;
        }
      }

      return true;
    }

    var skipSelectionChangeEvent = canUseDOM && 'documentMode' in document && document.documentMode <= 11;
    var eventTypes$3 = {
      select: {
        phasedRegistrationNames: {
          bubbled: 'onSelect',
          captured: 'onSelectCapture'
        },
        dependencies: [TOP_BLUR, TOP_CONTEXT_MENU, TOP_DRAG_END, TOP_FOCUS, TOP_KEY_DOWN, TOP_KEY_UP, TOP_MOUSE_DOWN, TOP_MOUSE_UP, TOP_SELECTION_CHANGE]
      }
    };
    var activeElement$1 = null;
    var activeElementInst$1 = null;
    var lastSelection = null;
    var mouseDown = false;
    /**
     * Get an object which is a unique representation of the current selection.
     *
     * The return value will not be consistent across nodes or browsers, but
     * two identical selections on the same node will return identical objects.
     *
     * @param {DOMElement} node
     * @return {object}
     */

    function getSelection$1(node) {
      if ('selectionStart' in node && hasSelectionCapabilities(node)) {
        return {
          start: node.selectionStart,
          end: node.selectionEnd
        };
      } else {
        var win = node.ownerDocument && node.ownerDocument.defaultView || window;
        var selection = win.getSelection();
        return {
          anchorNode: selection.anchorNode,
          anchorOffset: selection.anchorOffset,
          focusNode: selection.focusNode,
          focusOffset: selection.focusOffset
        };
      }
    }
    /**
     * Get document associated with the event target.
     *
     * @param {object} nativeEventTarget
     * @return {Document}
     */


    function getEventTargetDocument(eventTarget) {
      return eventTarget.window === eventTarget ? eventTarget.document : eventTarget.nodeType === DOCUMENT_NODE ? eventTarget : eventTarget.ownerDocument;
    }
    /**
     * Poll selection to see whether it's changed.
     *
     * @param {object} nativeEvent
     * @param {object} nativeEventTarget
     * @return {?SyntheticEvent}
     */


    function constructSelectEvent(nativeEvent, nativeEventTarget) {
      // Ensure we have the right element, and that the user is not dragging a
      // selection (this matches native `select` event behavior). In HTML5, select
      // fires only on input and textarea thus if there's no focused element we
      // won't dispatch.
      var doc = getEventTargetDocument(nativeEventTarget);

      if (mouseDown || activeElement$1 == null || activeElement$1 !== getActiveElement(doc)) {
        return null;
      } // Only fire when selection has actually changed.


      var currentSelection = getSelection$1(activeElement$1);

      if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) {
        lastSelection = currentSelection;
        var syntheticEvent = SyntheticEvent.getPooled(eventTypes$3.select, activeElementInst$1, nativeEvent, nativeEventTarget);
        syntheticEvent.type = 'select';
        syntheticEvent.target = activeElement$1;
        accumulateTwoPhaseDispatches(syntheticEvent);
        return syntheticEvent;
      }

      return null;
    }
    /**
     * This plugin creates an `onSelect` event that normalizes select events
     * across form elements.
     *
     * Supported elements are:
     * - input (see `isTextInputElement`)
     * - textarea
     * - contentEditable
     *
     * This differs from native browser implementations in the following ways:
     * - Fires on contentEditable fields as well as inputs.
     * - Fires for collapsed selection.
     * - Fires after user input.
     */


    var SelectEventPlugin = {
      eventTypes: eventTypes$3,
      extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, container) {
        var containerOrDoc = container || getEventTargetDocument(nativeEventTarget); // Track whether all listeners exists for this plugin. If none exist, we do
        // not extract events. See #3639.

        if (!containerOrDoc || !isListeningToAllDependencies('onSelect', containerOrDoc)) {
          return null;
        }

        var targetNode = targetInst ? getNodeFromInstance$1(targetInst) : window;

        switch (topLevelType) {
          // Track the input node that has focus.
          case TOP_FOCUS:
            if (isTextInputElement(targetNode) || targetNode.contentEditable === 'true') {
              activeElement$1 = targetNode;
              activeElementInst$1 = targetInst;
              lastSelection = null;
            }

            break;

          case TOP_BLUR:
            activeElement$1 = null;
            activeElementInst$1 = null;
            lastSelection = null;
            break;
          // Don't fire the event while the user is dragging. This matches the
          // semantics of the native select event.

          case TOP_MOUSE_DOWN:
            mouseDown = true;
            break;

          case TOP_CONTEXT_MENU:
          case TOP_MOUSE_UP:
          case TOP_DRAG_END:
            mouseDown = false;
            return constructSelectEvent(nativeEvent, nativeEventTarget);
          // Chrome and IE fire non-standard event when selection is changed (and
          // sometimes when it hasn't). IE's event fires out of order with respect
          // to key and input events on deletion, so we discard it.
          //
          // Firefox doesn't support selectionchange, so check selection status
          // after each key entry. The selection changes after keydown and before
          // keyup, but we check on keydown as well in the case of holding down a
          // key, when multiple keydown events are fired but only one keyup is.
          // This is also our approach for IE handling, for the reason above.

          case TOP_SELECTION_CHANGE:
            if (skipSelectionChangeEvent) {
              break;
            }

          // falls through

          case TOP_KEY_DOWN:
          case TOP_KEY_UP:
            return constructSelectEvent(nativeEvent, nativeEventTarget);
        }

        return null;
      }
    };
    /**
     * @interface Event
     * @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface
     * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent
     */

    var SyntheticAnimationEvent = SyntheticEvent.extend({
      animationName: null,
      elapsedTime: null,
      pseudoElement: null
    });
    /**
     * @interface Event
     * @see http://www.w3.org/TR/clipboard-apis/
     */

    var SyntheticClipboardEvent = SyntheticEvent.extend({
      clipboardData: function (event) {
        return 'clipboardData' in event ? event.clipboardData : window.clipboardData;
      }
    });
    /**
     * @interface FocusEvent
     * @see http://www.w3.org/TR/DOM-Level-3-Events/
     */

    var SyntheticFocusEvent = SyntheticUIEvent.extend({
      relatedTarget: null
    });
    /**
     * `charCode` represents the actual "character code" and is safe to use with
     * `String.fromCharCode`. As such, only keys that correspond to printable
     * characters produce a valid `charCode`, the only exception to this is Enter.
     * The Tab-key is considered non-printable and does not have a `charCode`,
     * presumably because it does not produce a tab-character in browsers.
     *
     * @param {object} nativeEvent Native browser event.
     * @return {number} Normalized `charCode` property.
     */

    function getEventCharCode(nativeEvent) {
      var charCode;
      var keyCode = nativeEvent.keyCode;

      if ('charCode' in nativeEvent) {
        charCode = nativeEvent.charCode; // FF does not set `charCode` for the Enter-key, check against `keyCode`.

        if (charCode === 0 && keyCode === 13) {
          charCode = 13;
        }
      } else {
        // IE8 does not implement `charCode`, but `keyCode` has the correct value.
        charCode = keyCode;
      } // IE and Edge (on Windows) and Chrome / Safari (on Windows and Linux)
      // report Enter as charCode 10 when ctrl is pressed.


      if (charCode === 10) {
        charCode = 13;
      } // Some non-printable keys are reported in `charCode`/`keyCode`, discard them.
      // Must not discard the (non-)printable Enter-key.


      if (charCode >= 32 || charCode === 13) {
        return charCode;
      }

      return 0;
    }
    /**
     * Normalization of deprecated HTML5 `key` values
     * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
     */


    var normalizeKey = {
      Esc: 'Escape',
      Spacebar: ' ',
      Left: 'ArrowLeft',
      Up: 'ArrowUp',
      Right: 'ArrowRight',
      Down: 'ArrowDown',
      Del: 'Delete',
      Win: 'OS',
      Menu: 'ContextMenu',
      Apps: 'ContextMenu',
      Scroll: 'ScrollLock',
      MozPrintableKey: 'Unidentified'
    };
    /**
     * Translation from legacy `keyCode` to HTML5 `key`
     * Only special keys supported, all others depend on keyboard layout or browser
     * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
     */

    var translateToKey = {
      '8': 'Backspace',
      '9': 'Tab',
      '12': 'Clear',
      '13': 'Enter',
      '16': 'Shift',
      '17': 'Control',
      '18': 'Alt',
      '19': 'Pause',
      '20': 'CapsLock',
      '27': 'Escape',
      '32': ' ',
      '33': 'PageUp',
      '34': 'PageDown',
      '35': 'End',
      '36': 'Home',
      '37': 'ArrowLeft',
      '38': 'ArrowUp',
      '39': 'ArrowRight',
      '40': 'ArrowDown',
      '45': 'Insert',
      '46': 'Delete',
      '112': 'F1',
      '113': 'F2',
      '114': 'F3',
      '115': 'F4',
      '116': 'F5',
      '117': 'F6',
      '118': 'F7',
      '119': 'F8',
      '120': 'F9',
      '121': 'F10',
      '122': 'F11',
      '123': 'F12',
      '144': 'NumLock',
      '145': 'ScrollLock',
      '224': 'Meta'
    };
    /**
     * @param {object} nativeEvent Native browser event.
     * @return {string} Normalized `key` property.
     */

    function getEventKey(nativeEvent) {
      if (nativeEvent.key) {
        // Normalize inconsistent values reported by browsers due to
        // implementations of a working draft specification.
        // FireFox implements `key` but returns `MozPrintableKey` for all
        // printable characters (normalized to `Unidentified`), ignore it.
        var key = normalizeKey[nativeEvent.key] || nativeEvent.key;

        if (key !== 'Unidentified') {
          return key;
        }
      } // Browser does not implement `key`, polyfill as much of it as we can.


      if (nativeEvent.type === 'keypress') {
        var charCode = getEventCharCode(nativeEvent); // The enter-key is technically both printable and non-printable and can
        // thus be captured by `keypress`, no other non-printable key should.

        return charCode === 13 ? 'Enter' : String.fromCharCode(charCode);
      }

      if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') {
        // While user keyboard layout determines the actual meaning of each
        // `keyCode` value, almost all function keys have a universal value.
        return translateToKey[nativeEvent.keyCode] || 'Unidentified';
      }

      return '';
    }
    /**
     * @interface KeyboardEvent
     * @see http://www.w3.org/TR/DOM-Level-3-Events/
     */


    var SyntheticKeyboardEvent = SyntheticUIEvent.extend({
      key: getEventKey,
      location: null,
      ctrlKey: null,
      shiftKey: null,
      altKey: null,
      metaKey: null,
      repeat: null,
      locale: null,
      getModifierState: getEventModifierState,
      // Legacy Interface
      charCode: function (event) {
        // `charCode` is the result of a KeyPress event and represents the value of
        // the actual printable character.
        // KeyPress is deprecated, but its replacement is not yet final and not
        // implemented in any major browser. Only KeyPress has charCode.
        if (event.type === 'keypress') {
          return getEventCharCode(event);
        }

        return 0;
      },
      keyCode: function (event) {
        // `keyCode` is the result of a KeyDown/Up event and represents the value of
        // physical keyboard key.
        // The actual meaning of the value depends on the users' keyboard layout
        // which cannot be detected. Assuming that it is a US keyboard layout
        // provides a surprisingly accurate mapping for US and European users.
        // Due to this, it is left to the user to implement at this time.
        if (event.type === 'keydown' || event.type === 'keyup') {
          return event.keyCode;
        }

        return 0;
      },
      which: function (event) {
        // `which` is an alias for either `keyCode` or `charCode` depending on the
        // type of the event.
        if (event.type === 'keypress') {
          return getEventCharCode(event);
        }

        if (event.type === 'keydown' || event.type === 'keyup') {
          return event.keyCode;
        }

        return 0;
      }
    });
    /**
     * @interface DragEvent
     * @see http://www.w3.org/TR/DOM-Level-3-Events/
     */

    var SyntheticDragEvent = SyntheticMouseEvent.extend({
      dataTransfer: null
    });
    /**
     * @interface TouchEvent
     * @see http://www.w3.org/TR/touch-events/
     */

    var SyntheticTouchEvent = SyntheticUIEvent.extend({
      touches: null,
      targetTouches: null,
      changedTouches: null,
      altKey: null,
      metaKey: null,
      ctrlKey: null,
      shiftKey: null,
      getModifierState: getEventModifierState
    });
    /**
     * @interface Event
     * @see http://www.w3.org/TR/2009/WD-css3-transitions-20090320/#transition-events-
     * @see https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent
     */

    var SyntheticTransitionEvent = SyntheticEvent.extend({
      propertyName: null,
      elapsedTime: null,
      pseudoElement: null
    });
    /**
     * @interface WheelEvent
     * @see http://www.w3.org/TR/DOM-Level-3-Events/
     */

    var SyntheticWheelEvent = SyntheticMouseEvent.extend({
      deltaX: function (event) {
        return 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive).
        'wheelDeltaX' in event ? -event.wheelDeltaX : 0;
      },
      deltaY: function (event) {
        return 'deltaY' in event ? event.deltaY : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive).
        'wheelDeltaY' in event ? -event.wheelDeltaY : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive).
        'wheelDelta' in event ? -event.wheelDelta : 0;
      },
      deltaZ: null,
      // Browsers without "deltaMode" is reporting in raw wheel delta where one
      // notch on the scroll is always +/- 120, roughly equivalent to pixels.
      // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or
      // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size.
      deltaMode: null
    });
    var knownHTMLTopLevelTypes = [TOP_ABORT, TOP_CANCEL, TOP_CAN_PLAY, TOP_CAN_PLAY_THROUGH, TOP_CLOSE, TOP_DURATION_CHANGE, TOP_EMPTIED, TOP_ENCRYPTED, TOP_ENDED, TOP_ERROR, TOP_INPUT, TOP_INVALID, TOP_LOAD, TOP_LOADED_DATA, TOP_LOADED_METADATA, TOP_LOAD_START, TOP_PAUSE, TOP_PLAY, TOP_PLAYING, TOP_PROGRESS, TOP_RATE_CHANGE, TOP_RESET, TOP_SEEKED, TOP_SEEKING, TOP_STALLED, TOP_SUBMIT, TOP_SUSPEND, TOP_TIME_UPDATE, TOP_TOGGLE, TOP_VOLUME_CHANGE, TOP_WAITING];
    var SimpleEventPlugin = {
      // simpleEventPluginEventTypes gets populated from
      // the DOMEventProperties module.
      eventTypes: simpleEventPluginEventTypes,
      extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {
        var dispatchConfig = topLevelEventsToDispatchConfig.get(topLevelType);

        if (!dispatchConfig) {
          return null;
        }

        var EventConstructor;

        switch (topLevelType) {
          case TOP_KEY_PRESS:
            // Firefox creates a keypress event for function keys too. This removes
            // the unwanted keypress events. Enter is however both printable and
            // non-printable. One would expect Tab to be as well (but it isn't).
            if (getEventCharCode(nativeEvent) === 0) {
              return null;
            }

          /* falls through */

          case TOP_KEY_DOWN:
          case TOP_KEY_UP:
            EventConstructor = SyntheticKeyboardEvent;
            break;

          case TOP_BLUR:
          case TOP_FOCUS:
            EventConstructor = SyntheticFocusEvent;
            break;

          case TOP_CLICK:
            // Firefox creates a click event on right mouse clicks. This removes the
            // unwanted click events.
            if (nativeEvent.button === 2) {
              return null;
            }

          /* falls through */

          case TOP_AUX_CLICK:
          case TOP_DOUBLE_CLICK:
          case TOP_MOUSE_DOWN:
          case TOP_MOUSE_MOVE:
          case TOP_MOUSE_UP: // TODO: Disabled elements should not respond to mouse events

          /* falls through */

          case TOP_MOUSE_OUT:
          case TOP_MOUSE_OVER:
          case TOP_CONTEXT_MENU:
            EventConstructor = SyntheticMouseEvent;
            break;

          case TOP_DRAG:
          case TOP_DRAG_END:
          case TOP_DRAG_ENTER:
          case TOP_DRAG_EXIT:
          case TOP_DRAG_LEAVE:
          case TOP_DRAG_OVER:
          case TOP_DRAG_START:
          case TOP_DROP:
            EventConstructor = SyntheticDragEvent;
            break;

          case TOP_TOUCH_CANCEL:
          case TOP_TOUCH_END:
          case TOP_TOUCH_MOVE:
          case TOP_TOUCH_START:
            EventConstructor = SyntheticTouchEvent;
            break;

          case TOP_ANIMATION_END:
          case TOP_ANIMATION_ITERATION:
          case TOP_ANIMATION_START:
            EventConstructor = SyntheticAnimationEvent;
            break;

          case TOP_TRANSITION_END:
            EventConstructor = SyntheticTransitionEvent;
            break;

          case TOP_SCROLL:
            EventConstructor = SyntheticUIEvent;
            break;

          case TOP_WHEEL:
            EventConstructor = SyntheticWheelEvent;
            break;

          case TOP_COPY:
          case TOP_CUT:
          case TOP_PASTE:
            EventConstructor = SyntheticClipboardEvent;
            break;

          case TOP_GOT_POINTER_CAPTURE:
          case TOP_LOST_POINTER_CAPTURE:
          case TOP_POINTER_CANCEL:
          case TOP_POINTER_DOWN:
          case TOP_POINTER_MOVE:
          case TOP_POINTER_OUT:
          case TOP_POINTER_OVER:
          case TOP_POINTER_UP:
            EventConstructor = SyntheticPointerEvent;
            break;

          default:
            {
              if (knownHTMLTopLevelTypes.indexOf(topLevelType) === -1) {
                error('SimpleEventPlugin: Unhandled event type, `%s`. This warning ' + 'is likely caused by a bug in React. Please file an issue.', topLevelType);
              }
            } // HTML Events
            // @see http://www.w3.org/TR/html5/index.html#events-0

            EventConstructor = SyntheticEvent;
            break;
        }

        var event = EventConstructor.getPooled(dispatchConfig, targetInst, nativeEvent, nativeEventTarget);
        accumulateTwoPhaseDispatches(event);
        return event;
      }
    };
    /**
     * Specifies a deterministic ordering of `EventPlugin`s. A convenient way to
     * reason about plugins, without having to package every one of them. This
     * is better than having plugins be ordered in the same order that they
     * are injected because that ordering would be influenced by the packaging order.
     * `ResponderEventPlugin` must occur before `SimpleEventPlugin` so that
     * preventing default on events is convenient in `SimpleEventPlugin` handlers.
     */

    var DOMEventPluginOrder = ['ResponderEventPlugin', 'SimpleEventPlugin', 'EnterLeaveEventPlugin', 'ChangeEventPlugin', 'SelectEventPlugin', 'BeforeInputEventPlugin'];
    /**
     * Inject modules for resolving DOM hierarchy and plugin ordering.
     */

    injectEventPluginOrder(DOMEventPluginOrder);
    setComponentTree(getFiberCurrentPropsFromNode$1, getInstanceFromNode$1, getNodeFromInstance$1);
    /**
     * Some important event plugins included by default (without having to require
     * them).
     */

    injectEventPluginsByName({
      SimpleEventPlugin: SimpleEventPlugin,
      EnterLeaveEventPlugin: EnterLeaveEventPlugin,
      ChangeEventPlugin: ChangeEventPlugin,
      SelectEventPlugin: SelectEventPlugin,
      BeforeInputEventPlugin: BeforeInputEventPlugin
    }); // Prefix measurements so that it's possible to filter them.
    // Longer prefixes are hard to read in DevTools.

    var reactEmoji = "\u269B";
    var warningEmoji = "\u26D4";
    var supportsUserTiming = typeof performance !== 'undefined' && typeof performance.mark === 'function' && typeof performance.clearMarks === 'function' && typeof performance.measure === 'function' && typeof performance.clearMeasures === 'function'; // Keep track of current fiber so that we know the path to unwind on pause.
    // TODO: this looks the same as nextUnitOfWork in scheduler. Can we unify them?

    var currentFiber = null; // If we're in the middle of user code, which fiber and method is it?
    // Reusing `currentFiber` would be confusing for this because user code fiber
    // can change during commit phase too, but we don't need to unwind it (since
    // lifecycles in the commit phase don't resemble a tree).

    var currentPhase = null;
    var currentPhaseFiber = null; // Did lifecycle hook schedule an update? This is often a performance problem,
    // so we will keep track of it, and include it in the report.
    // Track commits caused by cascading updates.

    var isCommitting = false;
    var hasScheduledUpdateInCurrentCommit = false;
    var hasScheduledUpdateInCurrentPhase = false;
    var commitCountInCurrentWorkLoop = 0;
    var effectCountInCurrentCommit = 0; // to avoid stretch the commit phase with measurement overhead.

    var labelsInCurrentCommit = new Set();

    var formatMarkName = function (markName) {
      return reactEmoji + " " + markName;
    };

    var formatLabel = function (label, warning) {
      var prefix = warning ? warningEmoji + " " : reactEmoji + " ";
      var suffix = warning ? " Warning: " + warning : '';
      return "" + prefix + label + suffix;
    };

    var beginMark = function (markName) {
      performance.mark(formatMarkName(markName));
    };

    var clearMark = function (markName) {
      performance.clearMarks(formatMarkName(markName));
    };

    var endMark = function (label, markName, warning) {
      var formattedMarkName = formatMarkName(markName);
      var formattedLabel = formatLabel(label, warning);

      try {
        performance.measure(formattedLabel, formattedMarkName);
      } catch (err) {} // If previous mark was missing for some reason, this will throw.
      // This could only happen if React crashed in an unexpected place earlier.
      // Don't pile on with more errors.
      // Clear marks immediately to avoid growing buffer.


      performance.clearMarks(formattedMarkName);
      performance.clearMeasures(formattedLabel);
    };

    var getFiberMarkName = function (label, debugID) {
      return label + " (#" + debugID + ")";
    };

    var getFiberLabel = function (componentName, isMounted, phase) {
      if (phase === null) {
        // These are composite component total time measurements.
        return componentName + " [" + (isMounted ? 'update' : 'mount') + "]";
      } else {
        // Composite component methods.
        return componentName + "." + phase;
      }
    };

    var beginFiberMark = function (fiber, phase) {
      var componentName = getComponentName(fiber.type) || 'Unknown';
      var debugID = fiber._debugID;
      var isMounted = fiber.alternate !== null;
      var label = getFiberLabel(componentName, isMounted, phase);

      if (isCommitting && labelsInCurrentCommit.has(label)) {
        // During the commit phase, we don't show duplicate labels because
        // there is a fixed overhead for every measurement, and we don't
        // want to stretch the commit phase beyond necessary.
        return false;
      }

      labelsInCurrentCommit.add(label);
      var markName = getFiberMarkName(label, debugID);
      beginMark(markName);
      return true;
    };

    var clearFiberMark = function (fiber, phase) {
      var componentName = getComponentName(fiber.type) || 'Unknown';
      var debugID = fiber._debugID;
      var isMounted = fiber.alternate !== null;
      var label = getFiberLabel(componentName, isMounted, phase);
      var markName = getFiberMarkName(label, debugID);
      clearMark(markName);
    };

    var endFiberMark = function (fiber, phase, warning) {
      var componentName = getComponentName(fiber.type) || 'Unknown';
      var debugID = fiber._debugID;
      var isMounted = fiber.alternate !== null;
      var label = getFiberLabel(componentName, isMounted, phase);
      var markName = getFiberMarkName(label, debugID);
      endMark(label, markName, warning);
    };

    var shouldIgnoreFiber = function (fiber) {
      // Host components should be skipped in the timeline.
      // We could check typeof fiber.type, but does this work with RN?
      switch (fiber.tag) {
        case HostRoot:
        case HostComponent:
        case HostText:
        case HostPortal:
        case Fragment:
        case ContextProvider:
        case ContextConsumer:
        case Mode:
          return true;

        default:
          return false;
      }
    };

    var clearPendingPhaseMeasurement = function () {
      if (currentPhase !== null && currentPhaseFiber !== null) {
        clearFiberMark(currentPhaseFiber, currentPhase);
      }

      currentPhaseFiber = null;
      currentPhase = null;
      hasScheduledUpdateInCurrentPhase = false;
    };

    var pauseTimers = function () {
      // Stops all currently active measurements so that they can be resumed
      // if we continue in a later deferred loop from the same unit of work.
      var fiber = currentFiber;

      while (fiber) {
        if (fiber._debugIsCurrentlyTiming) {
          endFiberMark(fiber, null, null);
        }

        fiber = fiber.return;
      }
    };

    var resumeTimersRecursively = function (fiber) {
      if (fiber.return !== null) {
        resumeTimersRecursively(fiber.return);
      }

      if (fiber._debugIsCurrentlyTiming) {
        beginFiberMark(fiber, null);
      }
    };

    var resumeTimers = function () {
      // Resumes all measurements that were active during the last deferred loop.
      if (currentFiber !== null) {
        resumeTimersRecursively(currentFiber);
      }
    };

    function recordEffect() {
      {
        effectCountInCurrentCommit++;
      }
    }

    function recordScheduleUpdate() {
      {
        if (isCommitting) {
          hasScheduledUpdateInCurrentCommit = true;
        }

        if (currentPhase !== null && currentPhase !== 'componentWillMount' && currentPhase !== 'componentWillReceiveProps') {
          hasScheduledUpdateInCurrentPhase = true;
        }
      }
    }

    function startWorkTimer(fiber) {
      {
        if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
          return;
        } // If we pause, this is the fiber to unwind from.


        currentFiber = fiber;

        if (!beginFiberMark(fiber, null)) {
          return;
        }

        fiber._debugIsCurrentlyTiming = true;
      }
    }

    function cancelWorkTimer(fiber) {
      {
        if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
          return;
        } // Remember we shouldn't complete measurement for this fiber.
        // Otherwise flamechart will be deep even for small updates.


        fiber._debugIsCurrentlyTiming = false;
        clearFiberMark(fiber, null);
      }
    }

    function stopWorkTimer(fiber) {
      {
        if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
          return;
        } // If we pause, its parent is the fiber to unwind from.


        currentFiber = fiber.return;

        if (!fiber._debugIsCurrentlyTiming) {
          return;
        }

        fiber._debugIsCurrentlyTiming = false;
        endFiberMark(fiber, null, null);
      }
    }

    function stopFailedWorkTimer(fiber) {
      {
        if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
          return;
        } // If we pause, its parent is the fiber to unwind from.


        currentFiber = fiber.return;

        if (!fiber._debugIsCurrentlyTiming) {
          return;
        }

        fiber._debugIsCurrentlyTiming = false;
        var warning = fiber.tag === SuspenseComponent ? 'Rendering was suspended' : 'An error was thrown inside this error boundary';
        endFiberMark(fiber, null, warning);
      }
    }

    function startPhaseTimer(fiber, phase) {
      {
        if (!supportsUserTiming) {
          return;
        }

        clearPendingPhaseMeasurement();

        if (!beginFiberMark(fiber, phase)) {
          return;
        }

        currentPhaseFiber = fiber;
        currentPhase = phase;
      }
    }

    function stopPhaseTimer() {
      {
        if (!supportsUserTiming) {
          return;
        }

        if (currentPhase !== null && currentPhaseFiber !== null) {
          var warning = hasScheduledUpdateInCurrentPhase ? 'Scheduled a cascading update' : null;
          endFiberMark(currentPhaseFiber, currentPhase, warning);
        }

        currentPhase = null;
        currentPhaseFiber = null;
      }
    }

    function startWorkLoopTimer(nextUnitOfWork) {
      {
        currentFiber = nextUnitOfWork;

        if (!supportsUserTiming) {
          return;
        }

        commitCountInCurrentWorkLoop = 0; // This is top level call.
        // Any other measurements are performed within.

        beginMark('(React Tree Reconciliation)'); // Resume any measurements that were in progress during the last loop.

        resumeTimers();
      }
    }

    function stopWorkLoopTimer(interruptedBy, didCompleteRoot) {
      {
        if (!supportsUserTiming) {
          return;
        }

        var warning = null;

        if (interruptedBy !== null) {
          if (interruptedBy.tag === HostRoot) {
            warning = 'A top-level update interrupted the previous render';
          } else {
            var componentName = getComponentName(interruptedBy.type) || 'Unknown';
            warning = "An update to " + componentName + " interrupted the previous render";
          }
        } else if (commitCountInCurrentWorkLoop > 1) {
          warning = 'There were cascading updates';
        }

        commitCountInCurrentWorkLoop = 0;
        var label = didCompleteRoot ? '(React Tree Reconciliation: Completed Root)' : '(React Tree Reconciliation: Yielded)'; // Pause any measurements until the next loop.

        pauseTimers();
        endMark(label, '(React Tree Reconciliation)', warning);
      }
    }

    function startCommitTimer() {
      {
        if (!supportsUserTiming) {
          return;
        }

        isCommitting = true;
        hasScheduledUpdateInCurrentCommit = false;
        labelsInCurrentCommit.clear();
        beginMark('(Committing Changes)');
      }
    }

    function stopCommitTimer() {
      {
        if (!supportsUserTiming) {
          return;
        }

        var warning = null;

        if (hasScheduledUpdateInCurrentCommit) {
          warning = 'Lifecycle hook scheduled a cascading update';
        } else if (commitCountInCurrentWorkLoop > 0) {
          warning = 'Caused by a cascading update in earlier commit';
        }

        hasScheduledUpdateInCurrentCommit = false;
        commitCountInCurrentWorkLoop++;
        isCommitting = false;
        labelsInCurrentCommit.clear();
        endMark('(Committing Changes)', '(Committing Changes)', warning);
      }
    }

    function startCommitSnapshotEffectsTimer() {
      {
        if (!supportsUserTiming) {
          return;
        }

        effectCountInCurrentCommit = 0;
        beginMark('(Committing Snapshot Effects)');
      }
    }

    function stopCommitSnapshotEffectsTimer() {
      {
        if (!supportsUserTiming) {
          return;
        }

        var count = effectCountInCurrentCommit;
        effectCountInCurrentCommit = 0;
        endMark("(Committing Snapshot Effects: " + count + " Total)", '(Committing Snapshot Effects)', null);
      }
    }

    function startCommitHostEffectsTimer() {
      {
        if (!supportsUserTiming) {
          return;
        }

        effectCountInCurrentCommit = 0;
        beginMark('(Committing Host Effects)');
      }
    }

    function stopCommitHostEffectsTimer() {
      {
        if (!supportsUserTiming) {
          return;
        }

        var count = effectCountInCurrentCommit;
        effectCountInCurrentCommit = 0;
        endMark("(Committing Host Effects: " + count + " Total)", '(Committing Host Effects)', null);
      }
    }

    function startCommitLifeCyclesTimer() {
      {
        if (!supportsUserTiming) {
          return;
        }

        effectCountInCurrentCommit = 0;
        beginMark('(Calling Lifecycle Methods)');
      }
    }

    function stopCommitLifeCyclesTimer() {
      {
        if (!supportsUserTiming) {
          return;
        }

        var count = effectCountInCurrentCommit;
        effectCountInCurrentCommit = 0;
        endMark("(Calling Lifecycle Methods: " + count + " Total)", '(Calling Lifecycle Methods)', null);
      }
    }

    var valueStack = [];
    var fiberStack;
    {
      fiberStack = [];
    }
    var index = -1;

    function createCursor(defaultValue) {
      return {
        current: defaultValue
      };
    }

    function pop(cursor, fiber) {
      if (index < 0) {
        {
          error('Unexpected pop.');
        }
        return;
      }

      {
        if (fiber !== fiberStack[index]) {
          error('Unexpected Fiber popped.');
        }
      }
      cursor.current = valueStack[index];
      valueStack[index] = null;
      {
        fiberStack[index] = null;
      }
      index--;
    }

    function push(cursor, value, fiber) {
      index++;
      valueStack[index] = cursor.current;
      {
        fiberStack[index] = fiber;
      }
      cursor.current = value;
    }

    var warnedAboutMissingGetChildContext;
    {
      warnedAboutMissingGetChildContext = {};
    }
    var emptyContextObject = {};
    {
      Object.freeze(emptyContextObject);
    } // A cursor to the current merged context object on the stack.

    var contextStackCursor = createCursor(emptyContextObject); // A cursor to a boolean indicating whether the context has changed.

    var didPerformWorkStackCursor = createCursor(false); // Keep track of the previous context object that was on the stack.
    // We use this to get access to the parent context after we have already
    // pushed the next context provider, and now need to merge their contexts.

    var previousContext = emptyContextObject;

    function getUnmaskedContext(workInProgress, Component, didPushOwnContextIfProvider) {
      {
        if (didPushOwnContextIfProvider && isContextProvider(Component)) {
          // If the fiber is a context provider itself, when we read its context
          // we may have already pushed its own child context on the stack. A context
          // provider should not "see" its own child context. Therefore we read the
          // previous (parent) context instead for a context provider.
          return previousContext;
        }

        return contextStackCursor.current;
      }
    }

    function cacheContext(workInProgress, unmaskedContext, maskedContext) {
      {
        var instance = workInProgress.stateNode;
        instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext;
        instance.__reactInternalMemoizedMaskedChildContext = maskedContext;
      }
    }

    function getMaskedContext(workInProgress, unmaskedContext) {
      {
        var type = workInProgress.type;
        var contextTypes = type.contextTypes;

        if (!contextTypes) {
          return emptyContextObject;
        } // Avoid recreating masked context unless unmasked context has changed.
        // Failing to do this will result in unnecessary calls to componentWillReceiveProps.
        // This may trigger infinite loops if componentWillReceiveProps calls setState.


        var instance = workInProgress.stateNode;

        if (instance && instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext) {
          return instance.__reactInternalMemoizedMaskedChildContext;
        }

        var context = {};

        for (var key in contextTypes) {
          context[key] = unmaskedContext[key];
        }

        {
          var name = getComponentName(type) || 'Unknown';
          checkPropTypes(contextTypes, context, 'context', name, getCurrentFiberStackInDev);
        } // Cache unmasked context so we can avoid recreating masked context unless necessary.
        // Context is created before the class component is instantiated so check for instance.

        if (instance) {
          cacheContext(workInProgress, unmaskedContext, context);
        }

        return context;
      }
    }

    function hasContextChanged() {
      {
        return didPerformWorkStackCursor.current;
      }
    }

    function isContextProvider(type) {
      {
        var childContextTypes = type.childContextTypes;
        return childContextTypes !== null && childContextTypes !== undefined;
      }
    }

    function popContext(fiber) {
      {
        pop(didPerformWorkStackCursor, fiber);
        pop(contextStackCursor, fiber);
      }
    }

    function popTopLevelContextObject(fiber) {
      {
        pop(didPerformWorkStackCursor, fiber);
        pop(contextStackCursor, fiber);
      }
    }

    function pushTopLevelContextObject(fiber, context, didChange) {
      {
        if (!(contextStackCursor.current === emptyContextObject)) {
          {
            throw Error("Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue.");
          }
        }

        push(contextStackCursor, context, fiber);
        push(didPerformWorkStackCursor, didChange, fiber);
      }
    }

    function processChildContext(fiber, type, parentContext) {
      {
        var instance = fiber.stateNode;
        var childContextTypes = type.childContextTypes; // TODO (bvaughn) Replace this behavior with an invariant() in the future.
        // It has only been added in Fiber to match the (unintentional) behavior in Stack.

        if (typeof instance.getChildContext !== 'function') {
          {
            var componentName = getComponentName(type) || 'Unknown';

            if (!warnedAboutMissingGetChildContext[componentName]) {
              warnedAboutMissingGetChildContext[componentName] = true;
              error('%s.childContextTypes is specified but there is no getChildContext() method ' + 'on the instance. You can either define getChildContext() on %s or remove ' + 'childContextTypes from it.', componentName, componentName);
            }
          }
          return parentContext;
        }

        var childContext;
        startPhaseTimer(fiber, 'getChildContext');
        childContext = instance.getChildContext();
        stopPhaseTimer();

        for (var contextKey in childContext) {
          if (!(contextKey in childContextTypes)) {
            {
              throw Error((getComponentName(type) || 'Unknown') + ".getChildContext(): key \"" + contextKey + "\" is not defined in childContextTypes.");
            }
          }
        }

        {
          var name = getComponentName(type) || 'Unknown';
          checkPropTypes(childContextTypes, childContext, 'child context', name, // In practice, there is one case in which we won't get a stack. It's when
          // somebody calls unstable_renderSubtreeIntoContainer() and we process
          // context from the parent component instance. The stack will be missing
          // because it's outside of the reconciliation, and so the pointer has not
          // been set. This is rare and doesn't matter. We'll also remove that API.
          getCurrentFiberStackInDev);
        }
        return _assign({}, parentContext, {}, childContext);
      }
    }

    function pushContextProvider(workInProgress) {
      {
        var instance = workInProgress.stateNode; // We push the context as early as possible to ensure stack integrity.
        // If the instance does not exist yet, we will push null at first,
        // and replace it on the stack later when invalidating the context.

        var memoizedMergedChildContext = instance && instance.__reactInternalMemoizedMergedChildContext || emptyContextObject; // Remember the parent context so we can merge with it later.
        // Inherit the parent's did-perform-work value to avoid inadvertently blocking updates.

        previousContext = contextStackCursor.current;
        push(contextStackCursor, memoizedMergedChildContext, workInProgress);
        push(didPerformWorkStackCursor, didPerformWorkStackCursor.current, workInProgress);
        return true;
      }
    }

    function invalidateContextProvider(workInProgress, type, didChange) {
      {
        var instance = workInProgress.stateNode;

        if (!instance) {
          {
            throw Error("Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue.");
          }
        }

        if (didChange) {
          // Merge parent and own context.
          // Skip this if we're not updating due to sCU.
          // This avoids unnecessarily recomputing memoized values.
          var mergedContext = processChildContext(workInProgress, type, previousContext);
          instance.__reactInternalMemoizedMergedChildContext = mergedContext; // Replace the old (or empty) context with the new one.
          // It is important to unwind the context in the reverse order.

          pop(didPerformWorkStackCursor, workInProgress);
          pop(contextStackCursor, workInProgress); // Now push the new context and mark that it has changed.

          push(contextStackCursor, mergedContext, workInProgress);
          push(didPerformWorkStackCursor, didChange, workInProgress);
        } else {
          pop(didPerformWorkStackCursor, workInProgress);
          push(didPerformWorkStackCursor, didChange, workInProgress);
        }
      }
    }

    function findCurrentUnmaskedContext(fiber) {
      {
        // Currently this is only used with renderSubtreeIntoContainer; not sure if it
        // makes sense elsewhere
        if (!(isFiberMounted(fiber) && fiber.tag === ClassComponent)) {
          {
            throw Error("Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue.");
          }
        }

        var node = fiber;

        do {
          switch (node.tag) {
            case HostRoot:
              return node.stateNode.context;

            case ClassComponent:
              {
                var Component = node.type;

                if (isContextProvider(Component)) {
                  return node.stateNode.__reactInternalMemoizedMergedChildContext;
                }

                break;
              }
          }

          node = node.return;
        } while (node !== null);

        {
          {
            throw Error("Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue.");
          }
        }
      }
    }

    var LegacyRoot = 0;
    var BlockingRoot = 1;
    var ConcurrentRoot = 2;
    var Scheduler_runWithPriority = Scheduler.unstable_runWithPriority,
        Scheduler_scheduleCallback = Scheduler.unstable_scheduleCallback,
        Scheduler_cancelCallback = Scheduler.unstable_cancelCallback,
        Scheduler_shouldYield = Scheduler.unstable_shouldYield,
        Scheduler_requestPaint = Scheduler.unstable_requestPaint,
        Scheduler_now = Scheduler.unstable_now,
        Scheduler_getCurrentPriorityLevel = Scheduler.unstable_getCurrentPriorityLevel,
        Scheduler_ImmediatePriority = Scheduler.unstable_ImmediatePriority,
        Scheduler_UserBlockingPriority = Scheduler.unstable_UserBlockingPriority,
        Scheduler_NormalPriority = Scheduler.unstable_NormalPriority,
        Scheduler_LowPriority = Scheduler.unstable_LowPriority,
        Scheduler_IdlePriority = Scheduler.unstable_IdlePriority;
    {
      // Provide explicit error message when production+profiling bundle of e.g.
      // react-dom is used with production (non-profiling) bundle of
      // scheduler/tracing
      if (!(tracing.__interactionsRef != null && tracing.__interactionsRef.current != null)) {
        {
          throw Error("It is not supported to run the profiling version of a renderer (for example, `react-dom/profiling`) without also replacing the `scheduler/tracing` module with `scheduler/tracing-profiling`. Your bundler might have a setting for aliasing both modules. Learn more at http://fb.me/react-profiling");
        }
      }
    }
    var fakeCallbackNode = {}; // Except for NoPriority, these correspond to Scheduler priorities. We use
    // ascending numbers so we can compare them like numbers. They start at 90 to
    // avoid clashing with Scheduler's priorities.

    var ImmediatePriority = 99;
    var UserBlockingPriority$1 = 98;
    var NormalPriority = 97;
    var LowPriority = 96;
    var IdlePriority = 95; // NoPriority is the absence of priority. Also React-only.

    var NoPriority = 90;
    var shouldYield = Scheduler_shouldYield;
    var requestPaint = // Fall back gracefully if we're running an older version of Scheduler.
    Scheduler_requestPaint !== undefined ? Scheduler_requestPaint : function () {};
    var syncQueue = null;
    var immediateQueueCallbackNode = null;
    var isFlushingSyncQueue = false;
    var initialTimeMs = Scheduler_now(); // If the initial timestamp is reasonably small, use Scheduler's `now` directly.
    // This will be the case for modern browsers that support `performance.now`. In
    // older browsers, Scheduler falls back to `Date.now`, which returns a Unix
    // timestamp. In that case, subtract the module initialization time to simulate
    // the behavior of performance.now and keep our times small enough to fit
    // within 32 bits.
    // TODO: Consider lifting this into Scheduler.

    var now = initialTimeMs < 10000 ? Scheduler_now : function () {
      return Scheduler_now() - initialTimeMs;
    };

    function getCurrentPriorityLevel() {
      switch (Scheduler_getCurrentPriorityLevel()) {
        case Scheduler_ImmediatePriority:
          return ImmediatePriority;

        case Scheduler_UserBlockingPriority:
          return UserBlockingPriority$1;

        case Scheduler_NormalPriority:
          return NormalPriority;

        case Scheduler_LowPriority:
          return LowPriority;

        case Scheduler_IdlePriority:
          return IdlePriority;

        default:
          {
            {
              throw Error("Unknown priority level.");
            }
          }
      }
    }

    function reactPriorityToSchedulerPriority(reactPriorityLevel) {
      switch (reactPriorityLevel) {
        case ImmediatePriority:
          return Scheduler_ImmediatePriority;

        case UserBlockingPriority$1:
          return Scheduler_UserBlockingPriority;

        case NormalPriority:
          return Scheduler_NormalPriority;

        case LowPriority:
          return Scheduler_LowPriority;

        case IdlePriority:
          return Scheduler_IdlePriority;

        default:
          {
            {
              throw Error("Unknown priority level.");
            }
          }
      }
    }

    function runWithPriority$1(reactPriorityLevel, fn) {
      var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel);
      return Scheduler_runWithPriority(priorityLevel, fn);
    }

    function scheduleCallback(reactPriorityLevel, callback, options) {
      var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel);
      return Scheduler_scheduleCallback(priorityLevel, callback, options);
    }

    function scheduleSyncCallback(callback) {
      // Push this callback into an internal queue. We'll flush these either in
      // the next tick, or earlier if something calls `flushSyncCallbackQueue`.
      if (syncQueue === null) {
        syncQueue = [callback]; // Flush the queue in the next tick, at the earliest.

        immediateQueueCallbackNode = Scheduler_scheduleCallback(Scheduler_ImmediatePriority, flushSyncCallbackQueueImpl);
      } else {
        // Push onto existing queue. Don't need to schedule a callback because
        // we already scheduled one when we created the queue.
        syncQueue.push(callback);
      }

      return fakeCallbackNode;
    }

    function cancelCallback(callbackNode) {
      if (callbackNode !== fakeCallbackNode) {
        Scheduler_cancelCallback(callbackNode);
      }
    }

    function flushSyncCallbackQueue() {
      if (immediateQueueCallbackNode !== null) {
        var node = immediateQueueCallbackNode;
        immediateQueueCallbackNode = null;
        Scheduler_cancelCallback(node);
      }

      flushSyncCallbackQueueImpl();
    }

    function flushSyncCallbackQueueImpl() {
      if (!isFlushingSyncQueue && syncQueue !== null) {
        // Prevent re-entrancy.
        isFlushingSyncQueue = true;
        var i = 0;

        try {
          var _isSync = true;
          var queue = syncQueue;
          runWithPriority$1(ImmediatePriority, function () {
            for (; i < queue.length; i++) {
              var callback = queue[i];

              do {
                callback = callback(_isSync);
              } while (callback !== null);
            }
          });
          syncQueue = null;
        } catch (error) {
          // If something throws, leave the remaining callbacks on the queue.
          if (syncQueue !== null) {
            syncQueue = syncQueue.slice(i + 1);
          } // Resume flushing in the next tick


          Scheduler_scheduleCallback(Scheduler_ImmediatePriority, flushSyncCallbackQueue);
          throw error;
        } finally {
          isFlushingSyncQueue = false;
        }
      }
    }

    var NoMode = 0;
    var StrictMode = 1; // TODO: Remove BlockingMode and ConcurrentMode by reading from the root
    // tag instead

    var BlockingMode = 2;
    var ConcurrentMode = 4;
    var ProfileMode = 8; // Max 31 bit integer. The max integer size in V8 for 32-bit systems.
    // Math.pow(2, 30) - 1
    // 0b111111111111111111111111111111

    var MAX_SIGNED_31_BIT_INT = 1073741823;
    var NoWork = 0; // TODO: Think of a better name for Never. The key difference with Idle is that
    // Never work can be committed in an inconsistent state without tearing the UI.
    // The main example is offscreen content, like a hidden subtree. So one possible
    // name is Offscreen. However, it also includes dehydrated Suspense boundaries,
    // which are inconsistent in the sense that they haven't finished yet, but
    // aren't visibly inconsistent because the server rendered HTML matches what the
    // hydrated tree would look like.

    var Never = 1; // Idle is slightly higher priority than Never. It must completely finish in
    // order to be consistent.

    var Idle = 2; // Continuous Hydration is slightly higher than Idle and is used to increase
    // priority of hover targets.

    var ContinuousHydration = 3;
    var Sync = MAX_SIGNED_31_BIT_INT;
    var Batched = Sync - 1;
    var UNIT_SIZE = 10;
    var MAGIC_NUMBER_OFFSET = Batched - 1; // 1 unit of expiration time represents 10ms.

    function msToExpirationTime(ms) {
      // Always subtract from the offset so that we don't clash with the magic number for NoWork.
      return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);
    }

    function expirationTimeToMs(expirationTime) {
      return (MAGIC_NUMBER_OFFSET - expirationTime) * UNIT_SIZE;
    }

    function ceiling(num, precision) {
      return ((num / precision | 0) + 1) * precision;
    }

    function computeExpirationBucket(currentTime, expirationInMs, bucketSizeMs) {
      return MAGIC_NUMBER_OFFSET - ceiling(MAGIC_NUMBER_OFFSET - currentTime + expirationInMs / UNIT_SIZE, bucketSizeMs / UNIT_SIZE);
    } // TODO: This corresponds to Scheduler's NormalPriority, not LowPriority. Update
    // the names to reflect.


    var LOW_PRIORITY_EXPIRATION = 5000;
    var LOW_PRIORITY_BATCH_SIZE = 250;

    function computeAsyncExpiration(currentTime) {
      return computeExpirationBucket(currentTime, LOW_PRIORITY_EXPIRATION, LOW_PRIORITY_BATCH_SIZE);
    }

    function computeSuspenseExpiration(currentTime, timeoutMs) {
      // TODO: Should we warn if timeoutMs is lower than the normal pri expiration time?
      return computeExpirationBucket(currentTime, timeoutMs, LOW_PRIORITY_BATCH_SIZE);
    } // We intentionally set a higher expiration time for interactive updates in
    // dev than in production.
    //
    // If the main thread is being blocked so long that you hit the expiration,
    // it's a problem that could be solved with better scheduling.
    //
    // People will be more likely to notice this and fix it with the long
    // expiration time in development.
    //
    // In production we opt for better UX at the risk of masking scheduling
    // problems, by expiring fast.


    var HIGH_PRIORITY_EXPIRATION = 500;
    var HIGH_PRIORITY_BATCH_SIZE = 100;

    function computeInteractiveExpiration(currentTime) {
      return computeExpirationBucket(currentTime, HIGH_PRIORITY_EXPIRATION, HIGH_PRIORITY_BATCH_SIZE);
    }

    function inferPriorityFromExpirationTime(currentTime, expirationTime) {
      if (expirationTime === Sync) {
        return ImmediatePriority;
      }

      if (expirationTime === Never || expirationTime === Idle) {
        return IdlePriority;
      }

      var msUntil = expirationTimeToMs(expirationTime) - expirationTimeToMs(currentTime);

      if (msUntil <= 0) {
        return ImmediatePriority;
      }

      if (msUntil <= HIGH_PRIORITY_EXPIRATION + HIGH_PRIORITY_BATCH_SIZE) {
        return UserBlockingPriority$1;
      }

      if (msUntil <= LOW_PRIORITY_EXPIRATION + LOW_PRIORITY_BATCH_SIZE) {
        return NormalPriority;
      } // TODO: Handle LowPriority
      // Assume anything lower has idle priority


      return IdlePriority;
    }

    var ReactStrictModeWarnings = {
      recordUnsafeLifecycleWarnings: function (fiber, instance) {},
      flushPendingUnsafeLifecycleWarnings: function () {},
      recordLegacyContextWarning: function (fiber, instance) {},
      flushLegacyContextWarning: function () {},
      discardPendingWarnings: function () {}
    };
    {
      var findStrictRoot = function (fiber) {
        var maybeStrictRoot = null;
        var node = fiber;

        while (node !== null) {
          if (node.mode & StrictMode) {
            maybeStrictRoot = node;
          }

          node = node.return;
        }

        return maybeStrictRoot;
      };

      var setToSortedString = function (set) {
        var array = [];
        set.forEach(function (value) {
          array.push(value);
        });
        return array.sort().join(', ');
      };

      var pendingComponentWillMountWarnings = [];
      var pendingUNSAFE_ComponentWillMountWarnings = [];
      var pendingComponentWillReceivePropsWarnings = [];
      var pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
      var pendingComponentWillUpdateWarnings = [];
      var pendingUNSAFE_ComponentWillUpdateWarnings = []; // Tracks components we have already warned about.

      var didWarnAboutUnsafeLifecycles = new Set();

      ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function (fiber, instance) {
        // Dedup strategy: Warn once per component.
        if (didWarnAboutUnsafeLifecycles.has(fiber.type)) {
          return;
        }

        if (typeof instance.componentWillMount === 'function' && // Don't warn about react-lifecycles-compat polyfilled components.
        instance.componentWillMount.__suppressDeprecationWarning !== true) {
          pendingComponentWillMountWarnings.push(fiber);
        }

        if (fiber.mode & StrictMode && typeof instance.UNSAFE_componentWillMount === 'function') {
          pendingUNSAFE_ComponentWillMountWarnings.push(fiber);
        }

        if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
          pendingComponentWillReceivePropsWarnings.push(fiber);
        }

        if (fiber.mode & StrictMode && typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
          pendingUNSAFE_ComponentWillReceivePropsWarnings.push(fiber);
        }

        if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
          pendingComponentWillUpdateWarnings.push(fiber);
        }

        if (fiber.mode & StrictMode && typeof instance.UNSAFE_componentWillUpdate === 'function') {
          pendingUNSAFE_ComponentWillUpdateWarnings.push(fiber);
        }
      };

      ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function () {
        // We do an initial pass to gather component names
        var componentWillMountUniqueNames = new Set();

        if (pendingComponentWillMountWarnings.length > 0) {
          pendingComponentWillMountWarnings.forEach(function (fiber) {
            componentWillMountUniqueNames.add(getComponentName(fiber.type) || 'Component');
            didWarnAboutUnsafeLifecycles.add(fiber.type);
          });
          pendingComponentWillMountWarnings = [];
        }

        var UNSAFE_componentWillMountUniqueNames = new Set();

        if (pendingUNSAFE_ComponentWillMountWarnings.length > 0) {
          pendingUNSAFE_ComponentWillMountWarnings.forEach(function (fiber) {
            UNSAFE_componentWillMountUniqueNames.add(getComponentName(fiber.type) || 'Component');
            didWarnAboutUnsafeLifecycles.add(fiber.type);
          });
          pendingUNSAFE_ComponentWillMountWarnings = [];
        }

        var componentWillReceivePropsUniqueNames = new Set();

        if (pendingComponentWillReceivePropsWarnings.length > 0) {
          pendingComponentWillReceivePropsWarnings.forEach(function (fiber) {
            componentWillReceivePropsUniqueNames.add(getComponentName(fiber.type) || 'Component');
            didWarnAboutUnsafeLifecycles.add(fiber.type);
          });
          pendingComponentWillReceivePropsWarnings = [];
        }

        var UNSAFE_componentWillReceivePropsUniqueNames = new Set();

        if (pendingUNSAFE_ComponentWillReceivePropsWarnings.length > 0) {
          pendingUNSAFE_ComponentWillReceivePropsWarnings.forEach(function (fiber) {
            UNSAFE_componentWillReceivePropsUniqueNames.add(getComponentName(fiber.type) || 'Component');
            didWarnAboutUnsafeLifecycles.add(fiber.type);
          });
          pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
        }

        var componentWillUpdateUniqueNames = new Set();

        if (pendingComponentWillUpdateWarnings.length > 0) {
          pendingComponentWillUpdateWarnings.forEach(function (fiber) {
            componentWillUpdateUniqueNames.add(getComponentName(fiber.type) || 'Component');
            didWarnAboutUnsafeLifecycles.add(fiber.type);
          });
          pendingComponentWillUpdateWarnings = [];
        }

        var UNSAFE_componentWillUpdateUniqueNames = new Set();

        if (pendingUNSAFE_ComponentWillUpdateWarnings.length > 0) {
          pendingUNSAFE_ComponentWillUpdateWarnings.forEach(function (fiber) {
            UNSAFE_componentWillUpdateUniqueNames.add(getComponentName(fiber.type) || 'Component');
            didWarnAboutUnsafeLifecycles.add(fiber.type);
          });
          pendingUNSAFE_ComponentWillUpdateWarnings = [];
        } // Finally, we flush all the warnings
        // UNSAFE_ ones before the deprecated ones, since they'll be 'louder'


        if (UNSAFE_componentWillMountUniqueNames.size > 0) {
          var sortedNames = setToSortedString(UNSAFE_componentWillMountUniqueNames);
          error('Using UNSAFE_componentWillMount in strict mode is not recommended and may indicate bugs in your code. ' + 'See https://fb.me/react-unsafe-component-lifecycles for details.\n\n' + '* Move code with side effects to componentDidMount, and set initial state in the constructor.\n' + '\nPlease update the following components: %s', sortedNames);
        }

        if (UNSAFE_componentWillReceivePropsUniqueNames.size > 0) {
          var _sortedNames = setToSortedString(UNSAFE_componentWillReceivePropsUniqueNames);

          error('Using UNSAFE_componentWillReceiveProps in strict mode is not recommended ' + 'and may indicate bugs in your code. ' + 'See https://fb.me/react-unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + "* If you're updating state whenever props change, " + 'refactor your code to use memoization techniques or move it to ' + 'static getDerivedStateFromProps. Learn more at: https://fb.me/react-derived-state\n' + '\nPlease update the following components: %s', _sortedNames);
        }

        if (UNSAFE_componentWillUpdateUniqueNames.size > 0) {
          var _sortedNames2 = setToSortedString(UNSAFE_componentWillUpdateUniqueNames);

          error('Using UNSAFE_componentWillUpdate in strict mode is not recommended ' + 'and may indicate bugs in your code. ' + 'See https://fb.me/react-unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + '\nPlease update the following components: %s', _sortedNames2);
        }

        if (componentWillMountUniqueNames.size > 0) {
          var _sortedNames3 = setToSortedString(componentWillMountUniqueNames);

          warn('componentWillMount has been renamed, and is not recommended for use. ' + 'See https://fb.me/react-unsafe-component-lifecycles for details.\n\n' + '* Move code with side effects to componentDidMount, and set initial state in the constructor.\n' + '* Rename componentWillMount to UNSAFE_componentWillMount to suppress ' + 'this warning in non-strict mode. In React 17.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames3);
        }

        if (componentWillReceivePropsUniqueNames.size > 0) {
          var _sortedNames4 = setToSortedString(componentWillReceivePropsUniqueNames);

          warn('componentWillReceiveProps has been renamed, and is not recommended for use. ' + 'See https://fb.me/react-unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + "* If you're updating state whenever props change, refactor your " + 'code to use memoization techniques or move it to ' + 'static getDerivedStateFromProps. Learn more at: https://fb.me/react-derived-state\n' + '* Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress ' + 'this warning in non-strict mode. In React 17.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames4);
        }

        if (componentWillUpdateUniqueNames.size > 0) {
          var _sortedNames5 = setToSortedString(componentWillUpdateUniqueNames);

          warn('componentWillUpdate has been renamed, and is not recommended for use. ' + 'See https://fb.me/react-unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + '* Rename componentWillUpdate to UNSAFE_componentWillUpdate to suppress ' + 'this warning in non-strict mode. In React 17.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames5);
        }
      };

      var pendingLegacyContextWarning = new Map(); // Tracks components we have already warned about.

      var didWarnAboutLegacyContext = new Set();

      ReactStrictModeWarnings.recordLegacyContextWarning = function (fiber, instance) {
        var strictRoot = findStrictRoot(fiber);

        if (strictRoot === null) {
          error('Expected to find a StrictMode component in a strict mode tree. ' + 'This error is likely caused by a bug in React. Please file an issue.');
          return;
        } // Dedup strategy: Warn once per component.


        if (didWarnAboutLegacyContext.has(fiber.type)) {
          return;
        }

        var warningsForRoot = pendingLegacyContextWarning.get(strictRoot);

        if (fiber.type.contextTypes != null || fiber.type.childContextTypes != null || instance !== null && typeof instance.getChildContext === 'function') {
          if (warningsForRoot === undefined) {
            warningsForRoot = [];
            pendingLegacyContextWarning.set(strictRoot, warningsForRoot);
          }

          warningsForRoot.push(fiber);
        }
      };

      ReactStrictModeWarnings.flushLegacyContextWarning = function () {
        pendingLegacyContextWarning.forEach(function (fiberArray, strictRoot) {
          if (fiberArray.length === 0) {
            return;
          }

          var firstFiber = fiberArray[0];
          var uniqueNames = new Set();
          fiberArray.forEach(function (fiber) {
            uniqueNames.add(getComponentName(fiber.type) || 'Component');
            didWarnAboutLegacyContext.add(fiber.type);
          });
          var sortedNames = setToSortedString(uniqueNames);
          var firstComponentStack = getStackByFiberInDevAndProd(firstFiber);
          error('Legacy context API has been detected within a strict-mode tree.' + '\n\nThe old API will be supported in all 16.x releases, but applications ' + 'using it should migrate to the new version.' + '\n\nPlease update the following components: %s' + '\n\nLearn more about this warning here: https://fb.me/react-legacy-context' + '%s', sortedNames, firstComponentStack);
        });
      };

      ReactStrictModeWarnings.discardPendingWarnings = function () {
        pendingComponentWillMountWarnings = [];
        pendingUNSAFE_ComponentWillMountWarnings = [];
        pendingComponentWillReceivePropsWarnings = [];
        pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
        pendingComponentWillUpdateWarnings = [];
        pendingUNSAFE_ComponentWillUpdateWarnings = [];
        pendingLegacyContextWarning = new Map();
      };
    }
    var resolveFamily = null; // $FlowFixMe Flow gets confused by a WeakSet feature check below.

    var failedBoundaries = null;

    var setRefreshHandler = function (handler) {
      {
        resolveFamily = handler;
      }
    };

    function resolveFunctionForHotReloading(type) {
      {
        if (resolveFamily === null) {
          // Hot reloading is disabled.
          return type;
        }

        var family = resolveFamily(type);

        if (family === undefined) {
          return type;
        } // Use the latest known implementation.


        return family.current;
      }
    }

    function resolveClassForHotReloading(type) {
      // No implementation differences.
      return resolveFunctionForHotReloading(type);
    }

    function resolveForwardRefForHotReloading(type) {
      {
        if (resolveFamily === null) {
          // Hot reloading is disabled.
          return type;
        }

        var family = resolveFamily(type);

        if (family === undefined) {
          // Check if we're dealing with a real forwardRef. Don't want to crash early.
          if (type !== null && type !== undefined && typeof type.render === 'function') {
            // ForwardRef is special because its resolved .type is an object,
            // but it's possible that we only have its inner render function in the map.
            // If that inner render function is different, we'll build a new forwardRef type.
            var currentRender = resolveFunctionForHotReloading(type.render);

            if (type.render !== currentRender) {
              var syntheticType = {
                $$typeof: REACT_FORWARD_REF_TYPE,
                render: currentRender
              };

              if (type.displayName !== undefined) {
                syntheticType.displayName = type.displayName;
              }

              return syntheticType;
            }
          }

          return type;
        } // Use the latest known implementation.


        return family.current;
      }
    }

    function isCompatibleFamilyForHotReloading(fiber, element) {
      {
        if (resolveFamily === null) {
          // Hot reloading is disabled.
          return false;
        }

        var prevType = fiber.elementType;
        var nextType = element.type; // If we got here, we know types aren't === equal.

        var needsCompareFamilies = false;
        var $$typeofNextType = typeof nextType === 'object' && nextType !== null ? nextType.$$typeof : null;

        switch (fiber.tag) {
          case ClassComponent:
            {
              if (typeof nextType === 'function') {
                needsCompareFamilies = true;
              }

              break;
            }

          case FunctionComponent:
            {
              if (typeof nextType === 'function') {
                needsCompareFamilies = true;
              } else if ($$typeofNextType === REACT_LAZY_TYPE) {
                // We don't know the inner type yet.
                // We're going to assume that the lazy inner type is stable,
                // and so it is sufficient to avoid reconciling it away.
                // We're not going to unwrap or actually use the new lazy type.
                needsCompareFamilies = true;
              }

              break;
            }

          case ForwardRef:
            {
              if ($$typeofNextType === REACT_FORWARD_REF_TYPE) {
                needsCompareFamilies = true;
              } else if ($$typeofNextType === REACT_LAZY_TYPE) {
                needsCompareFamilies = true;
              }

              break;
            }

          case MemoComponent:
          case SimpleMemoComponent:
            {
              if ($$typeofNextType === REACT_MEMO_TYPE) {
                // TODO: if it was but can no longer be simple,
                // we shouldn't set this.
                needsCompareFamilies = true;
              } else if ($$typeofNextType === REACT_LAZY_TYPE) {
                needsCompareFamilies = true;
              }

              break;
            }

          default:
            return false;
        } // Check if both types have a family and it's the same one.


        if (needsCompareFamilies) {
          // Note: memo() and forwardRef() we'll compare outer rather than inner type.
          // This means both of them need to be registered to preserve state.
          // If we unwrapped and compared the inner types for wrappers instead,
          // then we would risk falsely saying two separate memo(Foo)
          // calls are equivalent because they wrap the same Foo function.
          var prevFamily = resolveFamily(prevType);

          if (prevFamily !== undefined && prevFamily === resolveFamily(nextType)) {
            return true;
          }
        }

        return false;
      }
    }

    function markFailedErrorBoundaryForHotReloading(fiber) {
      {
        if (resolveFamily === null) {
          // Hot reloading is disabled.
          return;
        }

        if (typeof WeakSet !== 'function') {
          return;
        }

        if (failedBoundaries === null) {
          failedBoundaries = new WeakSet();
        }

        failedBoundaries.add(fiber);
      }
    }

    var scheduleRefresh = function (root, update) {
      {
        if (resolveFamily === null) {
          // Hot reloading is disabled.
          return;
        }

        var staleFamilies = update.staleFamilies,
            updatedFamilies = update.updatedFamilies;
        flushPassiveEffects();
        flushSync(function () {
          scheduleFibersWithFamiliesRecursively(root.current, updatedFamilies, staleFamilies);
        });
      }
    };

    var scheduleRoot = function (root, element) {
      {
        if (root.context !== emptyContextObject) {
          // Super edge case: root has a legacy _renderSubtree context
          // but we don't know the parentComponent so we can't pass it.
          // Just ignore. We'll delete this with _renderSubtree code path later.
          return;
        }

        flushPassiveEffects();
        syncUpdates(function () {
          updateContainer(element, root, null, null);
        });
      }
    };

    function scheduleFibersWithFamiliesRecursively(fiber, updatedFamilies, staleFamilies) {
      {
        var alternate = fiber.alternate,
            child = fiber.child,
            sibling = fiber.sibling,
            tag = fiber.tag,
            type = fiber.type;
        var candidateType = null;

        switch (tag) {
          case FunctionComponent:
          case SimpleMemoComponent:
          case ClassComponent:
            candidateType = type;
            break;

          case ForwardRef:
            candidateType = type.render;
            break;
        }

        if (resolveFamily === null) {
          throw new Error('Expected resolveFamily to be set during hot reload.');
        }

        var needsRender = false;
        var needsRemount = false;

        if (candidateType !== null) {
          var family = resolveFamily(candidateType);

          if (family !== undefined) {
            if (staleFamilies.has(family)) {
              needsRemount = true;
            } else if (updatedFamilies.has(family)) {
              if (tag === ClassComponent) {
                needsRemount = true;
              } else {
                needsRender = true;
              }
            }
          }
        }

        if (failedBoundaries !== null) {
          if (failedBoundaries.has(fiber) || alternate !== null && failedBoundaries.has(alternate)) {
            needsRemount = true;
          }
        }

        if (needsRemount) {
          fiber._debugNeedsRemount = true;
        }

        if (needsRemount || needsRender) {
          scheduleWork(fiber, Sync);
        }

        if (child !== null && !needsRemount) {
          scheduleFibersWithFamiliesRecursively(child, updatedFamilies, staleFamilies);
        }

        if (sibling !== null) {
          scheduleFibersWithFamiliesRecursively(sibling, updatedFamilies, staleFamilies);
        }
      }
    }

    var findHostInstancesForRefresh = function (root, families) {
      {
        var hostInstances = new Set();
        var types = new Set(families.map(function (family) {
          return family.current;
        }));
        findHostInstancesForMatchingFibersRecursively(root.current, types, hostInstances);
        return hostInstances;
      }
    };

    function findHostInstancesForMatchingFibersRecursively(fiber, types, hostInstances) {
      {
        var child = fiber.child,
            sibling = fiber.sibling,
            tag = fiber.tag,
            type = fiber.type;
        var candidateType = null;

        switch (tag) {
          case FunctionComponent:
          case SimpleMemoComponent:
          case ClassComponent:
            candidateType = type;
            break;

          case ForwardRef:
            candidateType = type.render;
            break;
        }

        var didMatch = false;

        if (candidateType !== null) {
          if (types.has(candidateType)) {
            didMatch = true;
          }
        }

        if (didMatch) {
          // We have a match. This only drills down to the closest host components.
          // There's no need to search deeper because for the purpose of giving
          // visual feedback, "flashing" outermost parent rectangles is sufficient.
          findHostInstancesForFiberShallowly(fiber, hostInstances);
        } else {
          // If there's no match, maybe there will be one further down in the child tree.
          if (child !== null) {
            findHostInstancesForMatchingFibersRecursively(child, types, hostInstances);
          }
        }

        if (sibling !== null) {
          findHostInstancesForMatchingFibersRecursively(sibling, types, hostInstances);
        }
      }
    }

    function findHostInstancesForFiberShallowly(fiber, hostInstances) {
      {
        var foundHostInstances = findChildHostInstancesForFiberShallowly(fiber, hostInstances);

        if (foundHostInstances) {
          return;
        } // If we didn't find any host children, fallback to closest host parent.


        var node = fiber;

        while (true) {
          switch (node.tag) {
            case HostComponent:
              hostInstances.add(node.stateNode);
              return;

            case HostPortal:
              hostInstances.add(node.stateNode.containerInfo);
              return;

            case HostRoot:
              hostInstances.add(node.stateNode.containerInfo);
              return;
          }

          if (node.return === null) {
            throw new Error('Expected to reach root first.');
          }

          node = node.return;
        }
      }
    }

    function findChildHostInstancesForFiberShallowly(fiber, hostInstances) {
      {
        var node = fiber;
        var foundHostInstances = false;

        while (true) {
          if (node.tag === HostComponent) {
            // We got a match.
            foundHostInstances = true;
            hostInstances.add(node.stateNode); // There may still be more, so keep searching.
          } else if (node.child !== null) {
            node.child.return = node;
            node = node.child;
            continue;
          }

          if (node === fiber) {
            return foundHostInstances;
          }

          while (node.sibling === null) {
            if (node.return === null || node.return === fiber) {
              return foundHostInstances;
            }

            node = node.return;
          }

          node.sibling.return = node.return;
          node = node.sibling;
        }
      }
      return false;
    }

    function resolveDefaultProps(Component, baseProps) {
      if (Component && Component.defaultProps) {
        // Resolve default props. Taken from ReactElement
        var props = _assign({}, baseProps);

        var defaultProps = Component.defaultProps;

        for (var propName in defaultProps) {
          if (props[propName] === undefined) {
            props[propName] = defaultProps[propName];
          }
        }

        return props;
      }

      return baseProps;
    }

    function readLazyComponentType(lazyComponent) {
      initializeLazyComponentType(lazyComponent);

      if (lazyComponent._status !== Resolved) {
        throw lazyComponent._result;
      }

      return lazyComponent._result;
    }

    var valueCursor = createCursor(null);
    var rendererSigil;
    {
      // Use this to detect multiple renderers using the same context
      rendererSigil = {};
    }
    var currentlyRenderingFiber = null;
    var lastContextDependency = null;
    var lastContextWithAllBitsObserved = null;
    var isDisallowedContextReadInDEV = false;

    function resetContextDependencies() {
      // This is called right before React yields execution, to ensure `readContext`
      // cannot be called outside the render phase.
      currentlyRenderingFiber = null;
      lastContextDependency = null;
      lastContextWithAllBitsObserved = null;
      {
        isDisallowedContextReadInDEV = false;
      }
    }

    function enterDisallowedContextReadInDEV() {
      {
        isDisallowedContextReadInDEV = true;
      }
    }

    function exitDisallowedContextReadInDEV() {
      {
        isDisallowedContextReadInDEV = false;
      }
    }

    function pushProvider(providerFiber, nextValue) {
      var context = providerFiber.type._context;
      {
        push(valueCursor, context._currentValue, providerFiber);
        context._currentValue = nextValue;
        {
          if (context._currentRenderer !== undefined && context._currentRenderer !== null && context._currentRenderer !== rendererSigil) {
            error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.');
          }

          context._currentRenderer = rendererSigil;
        }
      }
    }

    function popProvider(providerFiber) {
      var currentValue = valueCursor.current;
      pop(valueCursor, providerFiber);
      var context = providerFiber.type._context;
      {
        context._currentValue = currentValue;
      }
    }

    function calculateChangedBits(context, newValue, oldValue) {
      if (objectIs(oldValue, newValue)) {
        // No change
        return 0;
      } else {
        var changedBits = typeof context._calculateChangedBits === 'function' ? context._calculateChangedBits(oldValue, newValue) : MAX_SIGNED_31_BIT_INT;
        {
          if ((changedBits & MAX_SIGNED_31_BIT_INT) !== changedBits) {
            error('calculateChangedBits: Expected the return value to be a ' + '31-bit integer. Instead received: %s', changedBits);
          }
        }
        return changedBits | 0;
      }
    }

    function scheduleWorkOnParentPath(parent, renderExpirationTime) {
      // Update the child expiration time of all the ancestors, including
      // the alternates.
      var node = parent;

      while (node !== null) {
        var alternate = node.alternate;

        if (node.childExpirationTime < renderExpirationTime) {
          node.childExpirationTime = renderExpirationTime;

          if (alternate !== null && alternate.childExpirationTime < renderExpirationTime) {
            alternate.childExpirationTime = renderExpirationTime;
          }
        } else if (alternate !== null && alternate.childExpirationTime < renderExpirationTime) {
          alternate.childExpirationTime = renderExpirationTime;
        } else {
          // Neither alternate was updated, which means the rest of the
          // ancestor path already has sufficient priority.
          break;
        }

        node = node.return;
      }
    }

    function propagateContextChange(workInProgress, context, changedBits, renderExpirationTime) {
      var fiber = workInProgress.child;

      if (fiber !== null) {
        // Set the return pointer of the child to the work-in-progress fiber.
        fiber.return = workInProgress;
      }

      while (fiber !== null) {
        var nextFiber = void 0; // Visit this fiber.

        var list = fiber.dependencies;

        if (list !== null) {
          nextFiber = fiber.child;
          var dependency = list.firstContext;

          while (dependency !== null) {
            // Check if the context matches.
            if (dependency.context === context && (dependency.observedBits & changedBits) !== 0) {
              // Match! Schedule an update on this fiber.
              if (fiber.tag === ClassComponent) {
                // Schedule a force update on the work-in-progress.
                var update = createUpdate(renderExpirationTime, null);
                update.tag = ForceUpdate; // TODO: Because we don't have a work-in-progress, this will add the
                // update to the current fiber, too, which means it will persist even if
                // this render is thrown away. Since it's a race condition, not sure it's
                // worth fixing.

                enqueueUpdate(fiber, update);
              }

              if (fiber.expirationTime < renderExpirationTime) {
                fiber.expirationTime = renderExpirationTime;
              }

              var alternate = fiber.alternate;

              if (alternate !== null && alternate.expirationTime < renderExpirationTime) {
                alternate.expirationTime = renderExpirationTime;
              }

              scheduleWorkOnParentPath(fiber.return, renderExpirationTime); // Mark the expiration time on the list, too.

              if (list.expirationTime < renderExpirationTime) {
                list.expirationTime = renderExpirationTime;
              } // Since we already found a match, we can stop traversing the
              // dependency list.


              break;
            }

            dependency = dependency.next;
          }
        } else if (fiber.tag === ContextProvider) {
          // Don't scan deeper if this is a matching provider
          nextFiber = fiber.type === workInProgress.type ? null : fiber.child;
        } else {
          // Traverse down.
          nextFiber = fiber.child;
        }

        if (nextFiber !== null) {
          // Set the return pointer of the child to the work-in-progress fiber.
          nextFiber.return = fiber;
        } else {
          // No child. Traverse to next sibling.
          nextFiber = fiber;

          while (nextFiber !== null) {
            if (nextFiber === workInProgress) {
              // We're back to the root of this subtree. Exit.
              nextFiber = null;
              break;
            }

            var sibling = nextFiber.sibling;

            if (sibling !== null) {
              // Set the return pointer of the sibling to the work-in-progress fiber.
              sibling.return = nextFiber.return;
              nextFiber = sibling;
              break;
            } // No more siblings. Traverse up.


            nextFiber = nextFiber.return;
          }
        }

        fiber = nextFiber;
      }
    }

    function prepareToReadContext(workInProgress, renderExpirationTime) {
      currentlyRenderingFiber = workInProgress;
      lastContextDependency = null;
      lastContextWithAllBitsObserved = null;
      var dependencies = workInProgress.dependencies;

      if (dependencies !== null) {
        var firstContext = dependencies.firstContext;

        if (firstContext !== null) {
          if (dependencies.expirationTime >= renderExpirationTime) {
            // Context list has a pending update. Mark that this fiber performed work.
            markWorkInProgressReceivedUpdate();
          } // Reset the work-in-progress list


          dependencies.firstContext = null;
        }
      }
    }

    function readContext(context, observedBits) {
      {
        // This warning would fire if you read context inside a Hook like useMemo.
        // Unlike the class check below, it's not enforced in production for perf.
        if (isDisallowedContextReadInDEV) {
          error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().');
        }
      }
      if (lastContextWithAllBitsObserved === context) ;else if (observedBits === false || observedBits === 0) ;else {
        var resolvedObservedBits; // Avoid deopting on observable arguments or heterogeneous types.

        if (typeof observedBits !== 'number' || observedBits === MAX_SIGNED_31_BIT_INT) {
          // Observe all updates.
          lastContextWithAllBitsObserved = context;
          resolvedObservedBits = MAX_SIGNED_31_BIT_INT;
        } else {
          resolvedObservedBits = observedBits;
        }

        var contextItem = {
          context: context,
          observedBits: resolvedObservedBits,
          next: null
        };

        if (lastContextDependency === null) {
          if (!(currentlyRenderingFiber !== null)) {
            {
              throw Error("Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo().");
            }
          } // This is the first dependency for this component. Create a new list.


          lastContextDependency = contextItem;
          currentlyRenderingFiber.dependencies = {
            expirationTime: NoWork,
            firstContext: contextItem,
            responders: null
          };
        } else {
          // Append a new context item.
          lastContextDependency = lastContextDependency.next = contextItem;
        }
      }
      return context._currentValue;
    }

    var UpdateState = 0;
    var ReplaceState = 1;
    var ForceUpdate = 2;
    var CaptureUpdate = 3; // Global state that is reset at the beginning of calling `processUpdateQueue`.
    // It should only be read right after calling `processUpdateQueue`, via
    // `checkHasForceUpdateAfterProcessing`.

    var hasForceUpdate = false;
    var didWarnUpdateInsideUpdate;
    var currentlyProcessingQueue;
    {
      didWarnUpdateInsideUpdate = false;
      currentlyProcessingQueue = null;
    }

    function initializeUpdateQueue(fiber) {
      var queue = {
        baseState: fiber.memoizedState,
        baseQueue: null,
        shared: {
          pending: null
        },
        effects: null
      };
      fiber.updateQueue = queue;
    }

    function cloneUpdateQueue(current, workInProgress) {
      // Clone the update queue from current. Unless it's already a clone.
      var queue = workInProgress.updateQueue;
      var currentQueue = current.updateQueue;

      if (queue === currentQueue) {
        var clone = {
          baseState: currentQueue.baseState,
          baseQueue: currentQueue.baseQueue,
          shared: currentQueue.shared,
          effects: currentQueue.effects
        };
        workInProgress.updateQueue = clone;
      }
    }

    function createUpdate(expirationTime, suspenseConfig) {
      var update = {
        expirationTime: expirationTime,
        suspenseConfig: suspenseConfig,
        tag: UpdateState,
        payload: null,
        callback: null,
        next: null
      };
      update.next = update;
      {
        update.priority = getCurrentPriorityLevel();
      }
      return update;
    }

    function enqueueUpdate(fiber, update) {
      var updateQueue = fiber.updateQueue;

      if (updateQueue === null) {
        // Only occurs if the fiber has been unmounted.
        return;
      }

      var sharedQueue = updateQueue.shared;
      var pending = sharedQueue.pending;

      if (pending === null) {
        // This is the first update. Create a circular list.
        update.next = update;
      } else {
        update.next = pending.next;
        pending.next = update;
      }

      sharedQueue.pending = update;
      {
        if (currentlyProcessingQueue === sharedQueue && !didWarnUpdateInsideUpdate) {
          error('An update (setState, replaceState, or forceUpdate) was scheduled ' + 'from inside an update function. Update functions should be pure, ' + 'with zero side-effects. Consider using componentDidUpdate or a ' + 'callback.');
          didWarnUpdateInsideUpdate = true;
        }
      }
    }

    function enqueueCapturedUpdate(workInProgress, update) {
      var current = workInProgress.alternate;

      if (current !== null) {
        // Ensure the work-in-progress queue is a clone
        cloneUpdateQueue(current, workInProgress);
      } // Captured updates go only on the work-in-progress queue.


      var queue = workInProgress.updateQueue; // Append the update to the end of the list.

      var last = queue.baseQueue;

      if (last === null) {
        queue.baseQueue = update.next = update;
        update.next = update;
      } else {
        update.next = last.next;
        last.next = update;
      }
    }

    function getStateFromUpdate(workInProgress, queue, update, prevState, nextProps, instance) {
      switch (update.tag) {
        case ReplaceState:
          {
            var payload = update.payload;

            if (typeof payload === 'function') {
              // Updater function
              {
                enterDisallowedContextReadInDEV();

                if (workInProgress.mode & StrictMode) {
                  payload.call(instance, prevState, nextProps);
                }
              }
              var nextState = payload.call(instance, prevState, nextProps);
              {
                exitDisallowedContextReadInDEV();
              }
              return nextState;
            } // State object


            return payload;
          }

        case CaptureUpdate:
          {
            workInProgress.effectTag = workInProgress.effectTag & ~ShouldCapture | DidCapture;
          }
        // Intentional fallthrough

        case UpdateState:
          {
            var _payload = update.payload;
            var partialState;

            if (typeof _payload === 'function') {
              // Updater function
              {
                enterDisallowedContextReadInDEV();

                if (workInProgress.mode & StrictMode) {
                  _payload.call(instance, prevState, nextProps);
                }
              }
              partialState = _payload.call(instance, prevState, nextProps);
              {
                exitDisallowedContextReadInDEV();
              }
            } else {
              // Partial state object
              partialState = _payload;
            }

            if (partialState === null || partialState === undefined) {
              // Null and undefined are treated as no-ops.
              return prevState;
            } // Merge the partial state and the previous state.


            return _assign({}, prevState, partialState);
          }

        case ForceUpdate:
          {
            hasForceUpdate = true;
            return prevState;
          }
      }

      return prevState;
    }

    function processUpdateQueue(workInProgress, props, instance, renderExpirationTime) {
      // This is always non-null on a ClassComponent or HostRoot
      var queue = workInProgress.updateQueue;
      hasForceUpdate = false;
      {
        currentlyProcessingQueue = queue.shared;
      } // The last rebase update that is NOT part of the base state.

      var baseQueue = queue.baseQueue; // The last pending update that hasn't been processed yet.

      var pendingQueue = queue.shared.pending;

      if (pendingQueue !== null) {
        // We have new updates that haven't been processed yet.
        // We'll add them to the base queue.
        if (baseQueue !== null) {
          // Merge the pending queue and the base queue.
          var baseFirst = baseQueue.next;
          var pendingFirst = pendingQueue.next;
          baseQueue.next = pendingFirst;
          pendingQueue.next = baseFirst;
        }

        baseQueue = pendingQueue;
        queue.shared.pending = null; // TODO: Pass `current` as argument

        var current = workInProgress.alternate;

        if (current !== null) {
          var currentQueue = current.updateQueue;

          if (currentQueue !== null) {
            currentQueue.baseQueue = pendingQueue;
          }
        }
      } // These values may change as we process the queue.


      if (baseQueue !== null) {
        var first = baseQueue.next; // Iterate through the list of updates to compute the result.

        var newState = queue.baseState;
        var newExpirationTime = NoWork;
        var newBaseState = null;
        var newBaseQueueFirst = null;
        var newBaseQueueLast = null;

        if (first !== null) {
          var update = first;

          do {
            var updateExpirationTime = update.expirationTime;

            if (updateExpirationTime < renderExpirationTime) {
              // Priority is insufficient. Skip this update. If this is the first
              // skipped update, the previous update/state is the new base
              // update/state.
              var clone = {
                expirationTime: update.expirationTime,
                suspenseConfig: update.suspenseConfig,
                tag: update.tag,
                payload: update.payload,
                callback: update.callback,
                next: null
              };

              if (newBaseQueueLast === null) {
                newBaseQueueFirst = newBaseQueueLast = clone;
                newBaseState = newState;
              } else {
                newBaseQueueLast = newBaseQueueLast.next = clone;
              } // Update the remaining priority in the queue.


              if (updateExpirationTime > newExpirationTime) {
                newExpirationTime = updateExpirationTime;
              }
            } else {
              // This update does have sufficient priority.
              if (newBaseQueueLast !== null) {
                var _clone = {
                  expirationTime: Sync,
                  // This update is going to be committed so we never want uncommit it.
                  suspenseConfig: update.suspenseConfig,
                  tag: update.tag,
                  payload: update.payload,
                  callback: update.callback,
                  next: null
                };
                newBaseQueueLast = newBaseQueueLast.next = _clone;
              } // Mark the event time of this update as relevant to this render pass.
              // TODO: This should ideally use the true event time of this update rather than
              // its priority which is a derived and not reverseable value.
              // TODO: We should skip this update if it was already committed but currently
              // we have no way of detecting the difference between a committed and suspended
              // update here.


              markRenderEventTimeAndConfig(updateExpirationTime, update.suspenseConfig); // Process this update.

              newState = getStateFromUpdate(workInProgress, queue, update, newState, props, instance);
              var callback = update.callback;

              if (callback !== null) {
                workInProgress.effectTag |= Callback;
                var effects = queue.effects;

                if (effects === null) {
                  queue.effects = [update];
                } else {
                  effects.push(update);
                }
              }
            }

            update = update.next;

            if (update === null || update === first) {
              pendingQueue = queue.shared.pending;

              if (pendingQueue === null) {
                break;
              } else {
                // An update was scheduled from inside a reducer. Add the new
                // pending updates to the end of the list and keep processing.
                update = baseQueue.next = pendingQueue.next;
                pendingQueue.next = first;
                queue.baseQueue = baseQueue = pendingQueue;
                queue.shared.pending = null;
              }
            }
          } while (true);
        }

        if (newBaseQueueLast === null) {
          newBaseState = newState;
        } else {
          newBaseQueueLast.next = newBaseQueueFirst;
        }

        queue.baseState = newBaseState;
        queue.baseQueue = newBaseQueueLast; // Set the remaining expiration time to be whatever is remaining in the queue.
        // This should be fine because the only two other things that contribute to
        // expiration time are props and context. We're already in the middle of the
        // begin phase by the time we start processing the queue, so we've already
        // dealt with the props. Context in components that specify
        // shouldComponentUpdate is tricky; but we'll have to account for
        // that regardless.

        markUnprocessedUpdateTime(newExpirationTime);
        workInProgress.expirationTime = newExpirationTime;
        workInProgress.memoizedState = newState;
      }

      {
        currentlyProcessingQueue = null;
      }
    }

    function callCallback(callback, context) {
      if (!(typeof callback === 'function')) {
        {
          throw Error("Invalid argument passed as callback. Expected a function. Instead received: " + callback);
        }
      }

      callback.call(context);
    }

    function resetHasForceUpdateBeforeProcessing() {
      hasForceUpdate = false;
    }

    function checkHasForceUpdateAfterProcessing() {
      return hasForceUpdate;
    }

    function commitUpdateQueue(finishedWork, finishedQueue, instance) {
      // Commit the effects
      var effects = finishedQueue.effects;
      finishedQueue.effects = null;

      if (effects !== null) {
        for (var i = 0; i < effects.length; i++) {
          var effect = effects[i];
          var callback = effect.callback;

          if (callback !== null) {
            effect.callback = null;
            callCallback(callback, instance);
          }
        }
      }
    }

    var ReactCurrentBatchConfig = ReactSharedInternals.ReactCurrentBatchConfig;

    function requestCurrentSuspenseConfig() {
      return ReactCurrentBatchConfig.suspense;
    }

    var fakeInternalInstance = {};
    var isArray = Array.isArray; // React.Component uses a shared frozen object by default.
    // We'll use it to determine whether we need to initialize legacy refs.

    var emptyRefsObject = new React.Component().refs;
    var didWarnAboutStateAssignmentForComponent;
    var didWarnAboutUninitializedState;
    var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate;
    var didWarnAboutLegacyLifecyclesAndDerivedState;
    var didWarnAboutUndefinedDerivedState;
    var warnOnUndefinedDerivedState;
    var warnOnInvalidCallback;
    var didWarnAboutDirectlyAssigningPropsToState;
    var didWarnAboutContextTypeAndContextTypes;
    var didWarnAboutInvalidateContextType;
    {
      didWarnAboutStateAssignmentForComponent = new Set();
      didWarnAboutUninitializedState = new Set();
      didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set();
      didWarnAboutLegacyLifecyclesAndDerivedState = new Set();
      didWarnAboutDirectlyAssigningPropsToState = new Set();
      didWarnAboutUndefinedDerivedState = new Set();
      didWarnAboutContextTypeAndContextTypes = new Set();
      didWarnAboutInvalidateContextType = new Set();
      var didWarnOnInvalidCallback = new Set();

      warnOnInvalidCallback = function (callback, callerName) {
        if (callback === null || typeof callback === 'function') {
          return;
        }

        var key = callerName + "_" + callback;

        if (!didWarnOnInvalidCallback.has(key)) {
          didWarnOnInvalidCallback.add(key);
          error('%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback);
        }
      };

      warnOnUndefinedDerivedState = function (type, partialState) {
        if (partialState === undefined) {
          var componentName = getComponentName(type) || 'Component';

          if (!didWarnAboutUndefinedDerivedState.has(componentName)) {
            didWarnAboutUndefinedDerivedState.add(componentName);
            error('%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName);
          }
        }
      }; // This is so gross but it's at least non-critical and can be removed if
      // it causes problems. This is meant to give a nicer error message for
      // ReactDOM15.unstable_renderSubtreeIntoContainer(reactDOM16Component,
      // ...)) which otherwise throws a "_processChildContext is not a function"
      // exception.


      Object.defineProperty(fakeInternalInstance, '_processChildContext', {
        enumerable: false,
        value: function () {
          {
            {
              throw Error("_processChildContext is not available in React 16+. This likely means you have multiple copies of React and are attempting to nest a React 15 tree inside a React 16 tree using unstable_renderSubtreeIntoContainer, which isn't supported. Try to make sure you have only one copy of React (and ideally, switch to ReactDOM.createPortal).");
            }
          }
        }
      });
      Object.freeze(fakeInternalInstance);
    }

    function applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, nextProps) {
      var prevState = workInProgress.memoizedState;
      {
        if (workInProgress.mode & StrictMode) {
          // Invoke the function an extra time to help detect side-effects.
          getDerivedStateFromProps(nextProps, prevState);
        }
      }
      var partialState = getDerivedStateFromProps(nextProps, prevState);
      {
        warnOnUndefinedDerivedState(ctor, partialState);
      } // Merge the partial state and the previous state.

      var memoizedState = partialState === null || partialState === undefined ? prevState : _assign({}, prevState, partialState);
      workInProgress.memoizedState = memoizedState; // Once the update queue is empty, persist the derived state onto the
      // base state.

      if (workInProgress.expirationTime === NoWork) {
        // Queue is always non-null for classes
        var updateQueue = workInProgress.updateQueue;
        updateQueue.baseState = memoizedState;
      }
    }

    var classComponentUpdater = {
      isMounted: isMounted,
      enqueueSetState: function (inst, payload, callback) {
        var fiber = get(inst);
        var currentTime = requestCurrentTimeForUpdate();
        var suspenseConfig = requestCurrentSuspenseConfig();
        var expirationTime = computeExpirationForFiber(currentTime, fiber, suspenseConfig);
        var update = createUpdate(expirationTime, suspenseConfig);
        update.payload = payload;

        if (callback !== undefined && callback !== null) {
          {
            warnOnInvalidCallback(callback, 'setState');
          }
          update.callback = callback;
        }

        enqueueUpdate(fiber, update);
        scheduleWork(fiber, expirationTime);
      },
      enqueueReplaceState: function (inst, payload, callback) {
        var fiber = get(inst);
        var currentTime = requestCurrentTimeForUpdate();
        var suspenseConfig = requestCurrentSuspenseConfig();
        var expirationTime = computeExpirationForFiber(currentTime, fiber, suspenseConfig);
        var update = createUpdate(expirationTime, suspenseConfig);
        update.tag = ReplaceState;
        update.payload = payload;

        if (callback !== undefined && callback !== null) {
          {
            warnOnInvalidCallback(callback, 'replaceState');
          }
          update.callback = callback;
        }

        enqueueUpdate(fiber, update);
        scheduleWork(fiber, expirationTime);
      },
      enqueueForceUpdate: function (inst, callback) {
        var fiber = get(inst);
        var currentTime = requestCurrentTimeForUpdate();
        var suspenseConfig = requestCurrentSuspenseConfig();
        var expirationTime = computeExpirationForFiber(currentTime, fiber, suspenseConfig);
        var update = createUpdate(expirationTime, suspenseConfig);
        update.tag = ForceUpdate;

        if (callback !== undefined && callback !== null) {
          {
            warnOnInvalidCallback(callback, 'forceUpdate');
          }
          update.callback = callback;
        }

        enqueueUpdate(fiber, update);
        scheduleWork(fiber, expirationTime);
      }
    };

    function checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext) {
      var instance = workInProgress.stateNode;

      if (typeof instance.shouldComponentUpdate === 'function') {
        {
          if (workInProgress.mode & StrictMode) {
            // Invoke the function an extra time to help detect side-effects.
            instance.shouldComponentUpdate(newProps, newState, nextContext);
          }
        }
        startPhaseTimer(workInProgress, 'shouldComponentUpdate');
        var shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext);
        stopPhaseTimer();
        {
          if (shouldUpdate === undefined) {
            error('%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', getComponentName(ctor) || 'Component');
          }
        }
        return shouldUpdate;
      }

      if (ctor.prototype && ctor.prototype.isPureReactComponent) {
        return !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState);
      }

      return true;
    }

    function checkClassInstance(workInProgress, ctor, newProps) {
      var instance = workInProgress.stateNode;
      {
        var name = getComponentName(ctor) || 'Component';
        var renderPresent = instance.render;

        if (!renderPresent) {
          if (ctor.prototype && typeof ctor.prototype.render === 'function') {
            error('%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name);
          } else {
            error('%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name);
          }
        }

        if (instance.getInitialState && !instance.getInitialState.isReactClassApproved && !instance.state) {
          error('getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', name);
        }

        if (instance.getDefaultProps && !instance.getDefaultProps.isReactClassApproved) {
          error('getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', name);
        }

        if (instance.propTypes) {
          error('propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name);
        }

        if (instance.contextType) {
          error('contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name);
        }

        {
          if (instance.contextTypes) {
            error('contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name);
          }

          if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) {
            didWarnAboutContextTypeAndContextTypes.add(ctor);
            error('%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name);
          }
        }

        if (typeof instance.componentShouldUpdate === 'function') {
          error('%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', name);
        }

        if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') {
          error('%s has a method called shouldComponentUpdate(). ' + 'shouldComponentUpdate should not be used when extending React.PureComponent. ' + 'Please extend React.Component if shouldComponentUpdate is used.', getComponentName(ctor) || 'A pure component');
        }

        if (typeof instance.componentDidUnmount === 'function') {
          error('%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name);
        }

        if (typeof instance.componentDidReceiveProps === 'function') {
          error('%s has a method called ' + 'componentDidReceiveProps(). But there is no such lifecycle method. ' + 'If you meant to update the state in response to changing props, ' + 'use componentWillReceiveProps(). If you meant to fetch data or ' + 'run side-effects or mutations after React has updated the UI, use componentDidUpdate().', name);
        }

        if (typeof instance.componentWillRecieveProps === 'function') {
          error('%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name);
        }

        if (typeof instance.UNSAFE_componentWillRecieveProps === 'function') {
          error('%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name);
        }

        var hasMutatedProps = instance.props !== newProps;

        if (instance.props !== undefined && hasMutatedProps) {
          error('%s(...): When calling super() in `%s`, make sure to pass ' + "up the same props that your component's constructor was passed.", name, name);
        }

        if (instance.defaultProps) {
          error('Setting defaultProps as an instance property on %s is not supported and will be ignored.' + ' Instead, define defaultProps as a static property on %s.', name, name);
        }

        if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) {
          didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor);
          error('%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentName(ctor));
        }

        if (typeof instance.getDerivedStateFromProps === 'function') {
          error('%s: getDerivedStateFromProps() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name);
        }

        if (typeof instance.getDerivedStateFromError === 'function') {
          error('%s: getDerivedStateFromError() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name);
        }

        if (typeof ctor.getSnapshotBeforeUpdate === 'function') {
          error('%s: getSnapshotBeforeUpdate() is defined as a static method ' + 'and will be ignored. Instead, declare it as an instance method.', name);
        }

        var _state = instance.state;

        if (_state && (typeof _state !== 'object' || isArray(_state))) {
          error('%s.state: must be set to an object or null', name);
        }

        if (typeof instance.getChildContext === 'function' && typeof ctor.childContextTypes !== 'object') {
          error('%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name);
        }
      }
    }

    function adoptClassInstance(workInProgress, instance) {
      instance.updater = classComponentUpdater;
      workInProgress.stateNode = instance; // The instance needs access to the fiber so that it can schedule updates

      set(instance, workInProgress);
      {
        instance._reactInternalInstance = fakeInternalInstance;
      }
    }

    function constructClassInstance(workInProgress, ctor, props) {
      var isLegacyContextConsumer = false;
      var unmaskedContext = emptyContextObject;
      var context = emptyContextObject;
      var contextType = ctor.contextType;
      {
        if ('contextType' in ctor) {
          var isValid = // Allow null for conditional declaration
          contextType === null || contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === undefined; // Not a <Context.Consumer>

          if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) {
            didWarnAboutInvalidateContextType.add(ctor);
            var addendum = '';

            if (contextType === undefined) {
              addendum = ' However, it is set to undefined. ' + 'This can be caused by a typo or by mixing up named and default imports. ' + 'This can also happen due to a circular dependency, so ' + 'try moving the createContext() call to a separate file.';
            } else if (typeof contextType !== 'object') {
              addendum = ' However, it is set to a ' + typeof contextType + '.';
            } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) {
              addendum = ' Did you accidentally pass the Context.Provider instead?';
            } else if (contextType._context !== undefined) {
              // <Context.Consumer>
              addendum = ' Did you accidentally pass the Context.Consumer instead?';
            } else {
              addendum = ' However, it is set to an object with keys {' + Object.keys(contextType).join(', ') + '}.';
            }

            error('%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext().%s', getComponentName(ctor) || 'Component', addendum);
          }
        }
      }

      if (typeof contextType === 'object' && contextType !== null) {
        context = readContext(contextType);
      } else {
        unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
        var contextTypes = ctor.contextTypes;
        isLegacyContextConsumer = contextTypes !== null && contextTypes !== undefined;
        context = isLegacyContextConsumer ? getMaskedContext(workInProgress, unmaskedContext) : emptyContextObject;
      } // Instantiate twice to help detect side-effects.


      {
        if (workInProgress.mode & StrictMode) {
          new ctor(props, context); // eslint-disable-line no-new
        }
      }
      var instance = new ctor(props, context);
      var state = workInProgress.memoizedState = instance.state !== null && instance.state !== undefined ? instance.state : null;
      adoptClassInstance(workInProgress, instance);
      {
        if (typeof ctor.getDerivedStateFromProps === 'function' && state === null) {
          var componentName = getComponentName(ctor) || 'Component';

          if (!didWarnAboutUninitializedState.has(componentName)) {
            didWarnAboutUninitializedState.add(componentName);
            error('`%s` uses `getDerivedStateFromProps` but its initial state is ' + '%s. This is not recommended. Instead, define the initial state by ' + 'assigning an object to `this.state` in the constructor of `%s`. ' + 'This ensures that `getDerivedStateFromProps` arguments have a consistent shape.', componentName, instance.state === null ? 'null' : 'undefined', componentName);
          }
        } // If new component APIs are defined, "unsafe" lifecycles won't be called.
        // Warn about these lifecycles if they are present.
        // Don't warn about react-lifecycles-compat polyfilled methods though.


        if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') {
          var foundWillMountName = null;
          var foundWillReceivePropsName = null;
          var foundWillUpdateName = null;

          if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {
            foundWillMountName = 'componentWillMount';
          } else if (typeof instance.UNSAFE_componentWillMount === 'function') {
            foundWillMountName = 'UNSAFE_componentWillMount';
          }

          if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
            foundWillReceivePropsName = 'componentWillReceiveProps';
          } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
            foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';
          }

          if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
            foundWillUpdateName = 'componentWillUpdate';
          } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
            foundWillUpdateName = 'UNSAFE_componentWillUpdate';
          }

          if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) {
            var _componentName = getComponentName(ctor) || 'Component';

            var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()';

            if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) {
              didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName);
              error('Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' + '%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n' + 'The above lifecycles should be removed. Learn more about this warning here:\n' + 'https://fb.me/react-unsafe-component-lifecycles', _componentName, newApiName, foundWillMountName !== null ? "\n  " + foundWillMountName : '', foundWillReceivePropsName !== null ? "\n  " + foundWillReceivePropsName : '', foundWillUpdateName !== null ? "\n  " + foundWillUpdateName : '');
            }
          }
        }
      } // Cache unmasked context so we can avoid recreating masked context unless necessary.
      // ReactFiberContext usually updates this cache but can't for newly-created instances.

      if (isLegacyContextConsumer) {
        cacheContext(workInProgress, unmaskedContext, context);
      }

      return instance;
    }

    function callComponentWillMount(workInProgress, instance) {
      startPhaseTimer(workInProgress, 'componentWillMount');
      var oldState = instance.state;

      if (typeof instance.componentWillMount === 'function') {
        instance.componentWillMount();
      }

      if (typeof instance.UNSAFE_componentWillMount === 'function') {
        instance.UNSAFE_componentWillMount();
      }

      stopPhaseTimer();

      if (oldState !== instance.state) {
        {
          error('%s.componentWillMount(): Assigning directly to this.state is ' + "deprecated (except inside a component's " + 'constructor). Use setState instead.', getComponentName(workInProgress.type) || 'Component');
        }
        classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
      }
    }

    function callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext) {
      var oldState = instance.state;
      startPhaseTimer(workInProgress, 'componentWillReceiveProps');

      if (typeof instance.componentWillReceiveProps === 'function') {
        instance.componentWillReceiveProps(newProps, nextContext);
      }

      if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
        instance.UNSAFE_componentWillReceiveProps(newProps, nextContext);
      }

      stopPhaseTimer();

      if (instance.state !== oldState) {
        {
          var componentName = getComponentName(workInProgress.type) || 'Component';

          if (!didWarnAboutStateAssignmentForComponent.has(componentName)) {
            didWarnAboutStateAssignmentForComponent.add(componentName);
            error('%s.componentWillReceiveProps(): Assigning directly to ' + "this.state is deprecated (except inside a component's " + 'constructor). Use setState instead.', componentName);
          }
        }
        classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
      }
    } // Invokes the mount life-cycles on a previously never rendered instance.


    function mountClassInstance(workInProgress, ctor, newProps, renderExpirationTime) {
      {
        checkClassInstance(workInProgress, ctor, newProps);
      }
      var instance = workInProgress.stateNode;
      instance.props = newProps;
      instance.state = workInProgress.memoizedState;
      instance.refs = emptyRefsObject;
      initializeUpdateQueue(workInProgress);
      var contextType = ctor.contextType;

      if (typeof contextType === 'object' && contextType !== null) {
        instance.context = readContext(contextType);
      } else {
        var unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
        instance.context = getMaskedContext(workInProgress, unmaskedContext);
      }

      {
        if (instance.state === newProps) {
          var componentName = getComponentName(ctor) || 'Component';

          if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) {
            didWarnAboutDirectlyAssigningPropsToState.add(componentName);
            error('%s: It is not recommended to assign props directly to state ' + "because updates to props won't be reflected in state. " + 'In most cases, it is better to use props directly.', componentName);
          }
        }

        if (workInProgress.mode & StrictMode) {
          ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, instance);
        }

        {
          ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(workInProgress, instance);
        }
      }
      processUpdateQueue(workInProgress, newProps, instance, renderExpirationTime);
      instance.state = workInProgress.memoizedState;
      var getDerivedStateFromProps = ctor.getDerivedStateFromProps;

      if (typeof getDerivedStateFromProps === 'function') {
        applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
        instance.state = workInProgress.memoizedState;
      } // In order to support react-lifecycles-compat polyfilled components,
      // Unsafe lifecycles should not be invoked for components using the new APIs.


      if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
        callComponentWillMount(workInProgress, instance); // If we had additional state updates during this life-cycle, let's
        // process them now.

        processUpdateQueue(workInProgress, newProps, instance, renderExpirationTime);
        instance.state = workInProgress.memoizedState;
      }

      if (typeof instance.componentDidMount === 'function') {
        workInProgress.effectTag |= Update;
      }
    }

    function resumeMountClassInstance(workInProgress, ctor, newProps, renderExpirationTime) {
      var instance = workInProgress.stateNode;
      var oldProps = workInProgress.memoizedProps;
      instance.props = oldProps;
      var oldContext = instance.context;
      var contextType = ctor.contextType;
      var nextContext = emptyContextObject;

      if (typeof contextType === 'object' && contextType !== null) {
        nextContext = readContext(contextType);
      } else {
        var nextLegacyUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
        nextContext = getMaskedContext(workInProgress, nextLegacyUnmaskedContext);
      }

      var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
      var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what
      // ever the previously attempted to render - not the "current". However,
      // during componentDidUpdate we pass the "current" props.
      // In order to support react-lifecycles-compat polyfilled components,
      // Unsafe lifecycles should not be invoked for components using the new APIs.

      if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
        if (oldProps !== newProps || oldContext !== nextContext) {
          callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);
        }
      }

      resetHasForceUpdateBeforeProcessing();
      var oldState = workInProgress.memoizedState;
      var newState = instance.state = oldState;
      processUpdateQueue(workInProgress, newProps, instance, renderExpirationTime);
      newState = workInProgress.memoizedState;

      if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
        // If an update was already in progress, we should schedule an Update
        // effect even though we're bailing out, so that cWU/cDU are called.
        if (typeof instance.componentDidMount === 'function') {
          workInProgress.effectTag |= Update;
        }

        return false;
      }

      if (typeof getDerivedStateFromProps === 'function') {
        applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
        newState = workInProgress.memoizedState;
      }

      var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext);

      if (shouldUpdate) {
        // In order to support react-lifecycles-compat polyfilled components,
        // Unsafe lifecycles should not be invoked for components using the new APIs.
        if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
          startPhaseTimer(workInProgress, 'componentWillMount');

          if (typeof instance.componentWillMount === 'function') {
            instance.componentWillMount();
          }

          if (typeof instance.UNSAFE_componentWillMount === 'function') {
            instance.UNSAFE_componentWillMount();
          }

          stopPhaseTimer();
        }

        if (typeof instance.componentDidMount === 'function') {
          workInProgress.effectTag |= Update;
        }
      } else {
        // If an update was already in progress, we should schedule an Update
        // effect even though we're bailing out, so that cWU/cDU are called.
        if (typeof instance.componentDidMount === 'function') {
          workInProgress.effectTag |= Update;
        } // If shouldComponentUpdate returned false, we should still update the
        // memoized state to indicate that this work can be reused.


        workInProgress.memoizedProps = newProps;
        workInProgress.memoizedState = newState;
      } // Update the existing instance's state, props, and context pointers even
      // if shouldComponentUpdate returns false.


      instance.props = newProps;
      instance.state = newState;
      instance.context = nextContext;
      return shouldUpdate;
    } // Invokes the update life-cycles and returns false if it shouldn't rerender.


    function updateClassInstance(current, workInProgress, ctor, newProps, renderExpirationTime) {
      var instance = workInProgress.stateNode;
      cloneUpdateQueue(current, workInProgress);
      var oldProps = workInProgress.memoizedProps;
      instance.props = workInProgress.type === workInProgress.elementType ? oldProps : resolveDefaultProps(workInProgress.type, oldProps);
      var oldContext = instance.context;
      var contextType = ctor.contextType;
      var nextContext = emptyContextObject;

      if (typeof contextType === 'object' && contextType !== null) {
        nextContext = readContext(contextType);
      } else {
        var nextUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
        nextContext = getMaskedContext(workInProgress, nextUnmaskedContext);
      }

      var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
      var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what
      // ever the previously attempted to render - not the "current". However,
      // during componentDidUpdate we pass the "current" props.
      // In order to support react-lifecycles-compat polyfilled components,
      // Unsafe lifecycles should not be invoked for components using the new APIs.

      if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
        if (oldProps !== newProps || oldContext !== nextContext) {
          callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);
        }
      }

      resetHasForceUpdateBeforeProcessing();
      var oldState = workInProgress.memoizedState;
      var newState = instance.state = oldState;
      processUpdateQueue(workInProgress, newProps, instance, renderExpirationTime);
      newState = workInProgress.memoizedState;

      if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
        // If an update was already in progress, we should schedule an Update
        // effect even though we're bailing out, so that cWU/cDU are called.
        if (typeof instance.componentDidUpdate === 'function') {
          if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
            workInProgress.effectTag |= Update;
          }
        }

        if (typeof instance.getSnapshotBeforeUpdate === 'function') {
          if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
            workInProgress.effectTag |= Snapshot;
          }
        }

        return false;
      }

      if (typeof getDerivedStateFromProps === 'function') {
        applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
        newState = workInProgress.memoizedState;
      }

      var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext);

      if (shouldUpdate) {
        // In order to support react-lifecycles-compat polyfilled components,
        // Unsafe lifecycles should not be invoked for components using the new APIs.
        if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillUpdate === 'function' || typeof instance.componentWillUpdate === 'function')) {
          startPhaseTimer(workInProgress, 'componentWillUpdate');

          if (typeof instance.componentWillUpdate === 'function') {
            instance.componentWillUpdate(newProps, newState, nextContext);
          }

          if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
            instance.UNSAFE_componentWillUpdate(newProps, newState, nextContext);
          }

          stopPhaseTimer();
        }

        if (typeof instance.componentDidUpdate === 'function') {
          workInProgress.effectTag |= Update;
        }

        if (typeof instance.getSnapshotBeforeUpdate === 'function') {
          workInProgress.effectTag |= Snapshot;
        }
      } else {
        // If an update was already in progress, we should schedule an Update
        // effect even though we're bailing out, so that cWU/cDU are called.
        if (typeof instance.componentDidUpdate === 'function') {
          if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
            workInProgress.effectTag |= Update;
          }
        }

        if (typeof instance.getSnapshotBeforeUpdate === 'function') {
          if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
            workInProgress.effectTag |= Snapshot;
          }
        } // If shouldComponentUpdate returned false, we should still update the
        // memoized props/state to indicate that this work can be reused.


        workInProgress.memoizedProps = newProps;
        workInProgress.memoizedState = newState;
      } // Update the existing instance's state, props, and context pointers even
      // if shouldComponentUpdate returns false.


      instance.props = newProps;
      instance.state = newState;
      instance.context = nextContext;
      return shouldUpdate;
    }

    var didWarnAboutMaps;
    var didWarnAboutGenerators;
    var didWarnAboutStringRefs;
    var ownerHasKeyUseWarning;
    var ownerHasFunctionTypeWarning;

    var warnForMissingKey = function (child) {};

    {
      didWarnAboutMaps = false;
      didWarnAboutGenerators = false;
      didWarnAboutStringRefs = {};
      /**
       * Warn if there's no key explicitly set on dynamic arrays of children or
       * object keys are not valid. This allows us to keep track of children between
       * updates.
       */

      ownerHasKeyUseWarning = {};
      ownerHasFunctionTypeWarning = {};

      warnForMissingKey = function (child) {
        if (child === null || typeof child !== 'object') {
          return;
        }

        if (!child._store || child._store.validated || child.key != null) {
          return;
        }

        if (!(typeof child._store === 'object')) {
          {
            throw Error("React Component in warnForMissingKey should have a _store. This error is likely caused by a bug in React. Please file an issue.");
          }
        }

        child._store.validated = true;
        var currentComponentErrorInfo = 'Each child in a list should have a unique ' + '"key" prop. See https://fb.me/react-warning-keys for ' + 'more information.' + getCurrentFiberStackInDev();

        if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
          return;
        }

        ownerHasKeyUseWarning[currentComponentErrorInfo] = true;
        error('Each child in a list should have a unique ' + '"key" prop. See https://fb.me/react-warning-keys for ' + 'more information.');
      };
    }
    var isArray$1 = Array.isArray;

    function coerceRef(returnFiber, current, element) {
      var mixedRef = element.ref;

      if (mixedRef !== null && typeof mixedRef !== 'function' && typeof mixedRef !== 'object') {
        {
          // TODO: Clean this up once we turn on the string ref warning for
          // everyone, because the strict mode case will no longer be relevant
          if ((returnFiber.mode & StrictMode || warnAboutStringRefs) && // We warn in ReactElement.js if owner and self are equal for string refs
          // because these cannot be automatically converted to an arrow function
          // using a codemod. Therefore, we don't have to warn about string refs again.
          !(element._owner && element._self && element._owner.stateNode !== element._self)) {
            var componentName = getComponentName(returnFiber.type) || 'Component';

            if (!didWarnAboutStringRefs[componentName]) {
              {
                error('A string ref, "%s", has been found within a strict mode tree. ' + 'String refs are a source of potential bugs and should be avoided. ' + 'We recommend using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://fb.me/react-strict-mode-string-ref%s', mixedRef, getStackByFiberInDevAndProd(returnFiber));
              }
              didWarnAboutStringRefs[componentName] = true;
            }
          }
        }

        if (element._owner) {
          var owner = element._owner;
          var inst;

          if (owner) {
            var ownerFiber = owner;

            if (!(ownerFiber.tag === ClassComponent)) {
              {
                throw Error("Function components cannot have string refs. We recommend using useRef() instead. Learn more about using refs safely here: https://fb.me/react-strict-mode-string-ref");
              }
            }

            inst = ownerFiber.stateNode;
          }

          if (!inst) {
            {
              throw Error("Missing owner for string ref " + mixedRef + ". This error is likely caused by a bug in React. Please file an issue.");
            }
          }

          var stringRef = '' + mixedRef; // Check if previous string ref matches new string ref

          if (current !== null && current.ref !== null && typeof current.ref === 'function' && current.ref._stringRef === stringRef) {
            return current.ref;
          }

          var ref = function (value) {
            var refs = inst.refs;

            if (refs === emptyRefsObject) {
              // This is a lazy pooled frozen object, so we need to initialize.
              refs = inst.refs = {};
            }

            if (value === null) {
              delete refs[stringRef];
            } else {
              refs[stringRef] = value;
            }
          };

          ref._stringRef = stringRef;
          return ref;
        } else {
          if (!(typeof mixedRef === 'string')) {
            {
              throw Error("Expected ref to be a function, a string, an object returned by React.createRef(), or null.");
            }
          }

          if (!element._owner) {
            {
              throw Error("Element ref was specified as a string (" + mixedRef + ") but no owner was set. This could happen for one of the following reasons:\n1. You may be adding a ref to a function component\n2. You may be adding a ref to a component that was not created inside a component's render method\n3. You have multiple copies of React loaded\nSee https://fb.me/react-refs-must-have-owner for more information.");
            }
          }
        }
      }

      return mixedRef;
    }

    function throwOnInvalidObjectType(returnFiber, newChild) {
      if (returnFiber.type !== 'textarea') {
        var addendum = '';
        {
          addendum = ' If you meant to render a collection of children, use an array ' + 'instead.' + getCurrentFiberStackInDev();
        }
        {
          {
            throw Error("Objects are not valid as a React child (found: " + (Object.prototype.toString.call(newChild) === '[object Object]' ? 'object with keys {' + Object.keys(newChild).join(', ') + '}' : newChild) + ")." + addendum);
          }
        }
      }
    }

    function warnOnFunctionType() {
      {
        var currentComponentErrorInfo = 'Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of <Component /> from render. ' + 'Or maybe you meant to call this function rather than return it.' + getCurrentFiberStackInDev();

        if (ownerHasFunctionTypeWarning[currentComponentErrorInfo]) {
          return;
        }

        ownerHasFunctionTypeWarning[currentComponentErrorInfo] = true;
        error('Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of <Component /> from render. ' + 'Or maybe you meant to call this function rather than return it.');
      }
    } // This wrapper function exists because I expect to clone the code in each path
    // to be able to optimize each path individually by branching early. This needs
    // a compiler or we can do it manually. Helpers that don't need this branching
    // live outside of this function.


    function ChildReconciler(shouldTrackSideEffects) {
      function deleteChild(returnFiber, childToDelete) {
        if (!shouldTrackSideEffects) {
          // Noop.
          return;
        } // Deletions are added in reversed order so we add it to the front.
        // At this point, the return fiber's effect list is empty except for
        // deletions, so we can just append the deletion to the list. The remaining
        // effects aren't added until the complete phase. Once we implement
        // resuming, this may not be true.


        var last = returnFiber.lastEffect;

        if (last !== null) {
          last.nextEffect = childToDelete;
          returnFiber.lastEffect = childToDelete;
        } else {
          returnFiber.firstEffect = returnFiber.lastEffect = childToDelete;
        }

        childToDelete.nextEffect = null;
        childToDelete.effectTag = Deletion;
      }

      function deleteRemainingChildren(returnFiber, currentFirstChild) {
        if (!shouldTrackSideEffects) {
          // Noop.
          return null;
        } // TODO: For the shouldClone case, this could be micro-optimized a bit by
        // assuming that after the first child we've already added everything.


        var childToDelete = currentFirstChild;

        while (childToDelete !== null) {
          deleteChild(returnFiber, childToDelete);
          childToDelete = childToDelete.sibling;
        }

        return null;
      }

      function mapRemainingChildren(returnFiber, currentFirstChild) {
        // Add the remaining children to a temporary map so that we can find them by
        // keys quickly. Implicit (null) keys get added to this set with their index
        // instead.
        var existingChildren = new Map();
        var existingChild = currentFirstChild;

        while (existingChild !== null) {
          if (existingChild.key !== null) {
            existingChildren.set(existingChild.key, existingChild);
          } else {
            existingChildren.set(existingChild.index, existingChild);
          }

          existingChild = existingChild.sibling;
        }

        return existingChildren;
      }

      function useFiber(fiber, pendingProps) {
        // We currently set sibling to null and index to 0 here because it is easy
        // to forget to do before returning it. E.g. for the single child case.
        var clone = createWorkInProgress(fiber, pendingProps);
        clone.index = 0;
        clone.sibling = null;
        return clone;
      }

      function placeChild(newFiber, lastPlacedIndex, newIndex) {
        newFiber.index = newIndex;

        if (!shouldTrackSideEffects) {
          // Noop.
          return lastPlacedIndex;
        }

        var current = newFiber.alternate;

        if (current !== null) {
          var oldIndex = current.index;

          if (oldIndex < lastPlacedIndex) {
            // This is a move.
            newFiber.effectTag = Placement;
            return lastPlacedIndex;
          } else {
            // This item can stay in place.
            return oldIndex;
          }
        } else {
          // This is an insertion.
          newFiber.effectTag = Placement;
          return lastPlacedIndex;
        }
      }

      function placeSingleChild(newFiber) {
        // This is simpler for the single child case. We only need to do a
        // placement for inserting new children.
        if (shouldTrackSideEffects && newFiber.alternate === null) {
          newFiber.effectTag = Placement;
        }

        return newFiber;
      }

      function updateTextNode(returnFiber, current, textContent, expirationTime) {
        if (current === null || current.tag !== HostText) {
          // Insert
          var created = createFiberFromText(textContent, returnFiber.mode, expirationTime);
          created.return = returnFiber;
          return created;
        } else {
          // Update
          var existing = useFiber(current, textContent);
          existing.return = returnFiber;
          return existing;
        }
      }

      function updateElement(returnFiber, current, element, expirationTime) {
        if (current !== null) {
          if (current.elementType === element.type || // Keep this check inline so it only runs on the false path:
          isCompatibleFamilyForHotReloading(current, element)) {
            // Move based on index
            var existing = useFiber(current, element.props);
            existing.ref = coerceRef(returnFiber, current, element);
            existing.return = returnFiber;
            {
              existing._debugSource = element._source;
              existing._debugOwner = element._owner;
            }
            return existing;
          }
        } // Insert


        var created = createFiberFromElement(element, returnFiber.mode, expirationTime);
        created.ref = coerceRef(returnFiber, current, element);
        created.return = returnFiber;
        return created;
      }

      function updatePortal(returnFiber, current, portal, expirationTime) {
        if (current === null || current.tag !== HostPortal || current.stateNode.containerInfo !== portal.containerInfo || current.stateNode.implementation !== portal.implementation) {
          // Insert
          var created = createFiberFromPortal(portal, returnFiber.mode, expirationTime);
          created.return = returnFiber;
          return created;
        } else {
          // Update
          var existing = useFiber(current, portal.children || []);
          existing.return = returnFiber;
          return existing;
        }
      }

      function updateFragment(returnFiber, current, fragment, expirationTime, key) {
        if (current === null || current.tag !== Fragment) {
          // Insert
          var created = createFiberFromFragment(fragment, returnFiber.mode, expirationTime, key);
          created.return = returnFiber;
          return created;
        } else {
          // Update
          var existing = useFiber(current, fragment);
          existing.return = returnFiber;
          return existing;
        }
      }

      function createChild(returnFiber, newChild, expirationTime) {
        if (typeof newChild === 'string' || typeof newChild === 'number') {
          // Text nodes don't have keys. If the previous node is implicitly keyed
          // we can continue to replace it without aborting even if it is not a text
          // node.
          var created = createFiberFromText('' + newChild, returnFiber.mode, expirationTime);
          created.return = returnFiber;
          return created;
        }

        if (typeof newChild === 'object' && newChild !== null) {
          switch (newChild.$$typeof) {
            case REACT_ELEMENT_TYPE:
              {
                var _created = createFiberFromElement(newChild, returnFiber.mode, expirationTime);

                _created.ref = coerceRef(returnFiber, null, newChild);
                _created.return = returnFiber;
                return _created;
              }

            case REACT_PORTAL_TYPE:
              {
                var _created2 = createFiberFromPortal(newChild, returnFiber.mode, expirationTime);

                _created2.return = returnFiber;
                return _created2;
              }
          }

          if (isArray$1(newChild) || getIteratorFn(newChild)) {
            var _created3 = createFiberFromFragment(newChild, returnFiber.mode, expirationTime, null);

            _created3.return = returnFiber;
            return _created3;
          }

          throwOnInvalidObjectType(returnFiber, newChild);
        }

        {
          if (typeof newChild === 'function') {
            warnOnFunctionType();
          }
        }
        return null;
      }

      function updateSlot(returnFiber, oldFiber, newChild, expirationTime) {
        // Update the fiber if the keys match, otherwise return null.
        var key = oldFiber !== null ? oldFiber.key : null;

        if (typeof newChild === 'string' || typeof newChild === 'number') {
          // Text nodes don't have keys. If the previous node is implicitly keyed
          // we can continue to replace it without aborting even if it is not a text
          // node.
          if (key !== null) {
            return null;
          }

          return updateTextNode(returnFiber, oldFiber, '' + newChild, expirationTime);
        }

        if (typeof newChild === 'object' && newChild !== null) {
          switch (newChild.$$typeof) {
            case REACT_ELEMENT_TYPE:
              {
                if (newChild.key === key) {
                  if (newChild.type === REACT_FRAGMENT_TYPE) {
                    return updateFragment(returnFiber, oldFiber, newChild.props.children, expirationTime, key);
                  }

                  return updateElement(returnFiber, oldFiber, newChild, expirationTime);
                } else {
                  return null;
                }
              }

            case REACT_PORTAL_TYPE:
              {
                if (newChild.key === key) {
                  return updatePortal(returnFiber, oldFiber, newChild, expirationTime);
                } else {
                  return null;
                }
              }
          }

          if (isArray$1(newChild) || getIteratorFn(newChild)) {
            if (key !== null) {
              return null;
            }

            return updateFragment(returnFiber, oldFiber, newChild, expirationTime, null);
          }

          throwOnInvalidObjectType(returnFiber, newChild);
        }

        {
          if (typeof newChild === 'function') {
            warnOnFunctionType();
          }
        }
        return null;
      }

      function updateFromMap(existingChildren, returnFiber, newIdx, newChild, expirationTime) {
        if (typeof newChild === 'string' || typeof newChild === 'number') {
          // Text nodes don't have keys, so we neither have to check the old nor
          // new node for the key. If both are text nodes, they match.
          var matchedFiber = existingChildren.get(newIdx) || null;
          return updateTextNode(returnFiber, matchedFiber, '' + newChild, expirationTime);
        }

        if (typeof newChild === 'object' && newChild !== null) {
          switch (newChild.$$typeof) {
            case REACT_ELEMENT_TYPE:
              {
                var _matchedFiber = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;

                if (newChild.type === REACT_FRAGMENT_TYPE) {
                  return updateFragment(returnFiber, _matchedFiber, newChild.props.children, expirationTime, newChild.key);
                }

                return updateElement(returnFiber, _matchedFiber, newChild, expirationTime);
              }

            case REACT_PORTAL_TYPE:
              {
                var _matchedFiber2 = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;

                return updatePortal(returnFiber, _matchedFiber2, newChild, expirationTime);
              }
          }

          if (isArray$1(newChild) || getIteratorFn(newChild)) {
            var _matchedFiber3 = existingChildren.get(newIdx) || null;

            return updateFragment(returnFiber, _matchedFiber3, newChild, expirationTime, null);
          }

          throwOnInvalidObjectType(returnFiber, newChild);
        }

        {
          if (typeof newChild === 'function') {
            warnOnFunctionType();
          }
        }
        return null;
      }
      /**
       * Warns if there is a duplicate or missing key
       */


      function warnOnInvalidKey(child, knownKeys) {
        {
          if (typeof child !== 'object' || child === null) {
            return knownKeys;
          }

          switch (child.$$typeof) {
            case REACT_ELEMENT_TYPE:
            case REACT_PORTAL_TYPE:
              warnForMissingKey(child);
              var key = child.key;

              if (typeof key !== 'string') {
                break;
              }

              if (knownKeys === null) {
                knownKeys = new Set();
                knownKeys.add(key);
                break;
              }

              if (!knownKeys.has(key)) {
                knownKeys.add(key);
                break;
              }

              error('Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.', key);
              break;
          }
        }
        return knownKeys;
      }

      function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, expirationTime) {
        // This algorithm can't optimize by searching from both ends since we
        // don't have backpointers on fibers. I'm trying to see how far we can get
        // with that model. If it ends up not being worth the tradeoffs, we can
        // add it later.
        // Even with a two ended optimization, we'd want to optimize for the case
        // where there are few changes and brute force the comparison instead of
        // going for the Map. It'd like to explore hitting that path first in
        // forward-only mode and only go for the Map once we notice that we need
        // lots of look ahead. This doesn't handle reversal as well as two ended
        // search but that's unusual. Besides, for the two ended optimization to
        // work on Iterables, we'd need to copy the whole set.
        // In this first iteration, we'll just live with hitting the bad case
        // (adding everything to a Map) in for every insert/move.
        // If you change this code, also update reconcileChildrenIterator() which
        // uses the same algorithm.
        {
          // First, validate keys.
          var knownKeys = null;

          for (var i = 0; i < newChildren.length; i++) {
            var child = newChildren[i];
            knownKeys = warnOnInvalidKey(child, knownKeys);
          }
        }
        var resultingFirstChild = null;
        var previousNewFiber = null;
        var oldFiber = currentFirstChild;
        var lastPlacedIndex = 0;
        var newIdx = 0;
        var nextOldFiber = null;

        for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) {
          if (oldFiber.index > newIdx) {
            nextOldFiber = oldFiber;
            oldFiber = null;
          } else {
            nextOldFiber = oldFiber.sibling;
          }

          var newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx], expirationTime);

          if (newFiber === null) {
            // TODO: This breaks on empty slots like null children. That's
            // unfortunate because it triggers the slow path all the time. We need
            // a better way to communicate whether this was a miss or null,
            // boolean, undefined, etc.
            if (oldFiber === null) {
              oldFiber = nextOldFiber;
            }

            break;
          }

          if (shouldTrackSideEffects) {
            if (oldFiber && newFiber.alternate === null) {
              // We matched the slot, but we didn't reuse the existing fiber, so we
              // need to delete the existing child.
              deleteChild(returnFiber, oldFiber);
            }
          }

          lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);

          if (previousNewFiber === null) {
            // TODO: Move out of the loop. This only happens for the first run.
            resultingFirstChild = newFiber;
          } else {
            // TODO: Defer siblings if we're not at the right index for this slot.
            // I.e. if we had null values before, then we want to defer this
            // for each null value. However, we also don't want to call updateSlot
            // with the previous one.
            previousNewFiber.sibling = newFiber;
          }

          previousNewFiber = newFiber;
          oldFiber = nextOldFiber;
        }

        if (newIdx === newChildren.length) {
          // We've reached the end of the new children. We can delete the rest.
          deleteRemainingChildren(returnFiber, oldFiber);
          return resultingFirstChild;
        }

        if (oldFiber === null) {
          // If we don't have any more existing children we can choose a fast path
          // since the rest will all be insertions.
          for (; newIdx < newChildren.length; newIdx++) {
            var _newFiber = createChild(returnFiber, newChildren[newIdx], expirationTime);

            if (_newFiber === null) {
              continue;
            }

            lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx);

            if (previousNewFiber === null) {
              // TODO: Move out of the loop. This only happens for the first run.
              resultingFirstChild = _newFiber;
            } else {
              previousNewFiber.sibling = _newFiber;
            }

            previousNewFiber = _newFiber;
          }

          return resultingFirstChild;
        } // Add all children to a key map for quick lookups.


        var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves.

        for (; newIdx < newChildren.length; newIdx++) {
          var _newFiber2 = updateFromMap(existingChildren, returnFiber, newIdx, newChildren[newIdx], expirationTime);

          if (_newFiber2 !== null) {
            if (shouldTrackSideEffects) {
              if (_newFiber2.alternate !== null) {
                // The new fiber is a work in progress, but if there exists a
                // current, that means that we reused the fiber. We need to delete
                // it from the child list so that we don't add it to the deletion
                // list.
                existingChildren.delete(_newFiber2.key === null ? newIdx : _newFiber2.key);
              }
            }

            lastPlacedIndex = placeChild(_newFiber2, lastPlacedIndex, newIdx);

            if (previousNewFiber === null) {
              resultingFirstChild = _newFiber2;
            } else {
              previousNewFiber.sibling = _newFiber2;
            }

            previousNewFiber = _newFiber2;
          }
        }

        if (shouldTrackSideEffects) {
          // Any existing children that weren't consumed above were deleted. We need
          // to add them to the deletion list.
          existingChildren.forEach(function (child) {
            return deleteChild(returnFiber, child);
          });
        }

        return resultingFirstChild;
      }

      function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildrenIterable, expirationTime) {
        // This is the same implementation as reconcileChildrenArray(),
        // but using the iterator instead.
        var iteratorFn = getIteratorFn(newChildrenIterable);

        if (!(typeof iteratorFn === 'function')) {
          {
            throw Error("An object is not an iterable. This error is likely caused by a bug in React. Please file an issue.");
          }
        }

        {
          // We don't support rendering Generators because it's a mutation.
          // See https://github.com/facebook/react/issues/12995
          if (typeof Symbol === 'function' && // $FlowFixMe Flow doesn't know about toStringTag
          newChildrenIterable[Symbol.toStringTag] === 'Generator') {
            if (!didWarnAboutGenerators) {
              error('Using Generators as children is unsupported and will likely yield ' + 'unexpected results because enumerating a generator mutates it. ' + 'You may convert it to an array with `Array.from()` or the ' + '`[...spread]` operator before rendering. Keep in mind ' + 'you might need to polyfill these features for older browsers.');
            }

            didWarnAboutGenerators = true;
          } // Warn about using Maps as children


          if (newChildrenIterable.entries === iteratorFn) {
            if (!didWarnAboutMaps) {
              error('Using Maps as children is unsupported and will likely yield ' + 'unexpected results. Convert it to a sequence/iterable of keyed ' + 'ReactElements instead.');
            }

            didWarnAboutMaps = true;
          } // First, validate keys.
          // We'll get a different iterator later for the main pass.


          var _newChildren = iteratorFn.call(newChildrenIterable);

          if (_newChildren) {
            var knownKeys = null;

            var _step = _newChildren.next();

            for (; !_step.done; _step = _newChildren.next()) {
              var child = _step.value;
              knownKeys = warnOnInvalidKey(child, knownKeys);
            }
          }
        }
        var newChildren = iteratorFn.call(newChildrenIterable);

        if (!(newChildren != null)) {
          {
            throw Error("An iterable object provided no iterator.");
          }
        }

        var resultingFirstChild = null;
        var previousNewFiber = null;
        var oldFiber = currentFirstChild;
        var lastPlacedIndex = 0;
        var newIdx = 0;
        var nextOldFiber = null;
        var step = newChildren.next();

        for (; oldFiber !== null && !step.done; newIdx++, step = newChildren.next()) {
          if (oldFiber.index > newIdx) {
            nextOldFiber = oldFiber;
            oldFiber = null;
          } else {
            nextOldFiber = oldFiber.sibling;
          }

          var newFiber = updateSlot(returnFiber, oldFiber, step.value, expirationTime);

          if (newFiber === null) {
            // TODO: This breaks on empty slots like null children. That's
            // unfortunate because it triggers the slow path all the time. We need
            // a better way to communicate whether this was a miss or null,
            // boolean, undefined, etc.
            if (oldFiber === null) {
              oldFiber = nextOldFiber;
            }

            break;
          }

          if (shouldTrackSideEffects) {
            if (oldFiber && newFiber.alternate === null) {
              // We matched the slot, but we didn't reuse the existing fiber, so we
              // need to delete the existing child.
              deleteChild(returnFiber, oldFiber);
            }
          }

          lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);

          if (previousNewFiber === null) {
            // TODO: Move out of the loop. This only happens for the first run.
            resultingFirstChild = newFiber;
          } else {
            // TODO: Defer siblings if we're not at the right index for this slot.
            // I.e. if we had null values before, then we want to defer this
            // for each null value. However, we also don't want to call updateSlot
            // with the previous one.
            previousNewFiber.sibling = newFiber;
          }

          previousNewFiber = newFiber;
          oldFiber = nextOldFiber;
        }

        if (step.done) {
          // We've reached the end of the new children. We can delete the rest.
          deleteRemainingChildren(returnFiber, oldFiber);
          return resultingFirstChild;
        }

        if (oldFiber === null) {
          // If we don't have any more existing children we can choose a fast path
          // since the rest will all be insertions.
          for (; !step.done; newIdx++, step = newChildren.next()) {
            var _newFiber3 = createChild(returnFiber, step.value, expirationTime);

            if (_newFiber3 === null) {
              continue;
            }

            lastPlacedIndex = placeChild(_newFiber3, lastPlacedIndex, newIdx);

            if (previousNewFiber === null) {
              // TODO: Move out of the loop. This only happens for the first run.
              resultingFirstChild = _newFiber3;
            } else {
              previousNewFiber.sibling = _newFiber3;
            }

            previousNewFiber = _newFiber3;
          }

          return resultingFirstChild;
        } // Add all children to a key map for quick lookups.


        var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves.

        for (; !step.done; newIdx++, step = newChildren.next()) {
          var _newFiber4 = updateFromMap(existingChildren, returnFiber, newIdx, step.value, expirationTime);

          if (_newFiber4 !== null) {
            if (shouldTrackSideEffects) {
              if (_newFiber4.alternate !== null) {
                // The new fiber is a work in progress, but if there exists a
                // current, that means that we reused the fiber. We need to delete
                // it from the child list so that we don't add it to the deletion
                // list.
                existingChildren.delete(_newFiber4.key === null ? newIdx : _newFiber4.key);
              }
            }

            lastPlacedIndex = placeChild(_newFiber4, lastPlacedIndex, newIdx);

            if (previousNewFiber === null) {
              resultingFirstChild = _newFiber4;
            } else {
              previousNewFiber.sibling = _newFiber4;
            }

            previousNewFiber = _newFiber4;
          }
        }

        if (shouldTrackSideEffects) {
          // Any existing children that weren't consumed above were deleted. We need
          // to add them to the deletion list.
          existingChildren.forEach(function (child) {
            return deleteChild(returnFiber, child);
          });
        }

        return resultingFirstChild;
      }

      function reconcileSingleTextNode(returnFiber, currentFirstChild, textContent, expirationTime) {
        // There's no need to check for keys on text nodes since we don't have a
        // way to define them.
        if (currentFirstChild !== null && currentFirstChild.tag === HostText) {
          // We already have an existing node so let's just update it and delete
          // the rest.
          deleteRemainingChildren(returnFiber, currentFirstChild.sibling);
          var existing = useFiber(currentFirstChild, textContent);
          existing.return = returnFiber;
          return existing;
        } // The existing first child is not a text node so we need to create one
        // and delete the existing ones.


        deleteRemainingChildren(returnFiber, currentFirstChild);
        var created = createFiberFromText(textContent, returnFiber.mode, expirationTime);
        created.return = returnFiber;
        return created;
      }

      function reconcileSingleElement(returnFiber, currentFirstChild, element, expirationTime) {
        var key = element.key;
        var child = currentFirstChild;

        while (child !== null) {
          // TODO: If key === null and child.key === null, then this only applies to
          // the first item in the list.
          if (child.key === key) {
            switch (child.tag) {
              case Fragment:
                {
                  if (element.type === REACT_FRAGMENT_TYPE) {
                    deleteRemainingChildren(returnFiber, child.sibling);
                    var existing = useFiber(child, element.props.children);
                    existing.return = returnFiber;
                    {
                      existing._debugSource = element._source;
                      existing._debugOwner = element._owner;
                    }
                    return existing;
                  }

                  break;
                }

              case Block: // We intentionally fallthrough here if enableBlocksAPI is not on.
              // eslint-disable-next-lined no-fallthrough

              default:
                {
                  if (child.elementType === element.type || // Keep this check inline so it only runs on the false path:
                  isCompatibleFamilyForHotReloading(child, element)) {
                    deleteRemainingChildren(returnFiber, child.sibling);

                    var _existing3 = useFiber(child, element.props);

                    _existing3.ref = coerceRef(returnFiber, child, element);
                    _existing3.return = returnFiber;
                    {
                      _existing3._debugSource = element._source;
                      _existing3._debugOwner = element._owner;
                    }
                    return _existing3;
                  }

                  break;
                }
            } // Didn't match.


            deleteRemainingChildren(returnFiber, child);
            break;
          } else {
            deleteChild(returnFiber, child);
          }

          child = child.sibling;
        }

        if (element.type === REACT_FRAGMENT_TYPE) {
          var created = createFiberFromFragment(element.props.children, returnFiber.mode, expirationTime, element.key);
          created.return = returnFiber;
          return created;
        } else {
          var _created4 = createFiberFromElement(element, returnFiber.mode, expirationTime);

          _created4.ref = coerceRef(returnFiber, currentFirstChild, element);
          _created4.return = returnFiber;
          return _created4;
        }
      }

      function reconcileSinglePortal(returnFiber, currentFirstChild, portal, expirationTime) {
        var key = portal.key;
        var child = currentFirstChild;

        while (child !== null) {
          // TODO: If key === null and child.key === null, then this only applies to
          // the first item in the list.
          if (child.key === key) {
            if (child.tag === HostPortal && child.stateNode.containerInfo === portal.containerInfo && child.stateNode.implementation === portal.implementation) {
              deleteRemainingChildren(returnFiber, child.sibling);
              var existing = useFiber(child, portal.children || []);
              existing.return = returnFiber;
              return existing;
            } else {
              deleteRemainingChildren(returnFiber, child);
              break;
            }
          } else {
            deleteChild(returnFiber, child);
          }

          child = child.sibling;
        }

        var created = createFiberFromPortal(portal, returnFiber.mode, expirationTime);
        created.return = returnFiber;
        return created;
      } // This API will tag the children with the side-effect of the reconciliation
      // itself. They will be added to the side-effect list as we pass through the
      // children and the parent.


      function reconcileChildFibers(returnFiber, currentFirstChild, newChild, expirationTime) {
        // This function is not recursive.
        // If the top level item is an array, we treat it as a set of children,
        // not as a fragment. Nested arrays on the other hand will be treated as
        // fragment nodes. Recursion happens at the normal flow.
        // Handle top level unkeyed fragments as if they were arrays.
        // This leads to an ambiguity between <>{[...]}</> and <>...</>.
        // We treat the ambiguous cases above the same.
        var isUnkeyedTopLevelFragment = typeof newChild === 'object' && newChild !== null && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null;

        if (isUnkeyedTopLevelFragment) {
          newChild = newChild.props.children;
        } // Handle object types


        var isObject = typeof newChild === 'object' && newChild !== null;

        if (isObject) {
          switch (newChild.$$typeof) {
            case REACT_ELEMENT_TYPE:
              return placeSingleChild(reconcileSingleElement(returnFiber, currentFirstChild, newChild, expirationTime));

            case REACT_PORTAL_TYPE:
              return placeSingleChild(reconcileSinglePortal(returnFiber, currentFirstChild, newChild, expirationTime));
          }
        }

        if (typeof newChild === 'string' || typeof newChild === 'number') {
          return placeSingleChild(reconcileSingleTextNode(returnFiber, currentFirstChild, '' + newChild, expirationTime));
        }

        if (isArray$1(newChild)) {
          return reconcileChildrenArray(returnFiber, currentFirstChild, newChild, expirationTime);
        }

        if (getIteratorFn(newChild)) {
          return reconcileChildrenIterator(returnFiber, currentFirstChild, newChild, expirationTime);
        }

        if (isObject) {
          throwOnInvalidObjectType(returnFiber, newChild);
        }

        {
          if (typeof newChild === 'function') {
            warnOnFunctionType();
          }
        }

        if (typeof newChild === 'undefined' && !isUnkeyedTopLevelFragment) {
          // If the new child is undefined, and the return fiber is a composite
          // component, throw an error. If Fiber return types are disabled,
          // we already threw above.
          switch (returnFiber.tag) {
            case ClassComponent:
              {
                {
                  var instance = returnFiber.stateNode;

                  if (instance.render._isMockFunction) {
                    // We allow auto-mocks to proceed as if they're returning null.
                    break;
                  }
                }
              }
            // Intentionally fall through to the next case, which handles both
            // functions and classes
            // eslint-disable-next-lined no-fallthrough

            case FunctionComponent:
              {
                var Component = returnFiber.type;
                {
                  {
                    throw Error((Component.displayName || Component.name || 'Component') + "(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.");
                  }
                }
              }
          }
        } // Remaining cases are all treated as empty.


        return deleteRemainingChildren(returnFiber, currentFirstChild);
      }

      return reconcileChildFibers;
    }

    var reconcileChildFibers = ChildReconciler(true);
    var mountChildFibers = ChildReconciler(false);

    function cloneChildFibers(current, workInProgress) {
      if (!(current === null || workInProgress.child === current.child)) {
        {
          throw Error("Resuming work not yet implemented.");
        }
      }

      if (workInProgress.child === null) {
        return;
      }

      var currentChild = workInProgress.child;
      var newChild = createWorkInProgress(currentChild, currentChild.pendingProps);
      workInProgress.child = newChild;
      newChild.return = workInProgress;

      while (currentChild.sibling !== null) {
        currentChild = currentChild.sibling;
        newChild = newChild.sibling = createWorkInProgress(currentChild, currentChild.pendingProps);
        newChild.return = workInProgress;
      }

      newChild.sibling = null;
    } // Reset a workInProgress child set to prepare it for a second pass.


    function resetChildFibers(workInProgress, renderExpirationTime) {
      var child = workInProgress.child;

      while (child !== null) {
        resetWorkInProgress(child, renderExpirationTime);
        child = child.sibling;
      }
    }

    var NO_CONTEXT = {};
    var contextStackCursor$1 = createCursor(NO_CONTEXT);
    var contextFiberStackCursor = createCursor(NO_CONTEXT);
    var rootInstanceStackCursor = createCursor(NO_CONTEXT);

    function requiredContext(c) {
      if (!(c !== NO_CONTEXT)) {
        {
          throw Error("Expected host context to exist. This error is likely caused by a bug in React. Please file an issue.");
        }
      }

      return c;
    }

    function getRootHostContainer() {
      var rootInstance = requiredContext(rootInstanceStackCursor.current);
      return rootInstance;
    }

    function pushHostContainer(fiber, nextRootInstance) {
      // Push current root instance onto the stack;
      // This allows us to reset root when portals are popped.
      push(rootInstanceStackCursor, nextRootInstance, fiber); // Track the context and the Fiber that provided it.
      // This enables us to pop only Fibers that provide unique contexts.

      push(contextFiberStackCursor, fiber, fiber); // Finally, we need to push the host context to the stack.
      // However, we can't just call getRootHostContext() and push it because
      // we'd have a different number of entries on the stack depending on
      // whether getRootHostContext() throws somewhere in renderer code or not.
      // So we push an empty value first. This lets us safely unwind on errors.

      push(contextStackCursor$1, NO_CONTEXT, fiber);
      var nextRootContext = getRootHostContext(nextRootInstance); // Now that we know this function doesn't throw, replace it.

      pop(contextStackCursor$1, fiber);
      push(contextStackCursor$1, nextRootContext, fiber);
    }

    function popHostContainer(fiber) {
      pop(contextStackCursor$1, fiber);
      pop(contextFiberStackCursor, fiber);
      pop(rootInstanceStackCursor, fiber);
    }

    function getHostContext() {
      var context = requiredContext(contextStackCursor$1.current);
      return context;
    }

    function pushHostContext(fiber) {
      var rootInstance = requiredContext(rootInstanceStackCursor.current);
      var context = requiredContext(contextStackCursor$1.current);
      var nextContext = getChildHostContext(context, fiber.type); // Don't push this Fiber's context unless it's unique.

      if (context === nextContext) {
        return;
      } // Track the context and the Fiber that provided it.
      // This enables us to pop only Fibers that provide unique contexts.


      push(contextFiberStackCursor, fiber, fiber);
      push(contextStackCursor$1, nextContext, fiber);
    }

    function popHostContext(fiber) {
      // Do not pop unless this Fiber provided the current context.
      // pushHostContext() only pushes Fibers that provide unique contexts.
      if (contextFiberStackCursor.current !== fiber) {
        return;
      }

      pop(contextStackCursor$1, fiber);
      pop(contextFiberStackCursor, fiber);
    }

    var DefaultSuspenseContext = 0; // The Suspense Context is split into two parts. The lower bits is
    // inherited deeply down the subtree. The upper bits only affect
    // this immediate suspense boundary and gets reset each new
    // boundary or suspense list.

    var SubtreeSuspenseContextMask = 1; // Subtree Flags:
    // InvisibleParentSuspenseContext indicates that one of our parent Suspense
    // boundaries is not currently showing visible main content.
    // Either because it is already showing a fallback or is not mounted at all.
    // We can use this to determine if it is desirable to trigger a fallback at
    // the parent. If not, then we might need to trigger undesirable boundaries
    // and/or suspend the commit to avoid hiding the parent content.

    var InvisibleParentSuspenseContext = 1; // Shallow Flags:
    // ForceSuspenseFallback can be used by SuspenseList to force newly added
    // items into their fallback state during one of the render passes.

    var ForceSuspenseFallback = 2;
    var suspenseStackCursor = createCursor(DefaultSuspenseContext);

    function hasSuspenseContext(parentContext, flag) {
      return (parentContext & flag) !== 0;
    }

    function setDefaultShallowSuspenseContext(parentContext) {
      return parentContext & SubtreeSuspenseContextMask;
    }

    function setShallowSuspenseContext(parentContext, shallowContext) {
      return parentContext & SubtreeSuspenseContextMask | shallowContext;
    }

    function addSubtreeSuspenseContext(parentContext, subtreeContext) {
      return parentContext | subtreeContext;
    }

    function pushSuspenseContext(fiber, newContext) {
      push(suspenseStackCursor, newContext, fiber);
    }

    function popSuspenseContext(fiber) {
      pop(suspenseStackCursor, fiber);
    }

    function shouldCaptureSuspense(workInProgress, hasInvisibleParent) {
      // If it was the primary children that just suspended, capture and render the
      // fallback. Otherwise, don't capture and bubble to the next boundary.
      var nextState = workInProgress.memoizedState;

      if (nextState !== null) {
        if (nextState.dehydrated !== null) {
          // A dehydrated boundary always captures.
          return true;
        }

        return false;
      }

      var props = workInProgress.memoizedProps; // In order to capture, the Suspense component must have a fallback prop.

      if (props.fallback === undefined) {
        return false;
      } // Regular boundaries always capture.


      if (props.unstable_avoidThisFallback !== true) {
        return true;
      } // If it's a boundary we should avoid, then we prefer to bubble up to the
      // parent boundary if it is currently invisible.


      if (hasInvisibleParent) {
        return false;
      } // If the parent is not able to handle it, we must handle it.


      return true;
    }

    function findFirstSuspended(row) {
      var node = row;

      while (node !== null) {
        if (node.tag === SuspenseComponent) {
          var state = node.memoizedState;

          if (state !== null) {
            var dehydrated = state.dehydrated;

            if (dehydrated === null || isSuspenseInstancePending(dehydrated) || isSuspenseInstanceFallback(dehydrated)) {
              return node;
            }
          }
        } else if (node.tag === SuspenseListComponent && // revealOrder undefined can't be trusted because it don't
        // keep track of whether it suspended or not.
        node.memoizedProps.revealOrder !== undefined) {
          var didSuspend = (node.effectTag & DidCapture) !== NoEffect;

          if (didSuspend) {
            return node;
          }
        } else if (node.child !== null) {
          node.child.return = node;
          node = node.child;
          continue;
        }

        if (node === row) {
          return null;
        }

        while (node.sibling === null) {
          if (node.return === null || node.return === row) {
            return null;
          }

          node = node.return;
        }

        node.sibling.return = node.return;
        node = node.sibling;
      }

      return null;
    }

    function createDeprecatedResponderListener(responder, props) {
      var eventResponderListener = {
        responder: responder,
        props: props
      };
      {
        Object.freeze(eventResponderListener);
      }
      return eventResponderListener;
    }

    var HasEffect =
    /* */
    1; // Represents the phase in which the effect (not the clean-up) fires.

    var Layout =
    /*    */
    2;
    var Passive$1 =
    /*   */
    4;
    var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher,
        ReactCurrentBatchConfig$1 = ReactSharedInternals.ReactCurrentBatchConfig;
    var didWarnAboutMismatchedHooksForComponent;
    {
      didWarnAboutMismatchedHooksForComponent = new Set();
    } // These are set right before calling the component.

    var renderExpirationTime = NoWork; // The work-in-progress fiber. I've named it differently to distinguish it from
    // the work-in-progress hook.

    var currentlyRenderingFiber$1 = null; // Hooks are stored as a linked list on the fiber's memoizedState field. The
    // current hook list is the list that belongs to the current fiber. The
    // work-in-progress hook list is a new list that will be added to the
    // work-in-progress fiber.

    var currentHook = null;
    var workInProgressHook = null; // Whether an update was scheduled at any point during the render phase. This
    // does not get reset if we do another render pass; only when we're completely
    // finished evaluating this component. This is an optimization so we know
    // whether we need to clear render phase updates after a throw.

    var didScheduleRenderPhaseUpdate = false;
    var RE_RENDER_LIMIT = 25; // In DEV, this is the name of the currently executing primitive hook

    var currentHookNameInDev = null; // In DEV, this list ensures that hooks are called in the same order between renders.
    // The list stores the order of hooks used during the initial render (mount).
    // Subsequent renders (updates) reference this list.

    var hookTypesDev = null;
    var hookTypesUpdateIndexDev = -1; // In DEV, this tracks whether currently rendering component needs to ignore
    // the dependencies for Hooks that need them (e.g. useEffect or useMemo).
    // When true, such Hooks will always be "remounted". Only used during hot reload.

    var ignorePreviousDependencies = false;

    function mountHookTypesDev() {
      {
        var hookName = currentHookNameInDev;

        if (hookTypesDev === null) {
          hookTypesDev = [hookName];
        } else {
          hookTypesDev.push(hookName);
        }
      }
    }

    function updateHookTypesDev() {
      {
        var hookName = currentHookNameInDev;

        if (hookTypesDev !== null) {
          hookTypesUpdateIndexDev++;

          if (hookTypesDev[hookTypesUpdateIndexDev] !== hookName) {
            warnOnHookMismatchInDev(hookName);
          }
        }
      }
    }

    function checkDepsAreArrayDev(deps) {
      {
        if (deps !== undefined && deps !== null && !Array.isArray(deps)) {
          // Verify deps, but only on mount to avoid extra checks.
          // It's unlikely their type would change as usually you define them inline.
          error('%s received a final argument that is not an array (instead, received `%s`). When ' + 'specified, the final argument must be an array.', currentHookNameInDev, typeof deps);
        }
      }
    }

    function warnOnHookMismatchInDev(currentHookName) {
      {
        var componentName = getComponentName(currentlyRenderingFiber$1.type);

        if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) {
          didWarnAboutMismatchedHooksForComponent.add(componentName);

          if (hookTypesDev !== null) {
            var table = '';
            var secondColumnStart = 30;

            for (var i = 0; i <= hookTypesUpdateIndexDev; i++) {
              var oldHookName = hookTypesDev[i];
              var newHookName = i === hookTypesUpdateIndexDev ? currentHookName : oldHookName;
              var row = i + 1 + ". " + oldHookName; // Extra space so second column lines up
              // lol @ IE not supporting String#repeat

              while (row.length < secondColumnStart) {
                row += ' ';
              }

              row += newHookName + '\n';
              table += row;
            }

            error('React has detected a change in the order of Hooks called by %s. ' + 'This will lead to bugs and errors if not fixed. ' + 'For more information, read the Rules of Hooks: https://fb.me/rules-of-hooks\n\n' + '   Previous render            Next render\n' + '   ------------------------------------------------------\n' + '%s' + '   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n', componentName, table);
          }
        }
      }
    }

    function throwInvalidHookError() {
      {
        {
          throw Error("Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.");
        }
      }
    }

    function areHookInputsEqual(nextDeps, prevDeps) {
      {
        if (ignorePreviousDependencies) {
          // Only true when this component is being hot reloaded.
          return false;
        }
      }

      if (prevDeps === null) {
        {
          error('%s received a final argument during this render, but not during ' + 'the previous render. Even though the final argument is optional, ' + 'its type cannot change between renders.', currentHookNameInDev);
        }
        return false;
      }

      {
        // Don't bother comparing lengths in prod because these arrays should be
        // passed inline.
        if (nextDeps.length !== prevDeps.length) {
          error('The final argument passed to %s changed size between renders. The ' + 'order and size of this array must remain constant.\n\n' + 'Previous: %s\n' + 'Incoming: %s', currentHookNameInDev, "[" + prevDeps.join(', ') + "]", "[" + nextDeps.join(', ') + "]");
        }
      }

      for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) {
        if (objectIs(nextDeps[i], prevDeps[i])) {
          continue;
        }

        return false;
      }

      return true;
    }

    function renderWithHooks(current, workInProgress, Component, props, secondArg, nextRenderExpirationTime) {
      renderExpirationTime = nextRenderExpirationTime;
      currentlyRenderingFiber$1 = workInProgress;
      {
        hookTypesDev = current !== null ? current._debugHookTypes : null;
        hookTypesUpdateIndexDev = -1; // Used for hot reloading:

        ignorePreviousDependencies = current !== null && current.type !== workInProgress.type;
      }
      workInProgress.memoizedState = null;
      workInProgress.updateQueue = null;
      workInProgress.expirationTime = NoWork; // The following should have already been reset
      // currentHook = null;
      // workInProgressHook = null;
      // didScheduleRenderPhaseUpdate = false;
      // TODO Warn if no hooks are used at all during mount, then some are used during update.
      // Currently we will identify the update render as a mount because memoizedState === null.
      // This is tricky because it's valid for certain types of components (e.g. React.lazy)
      // Using memoizedState to differentiate between mount/update only works if at least one stateful hook is used.
      // Non-stateful hooks (e.g. context) don't get added to memoizedState,
      // so memoizedState would be null during updates and mounts.

      {
        if (current !== null && current.memoizedState !== null) {
          ReactCurrentDispatcher.current = HooksDispatcherOnUpdateInDEV;
        } else if (hookTypesDev !== null) {
          // This dispatcher handles an edge case where a component is updating,
          // but no stateful hooks have been used.
          // We want to match the production code behavior (which will use HooksDispatcherOnMount),
          // but with the extra DEV validation to ensure hooks ordering hasn't changed.
          // This dispatcher does that.
          ReactCurrentDispatcher.current = HooksDispatcherOnMountWithHookTypesInDEV;
        } else {
          ReactCurrentDispatcher.current = HooksDispatcherOnMountInDEV;
        }
      }
      var children = Component(props, secondArg); // Check if there was a render phase update

      if (workInProgress.expirationTime === renderExpirationTime) {
        // Keep rendering in a loop for as long as render phase updates continue to
        // be scheduled. Use a counter to prevent infinite loops.
        var numberOfReRenders = 0;

        do {
          workInProgress.expirationTime = NoWork;

          if (!(numberOfReRenders < RE_RENDER_LIMIT)) {
            {
              throw Error("Too many re-renders. React limits the number of renders to prevent an infinite loop.");
            }
          }

          numberOfReRenders += 1;
          {
            // Even when hot reloading, allow dependencies to stabilize
            // after first render to prevent infinite render phase updates.
            ignorePreviousDependencies = false;
          } // Start over from the beginning of the list

          currentHook = null;
          workInProgressHook = null;
          workInProgress.updateQueue = null;
          {
            // Also validate hook order for cascading updates.
            hookTypesUpdateIndexDev = -1;
          }
          ReactCurrentDispatcher.current = HooksDispatcherOnRerenderInDEV;
          children = Component(props, secondArg);
        } while (workInProgress.expirationTime === renderExpirationTime);
      } // We can assume the previous dispatcher is always this one, since we set it
      // at the beginning of the render phase and there's no re-entrancy.


      ReactCurrentDispatcher.current = ContextOnlyDispatcher;
      {
        workInProgress._debugHookTypes = hookTypesDev;
      } // This check uses currentHook so that it works the same in DEV and prod bundles.
      // hookTypesDev could catch more cases (e.g. context) but only in DEV bundles.

      var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null;
      renderExpirationTime = NoWork;
      currentlyRenderingFiber$1 = null;
      currentHook = null;
      workInProgressHook = null;
      {
        currentHookNameInDev = null;
        hookTypesDev = null;
        hookTypesUpdateIndexDev = -1;
      }
      didScheduleRenderPhaseUpdate = false;

      if (!!didRenderTooFewHooks) {
        {
          throw Error("Rendered fewer hooks than expected. This may be caused by an accidental early return statement.");
        }
      }

      return children;
    }

    function bailoutHooks(current, workInProgress, expirationTime) {
      workInProgress.updateQueue = current.updateQueue;
      workInProgress.effectTag &= ~(Passive | Update);

      if (current.expirationTime <= expirationTime) {
        current.expirationTime = NoWork;
      }
    }

    function resetHooksAfterThrow() {
      // We can assume the previous dispatcher is always this one, since we set it
      // at the beginning of the render phase and there's no re-entrancy.
      ReactCurrentDispatcher.current = ContextOnlyDispatcher;

      if (didScheduleRenderPhaseUpdate) {
        // There were render phase updates. These are only valid for this render
        // phase, which we are now aborting. Remove the updates from the queues so
        // they do not persist to the next render. Do not remove updates from hooks
        // that weren't processed.
        //
        // Only reset the updates from the queue if it has a clone. If it does
        // not have a clone, that means it wasn't processed, and the updates were
        // scheduled before we entered the render phase.
        var hook = currentlyRenderingFiber$1.memoizedState;

        while (hook !== null) {
          var queue = hook.queue;

          if (queue !== null) {
            queue.pending = null;
          }

          hook = hook.next;
        }
      }

      renderExpirationTime = NoWork;
      currentlyRenderingFiber$1 = null;
      currentHook = null;
      workInProgressHook = null;
      {
        hookTypesDev = null;
        hookTypesUpdateIndexDev = -1;
        currentHookNameInDev = null;
      }
      didScheduleRenderPhaseUpdate = false;
    }

    function mountWorkInProgressHook() {
      var hook = {
        memoizedState: null,
        baseState: null,
        baseQueue: null,
        queue: null,
        next: null
      };

      if (workInProgressHook === null) {
        // This is the first hook in the list
        currentlyRenderingFiber$1.memoizedState = workInProgressHook = hook;
      } else {
        // Append to the end of the list
        workInProgressHook = workInProgressHook.next = hook;
      }

      return workInProgressHook;
    }

    function updateWorkInProgressHook() {
      // This function is used both for updates and for re-renders triggered by a
      // render phase update. It assumes there is either a current hook we can
      // clone, or a work-in-progress hook from a previous render pass that we can
      // use as a base. When we reach the end of the base list, we must switch to
      // the dispatcher used for mounts.
      var nextCurrentHook;

      if (currentHook === null) {
        var current = currentlyRenderingFiber$1.alternate;

        if (current !== null) {
          nextCurrentHook = current.memoizedState;
        } else {
          nextCurrentHook = null;
        }
      } else {
        nextCurrentHook = currentHook.next;
      }

      var nextWorkInProgressHook;

      if (workInProgressHook === null) {
        nextWorkInProgressHook = currentlyRenderingFiber$1.memoizedState;
      } else {
        nextWorkInProgressHook = workInProgressHook.next;
      }

      if (nextWorkInProgressHook !== null) {
        // There's already a work-in-progress. Reuse it.
        workInProgressHook = nextWorkInProgressHook;
        nextWorkInProgressHook = workInProgressHook.next;
        currentHook = nextCurrentHook;
      } else {
        // Clone from the current hook.
        if (!(nextCurrentHook !== null)) {
          {
            throw Error("Rendered more hooks than during the previous render.");
          }
        }

        currentHook = nextCurrentHook;
        var newHook = {
          memoizedState: currentHook.memoizedState,
          baseState: currentHook.baseState,
          baseQueue: currentHook.baseQueue,
          queue: currentHook.queue,
          next: null
        };

        if (workInProgressHook === null) {
          // This is the first hook in the list.
          currentlyRenderingFiber$1.memoizedState = workInProgressHook = newHook;
        } else {
          // Append to the end of the list.
          workInProgressHook = workInProgressHook.next = newHook;
        }
      }

      return workInProgressHook;
    }

    function createFunctionComponentUpdateQueue() {
      return {
        lastEffect: null
      };
    }

    function basicStateReducer(state, action) {
      // $FlowFixMe: Flow doesn't like mixed types
      return typeof action === 'function' ? action(state) : action;
    }

    function mountReducer(reducer, initialArg, init) {
      var hook = mountWorkInProgressHook();
      var initialState;

      if (init !== undefined) {
        initialState = init(initialArg);
      } else {
        initialState = initialArg;
      }

      hook.memoizedState = hook.baseState = initialState;
      var queue = hook.queue = {
        pending: null,
        dispatch: null,
        lastRenderedReducer: reducer,
        lastRenderedState: initialState
      };
      var dispatch = queue.dispatch = dispatchAction.bind(null, currentlyRenderingFiber$1, queue);
      return [hook.memoizedState, dispatch];
    }

    function updateReducer(reducer, initialArg, init) {
      var hook = updateWorkInProgressHook();
      var queue = hook.queue;

      if (!(queue !== null)) {
        {
          throw Error("Should have a queue. This is likely a bug in React. Please file an issue.");
        }
      }

      queue.lastRenderedReducer = reducer;
      var current = currentHook; // The last rebase update that is NOT part of the base state.

      var baseQueue = current.baseQueue; // The last pending update that hasn't been processed yet.

      var pendingQueue = queue.pending;

      if (pendingQueue !== null) {
        // We have new updates that haven't been processed yet.
        // We'll add them to the base queue.
        if (baseQueue !== null) {
          // Merge the pending queue and the base queue.
          var baseFirst = baseQueue.next;
          var pendingFirst = pendingQueue.next;
          baseQueue.next = pendingFirst;
          pendingQueue.next = baseFirst;
        }

        current.baseQueue = baseQueue = pendingQueue;
        queue.pending = null;
      }

      if (baseQueue !== null) {
        // We have a queue to process.
        var first = baseQueue.next;
        var newState = current.baseState;
        var newBaseState = null;
        var newBaseQueueFirst = null;
        var newBaseQueueLast = null;
        var update = first;

        do {
          var updateExpirationTime = update.expirationTime;

          if (updateExpirationTime < renderExpirationTime) {
            // Priority is insufficient. Skip this update. If this is the first
            // skipped update, the previous update/state is the new base
            // update/state.
            var clone = {
              expirationTime: update.expirationTime,
              suspenseConfig: update.suspenseConfig,
              action: update.action,
              eagerReducer: update.eagerReducer,
              eagerState: update.eagerState,
              next: null
            };

            if (newBaseQueueLast === null) {
              newBaseQueueFirst = newBaseQueueLast = clone;
              newBaseState = newState;
            } else {
              newBaseQueueLast = newBaseQueueLast.next = clone;
            } // Update the remaining priority in the queue.


            if (updateExpirationTime > currentlyRenderingFiber$1.expirationTime) {
              currentlyRenderingFiber$1.expirationTime = updateExpirationTime;
              markUnprocessedUpdateTime(updateExpirationTime);
            }
          } else {
            // This update does have sufficient priority.
            if (newBaseQueueLast !== null) {
              var _clone = {
                expirationTime: Sync,
                // This update is going to be committed so we never want uncommit it.
                suspenseConfig: update.suspenseConfig,
                action: update.action,
                eagerReducer: update.eagerReducer,
                eagerState: update.eagerState,
                next: null
              };
              newBaseQueueLast = newBaseQueueLast.next = _clone;
            } // Mark the event time of this update as relevant to this render pass.
            // TODO: This should ideally use the true event time of this update rather than
            // its priority which is a derived and not reverseable value.
            // TODO: We should skip this update if it was already committed but currently
            // we have no way of detecting the difference between a committed and suspended
            // update here.


            markRenderEventTimeAndConfig(updateExpirationTime, update.suspenseConfig); // Process this update.

            if (update.eagerReducer === reducer) {
              // If this update was processed eagerly, and its reducer matches the
              // current reducer, we can use the eagerly computed state.
              newState = update.eagerState;
            } else {
              var action = update.action;
              newState = reducer(newState, action);
            }
          }

          update = update.next;
        } while (update !== null && update !== first);

        if (newBaseQueueLast === null) {
          newBaseState = newState;
        } else {
          newBaseQueueLast.next = newBaseQueueFirst;
        } // Mark that the fiber performed work, but only if the new state is
        // different from the current state.


        if (!objectIs(newState, hook.memoizedState)) {
          markWorkInProgressReceivedUpdate();
        }

        hook.memoizedState = newState;
        hook.baseState = newBaseState;
        hook.baseQueue = newBaseQueueLast;
        queue.lastRenderedState = newState;
      }

      var dispatch = queue.dispatch;
      return [hook.memoizedState, dispatch];
    }

    function rerenderReducer(reducer, initialArg, init) {
      var hook = updateWorkInProgressHook();
      var queue = hook.queue;

      if (!(queue !== null)) {
        {
          throw Error("Should have a queue. This is likely a bug in React. Please file an issue.");
        }
      }

      queue.lastRenderedReducer = reducer; // This is a re-render. Apply the new render phase updates to the previous
      // work-in-progress hook.

      var dispatch = queue.dispatch;
      var lastRenderPhaseUpdate = queue.pending;
      var newState = hook.memoizedState;

      if (lastRenderPhaseUpdate !== null) {
        // The queue doesn't persist past this render pass.
        queue.pending = null;
        var firstRenderPhaseUpdate = lastRenderPhaseUpdate.next;
        var update = firstRenderPhaseUpdate;

        do {
          // Process this render phase update. We don't have to check the
          // priority because it will always be the same as the current
          // render's.
          var action = update.action;
          newState = reducer(newState, action);
          update = update.next;
        } while (update !== firstRenderPhaseUpdate); // Mark that the fiber performed work, but only if the new state is
        // different from the current state.


        if (!objectIs(newState, hook.memoizedState)) {
          markWorkInProgressReceivedUpdate();
        }

        hook.memoizedState = newState; // Don't persist the state accumulated from the render phase updates to
        // the base state unless the queue is empty.
        // TODO: Not sure if this is the desired semantics, but it's what we
        // do for gDSFP. I can't remember why.

        if (hook.baseQueue === null) {
          hook.baseState = newState;
        }

        queue.lastRenderedState = newState;
      }

      return [newState, dispatch];
    }

    function mountState(initialState) {
      var hook = mountWorkInProgressHook();

      if (typeof initialState === 'function') {
        // $FlowFixMe: Flow doesn't like mixed types
        initialState = initialState();
      }

      hook.memoizedState = hook.baseState = initialState;
      var queue = hook.queue = {
        pending: null,
        dispatch: null,
        lastRenderedReducer: basicStateReducer,
        lastRenderedState: initialState
      };
      var dispatch = queue.dispatch = dispatchAction.bind(null, currentlyRenderingFiber$1, queue);
      return [hook.memoizedState, dispatch];
    }

    function updateState(initialState) {
      return updateReducer(basicStateReducer);
    }

    function rerenderState(initialState) {
      return rerenderReducer(basicStateReducer);
    }

    function pushEffect(tag, create, destroy, deps) {
      var effect = {
        tag: tag,
        create: create,
        destroy: destroy,
        deps: deps,
        // Circular
        next: null
      };
      var componentUpdateQueue = currentlyRenderingFiber$1.updateQueue;

      if (componentUpdateQueue === null) {
        componentUpdateQueue = createFunctionComponentUpdateQueue();
        currentlyRenderingFiber$1.updateQueue = componentUpdateQueue;
        componentUpdateQueue.lastEffect = effect.next = effect;
      } else {
        var lastEffect = componentUpdateQueue.lastEffect;

        if (lastEffect === null) {
          componentUpdateQueue.lastEffect = effect.next = effect;
        } else {
          var firstEffect = lastEffect.next;
          lastEffect.next = effect;
          effect.next = firstEffect;
          componentUpdateQueue.lastEffect = effect;
        }
      }

      return effect;
    }

    function mountRef(initialValue) {
      var hook = mountWorkInProgressHook();
      var ref = {
        current: initialValue
      };
      {
        Object.seal(ref);
      }
      hook.memoizedState = ref;
      return ref;
    }

    function updateRef(initialValue) {
      var hook = updateWorkInProgressHook();
      return hook.memoizedState;
    }

    function mountEffectImpl(fiberEffectTag, hookEffectTag, create, deps) {
      var hook = mountWorkInProgressHook();
      var nextDeps = deps === undefined ? null : deps;
      currentlyRenderingFiber$1.effectTag |= fiberEffectTag;
      hook.memoizedState = pushEffect(HasEffect | hookEffectTag, create, undefined, nextDeps);
    }

    function updateEffectImpl(fiberEffectTag, hookEffectTag, create, deps) {
      var hook = updateWorkInProgressHook();
      var nextDeps = deps === undefined ? null : deps;
      var destroy = undefined;

      if (currentHook !== null) {
        var prevEffect = currentHook.memoizedState;
        destroy = prevEffect.destroy;

        if (nextDeps !== null) {
          var prevDeps = prevEffect.deps;

          if (areHookInputsEqual(nextDeps, prevDeps)) {
            pushEffect(hookEffectTag, create, destroy, nextDeps);
            return;
          }
        }
      }

      currentlyRenderingFiber$1.effectTag |= fiberEffectTag;
      hook.memoizedState = pushEffect(HasEffect | hookEffectTag, create, destroy, nextDeps);
    }

    function mountEffect(create, deps) {
      {
        // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests
        if ('undefined' !== typeof jest) {
          warnIfNotCurrentlyActingEffectsInDEV(currentlyRenderingFiber$1);
        }
      }
      return mountEffectImpl(Update | Passive, Passive$1, create, deps);
    }

    function updateEffect(create, deps) {
      {
        // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests
        if ('undefined' !== typeof jest) {
          warnIfNotCurrentlyActingEffectsInDEV(currentlyRenderingFiber$1);
        }
      }
      return updateEffectImpl(Update | Passive, Passive$1, create, deps);
    }

    function mountLayoutEffect(create, deps) {
      return mountEffectImpl(Update, Layout, create, deps);
    }

    function updateLayoutEffect(create, deps) {
      return updateEffectImpl(Update, Layout, create, deps);
    }

    function imperativeHandleEffect(create, ref) {
      if (typeof ref === 'function') {
        var refCallback = ref;

        var _inst = create();

        refCallback(_inst);
        return function () {
          refCallback(null);
        };
      } else if (ref !== null && ref !== undefined) {
        var refObject = ref;
        {
          if (!refObject.hasOwnProperty('current')) {
            error('Expected useImperativeHandle() first argument to either be a ' + 'ref callback or React.createRef() object. Instead received: %s.', 'an object with keys {' + Object.keys(refObject).join(', ') + '}');
          }
        }

        var _inst2 = create();

        refObject.current = _inst2;
        return function () {
          refObject.current = null;
        };
      }
    }

    function mountImperativeHandle(ref, create, deps) {
      {
        if (typeof create !== 'function') {
          error('Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.', create !== null ? typeof create : 'null');
        }
      } // TODO: If deps are provided, should we skip comparing the ref itself?

      var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null;
      return mountEffectImpl(Update, Layout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
    }

    function updateImperativeHandle(ref, create, deps) {
      {
        if (typeof create !== 'function') {
          error('Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.', create !== null ? typeof create : 'null');
        }
      } // TODO: If deps are provided, should we skip comparing the ref itself?

      var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null;
      return updateEffectImpl(Update, Layout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
    }

    function mountDebugValue(value, formatterFn) {// This hook is normally a no-op.
      // The react-debug-hooks package injects its own implementation
      // so that e.g. DevTools can display custom hook values.
    }

    var updateDebugValue = mountDebugValue;

    function mountCallback(callback, deps) {
      var hook = mountWorkInProgressHook();
      var nextDeps = deps === undefined ? null : deps;
      hook.memoizedState = [callback, nextDeps];
      return callback;
    }

    function updateCallback(callback, deps) {
      var hook = updateWorkInProgressHook();
      var nextDeps = deps === undefined ? null : deps;
      var prevState = hook.memoizedState;

      if (prevState !== null) {
        if (nextDeps !== null) {
          var prevDeps = prevState[1];

          if (areHookInputsEqual(nextDeps, prevDeps)) {
            return prevState[0];
          }
        }
      }

      hook.memoizedState = [callback, nextDeps];
      return callback;
    }

    function mountMemo(nextCreate, deps) {
      var hook = mountWorkInProgressHook();
      var nextDeps = deps === undefined ? null : deps;
      var nextValue = nextCreate();
      hook.memoizedState = [nextValue, nextDeps];
      return nextValue;
    }

    function updateMemo(nextCreate, deps) {
      var hook = updateWorkInProgressHook();
      var nextDeps = deps === undefined ? null : deps;
      var prevState = hook.memoizedState;

      if (prevState !== null) {
        // Assume these are defined. If they're not, areHookInputsEqual will warn.
        if (nextDeps !== null) {
          var prevDeps = prevState[1];

          if (areHookInputsEqual(nextDeps, prevDeps)) {
            return prevState[0];
          }
        }
      }

      var nextValue = nextCreate();
      hook.memoizedState = [nextValue, nextDeps];
      return nextValue;
    }

    function mountDeferredValue(value, config) {
      var _mountState = mountState(value),
          prevValue = _mountState[0],
          setValue = _mountState[1];

      mountEffect(function () {
        var previousConfig = ReactCurrentBatchConfig$1.suspense;
        ReactCurrentBatchConfig$1.suspense = config === undefined ? null : config;

        try {
          setValue(value);
        } finally {
          ReactCurrentBatchConfig$1.suspense = previousConfig;
        }
      }, [value, config]);
      return prevValue;
    }

    function updateDeferredValue(value, config) {
      var _updateState = updateState(),
          prevValue = _updateState[0],
          setValue = _updateState[1];

      updateEffect(function () {
        var previousConfig = ReactCurrentBatchConfig$1.suspense;
        ReactCurrentBatchConfig$1.suspense = config === undefined ? null : config;

        try {
          setValue(value);
        } finally {
          ReactCurrentBatchConfig$1.suspense = previousConfig;
        }
      }, [value, config]);
      return prevValue;
    }

    function rerenderDeferredValue(value, config) {
      var _rerenderState = rerenderState(),
          prevValue = _rerenderState[0],
          setValue = _rerenderState[1];

      updateEffect(function () {
        var previousConfig = ReactCurrentBatchConfig$1.suspense;
        ReactCurrentBatchConfig$1.suspense = config === undefined ? null : config;

        try {
          setValue(value);
        } finally {
          ReactCurrentBatchConfig$1.suspense = previousConfig;
        }
      }, [value, config]);
      return prevValue;
    }

    function startTransition(setPending, config, callback) {
      var priorityLevel = getCurrentPriorityLevel();
      runWithPriority$1(priorityLevel < UserBlockingPriority$1 ? UserBlockingPriority$1 : priorityLevel, function () {
        setPending(true);
      });
      runWithPriority$1(priorityLevel > NormalPriority ? NormalPriority : priorityLevel, function () {
        var previousConfig = ReactCurrentBatchConfig$1.suspense;
        ReactCurrentBatchConfig$1.suspense = config === undefined ? null : config;

        try {
          setPending(false);
          callback();
        } finally {
          ReactCurrentBatchConfig$1.suspense = previousConfig;
        }
      });
    }

    function mountTransition(config) {
      var _mountState2 = mountState(false),
          isPending = _mountState2[0],
          setPending = _mountState2[1];

      var start = mountCallback(startTransition.bind(null, setPending, config), [setPending, config]);
      return [start, isPending];
    }

    function updateTransition(config) {
      var _updateState2 = updateState(),
          isPending = _updateState2[0],
          setPending = _updateState2[1];

      var start = updateCallback(startTransition.bind(null, setPending, config), [setPending, config]);
      return [start, isPending];
    }

    function rerenderTransition(config) {
      var _rerenderState2 = rerenderState(),
          isPending = _rerenderState2[0],
          setPending = _rerenderState2[1];

      var start = updateCallback(startTransition.bind(null, setPending, config), [setPending, config]);
      return [start, isPending];
    }

    function dispatchAction(fiber, queue, action) {
      {
        if (typeof arguments[3] === 'function') {
          error("State updates from the useState() and useReducer() Hooks don't support the " + 'second callback argument. To execute a side effect after ' + 'rendering, declare it in the component body with useEffect().');
        }
      }
      var currentTime = requestCurrentTimeForUpdate();
      var suspenseConfig = requestCurrentSuspenseConfig();
      var expirationTime = computeExpirationForFiber(currentTime, fiber, suspenseConfig);
      var update = {
        expirationTime: expirationTime,
        suspenseConfig: suspenseConfig,
        action: action,
        eagerReducer: null,
        eagerState: null,
        next: null
      };
      {
        update.priority = getCurrentPriorityLevel();
      } // Append the update to the end of the list.

      var pending = queue.pending;

      if (pending === null) {
        // This is the first update. Create a circular list.
        update.next = update;
      } else {
        update.next = pending.next;
        pending.next = update;
      }

      queue.pending = update;
      var alternate = fiber.alternate;

      if (fiber === currentlyRenderingFiber$1 || alternate !== null && alternate === currentlyRenderingFiber$1) {
        // This is a render phase update. Stash it in a lazily-created map of
        // queue -> linked list of updates. After this render pass, we'll restart
        // and apply the stashed updates on top of the work-in-progress hook.
        didScheduleRenderPhaseUpdate = true;
        update.expirationTime = renderExpirationTime;
        currentlyRenderingFiber$1.expirationTime = renderExpirationTime;
      } else {
        if (fiber.expirationTime === NoWork && (alternate === null || alternate.expirationTime === NoWork)) {
          // The queue is currently empty, which means we can eagerly compute the
          // next state before entering the render phase. If the new state is the
          // same as the current state, we may be able to bail out entirely.
          var lastRenderedReducer = queue.lastRenderedReducer;

          if (lastRenderedReducer !== null) {
            var prevDispatcher;
            {
              prevDispatcher = ReactCurrentDispatcher.current;
              ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
            }

            try {
              var currentState = queue.lastRenderedState;
              var eagerState = lastRenderedReducer(currentState, action); // Stash the eagerly computed state, and the reducer used to compute
              // it, on the update object. If the reducer hasn't changed by the
              // time we enter the render phase, then the eager state can be used
              // without calling the reducer again.

              update.eagerReducer = lastRenderedReducer;
              update.eagerState = eagerState;

              if (objectIs(eagerState, currentState)) {
                // Fast path. We can bail out without scheduling React to re-render.
                // It's still possible that we'll need to rebase this update later,
                // if the component re-renders for a different reason and by that
                // time the reducer has changed.
                return;
              }
            } catch (error) {// Suppress the error. It will throw again in the render phase.
            } finally {
              {
                ReactCurrentDispatcher.current = prevDispatcher;
              }
            }
          }
        }

        {
          // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests
          if ('undefined' !== typeof jest) {
            warnIfNotScopedWithMatchingAct(fiber);
            warnIfNotCurrentlyActingUpdatesInDev(fiber);
          }
        }
        scheduleWork(fiber, expirationTime);
      }
    }

    var ContextOnlyDispatcher = {
      readContext: readContext,
      useCallback: throwInvalidHookError,
      useContext: throwInvalidHookError,
      useEffect: throwInvalidHookError,
      useImperativeHandle: throwInvalidHookError,
      useLayoutEffect: throwInvalidHookError,
      useMemo: throwInvalidHookError,
      useReducer: throwInvalidHookError,
      useRef: throwInvalidHookError,
      useState: throwInvalidHookError,
      useDebugValue: throwInvalidHookError,
      useResponder: throwInvalidHookError,
      useDeferredValue: throwInvalidHookError,
      useTransition: throwInvalidHookError
    };
    var HooksDispatcherOnMountInDEV = null;
    var HooksDispatcherOnMountWithHookTypesInDEV = null;
    var HooksDispatcherOnUpdateInDEV = null;
    var HooksDispatcherOnRerenderInDEV = null;
    var InvalidNestedHooksDispatcherOnMountInDEV = null;
    var InvalidNestedHooksDispatcherOnUpdateInDEV = null;
    var InvalidNestedHooksDispatcherOnRerenderInDEV = null;
    {
      var warnInvalidContextAccess = function () {
        error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().');
      };

      var warnInvalidHookAccess = function () {
        error('Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. ' + 'You can only call Hooks at the top level of your React function. ' + 'For more information, see ' + 'https://fb.me/rules-of-hooks');
      };

      HooksDispatcherOnMountInDEV = {
        readContext: function (context, observedBits) {
          return readContext(context, observedBits);
        },
        useCallback: function (callback, deps) {
          currentHookNameInDev = 'useCallback';
          mountHookTypesDev();
          checkDepsAreArrayDev(deps);
          return mountCallback(callback, deps);
        },
        useContext: function (context, observedBits) {
          currentHookNameInDev = 'useContext';
          mountHookTypesDev();
          return readContext(context, observedBits);
        },
        useEffect: function (create, deps) {
          currentHookNameInDev = 'useEffect';
          mountHookTypesDev();
          checkDepsAreArrayDev(deps);
          return mountEffect(create, deps);
        },
        useImperativeHandle: function (ref, create, deps) {
          currentHookNameInDev = 'useImperativeHandle';
          mountHookTypesDev();
          checkDepsAreArrayDev(deps);
          return mountImperativeHandle(ref, create, deps);
        },
        useLayoutEffect: function (create, deps) {
          currentHookNameInDev = 'useLayoutEffect';
          mountHookTypesDev();
          checkDepsAreArrayDev(deps);
          return mountLayoutEffect(create, deps);
        },
        useMemo: function (create, deps) {
          currentHookNameInDev = 'useMemo';
          mountHookTypesDev();
          checkDepsAreArrayDev(deps);
          var prevDispatcher = ReactCurrentDispatcher.current;
          ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;

          try {
            return mountMemo(create, deps);
          } finally {
            ReactCurrentDispatcher.current = prevDispatcher;
          }
        },
        useReducer: function (reducer, initialArg, init) {
          currentHookNameInDev = 'useReducer';
          mountHookTypesDev();
          var prevDispatcher = ReactCurrentDispatcher.current;
          ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;

          try {
            return mountReducer(reducer, initialArg, init);
          } finally {
            ReactCurrentDispatcher.current = prevDispatcher;
          }
        },
        useRef: function (initialValue) {
          currentHookNameInDev = 'useRef';
          mountHookTypesDev();
          return mountRef(initialValue);
        },
        useState: function (initialState) {
          currentHookNameInDev = 'useState';
          mountHookTypesDev();
          var prevDispatcher = ReactCurrentDispatcher.current;
          ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;

          try {
            return mountState(initialState);
          } finally {
            ReactCurrentDispatcher.current = prevDispatcher;
          }
        },
        useDebugValue: function (value, formatterFn) {
          currentHookNameInDev = 'useDebugValue';
          mountHookTypesDev();
          return mountDebugValue();
        },
        useResponder: function (responder, props) {
          currentHookNameInDev = 'useResponder';
          mountHookTypesDev();
          return createDeprecatedResponderListener(responder, props);
        },
        useDeferredValue: function (value, config) {
          currentHookNameInDev = 'useDeferredValue';
          mountHookTypesDev();
          return mountDeferredValue(value, config);
        },
        useTransition: function (config) {
          currentHookNameInDev = 'useTransition';
          mountHookTypesDev();
          return mountTransition(config);
        }
      };
      HooksDispatcherOnMountWithHookTypesInDEV = {
        readContext: function (context, observedBits) {
          return readContext(context, observedBits);
        },
        useCallback: function (callback, deps) {
          currentHookNameInDev = 'useCallback';
          updateHookTypesDev();
          return mountCallback(callback, deps);
        },
        useContext: function (context, observedBits) {
          currentHookNameInDev = 'useContext';
          updateHookTypesDev();
          return readContext(context, observedBits);
        },
        useEffect: function (create, deps) {
          currentHookNameInDev = 'useEffect';
          updateHookTypesDev();
          return mountEffect(create, deps);
        },
        useImperativeHandle: function (ref, create, deps) {
          currentHookNameInDev = 'useImperativeHandle';
          updateHookTypesDev();
          return mountImperativeHandle(ref, create, deps);
        },
        useLayoutEffect: function (create, deps) {
          currentHookNameInDev = 'useLayoutEffect';
          updateHookTypesDev();
          return mountLayoutEffect(create, deps);
        },
        useMemo: function (create, deps) {
          currentHookNameInDev = 'useMemo';
          updateHookTypesDev();
          var prevDispatcher = ReactCurrentDispatcher.current;
          ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;

          try {
            return mountMemo(create, deps);
          } finally {
            ReactCurrentDispatcher.current = prevDispatcher;
          }
        },
        useReducer: function (reducer, initialArg, init) {
          currentHookNameInDev = 'useReducer';
          updateHookTypesDev();
          var prevDispatcher = ReactCurrentDispatcher.current;
          ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;

          try {
            return mountReducer(reducer, initialArg, init);
          } finally {
            ReactCurrentDispatcher.current = prevDispatcher;
          }
        },
        useRef: function (initialValue) {
          currentHookNameInDev = 'useRef';
          updateHookTypesDev();
          return mountRef(initialValue);
        },
        useState: function (initialState) {
          currentHookNameInDev = 'useState';
          updateHookTypesDev();
          var prevDispatcher = ReactCurrentDispatcher.current;
          ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;

          try {
            return mountState(initialState);
          } finally {
            ReactCurrentDispatcher.current = prevDispatcher;
          }
        },
        useDebugValue: function (value, formatterFn) {
          currentHookNameInDev = 'useDebugValue';
          updateHookTypesDev();
          return mountDebugValue();
        },
        useResponder: function (responder, props) {
          currentHookNameInDev = 'useResponder';
          updateHookTypesDev();
          return createDeprecatedResponderListener(responder, props);
        },
        useDeferredValue: function (value, config) {
          currentHookNameInDev = 'useDeferredValue';
          updateHookTypesDev();
          return mountDeferredValue(value, config);
        },
        useTransition: function (config) {
          currentHookNameInDev = 'useTransition';
          updateHookTypesDev();
          return mountTransition(config);
        }
      };
      HooksDispatcherOnUpdateInDEV = {
        readContext: function (context, observedBits) {
          return readContext(context, observedBits);
        },
        useCallback: function (callback, deps) {
          currentHookNameInDev = 'useCallback';
          updateHookTypesDev();
          return updateCallback(callback, deps);
        },
        useContext: function (context, observedBits) {
          currentHookNameInDev = 'useContext';
          updateHookTypesDev();
          return readContext(context, observedBits);
        },
        useEffect: function (create, deps) {
          currentHookNameInDev = 'useEffect';
          updateHookTypesDev();
          return updateEffect(create, deps);
        },
        useImperativeHandle: function (ref, create, deps) {
          currentHookNameInDev = 'useImperativeHandle';
          updateHookTypesDev();
          return updateImperativeHandle(ref, create, deps);
        },
        useLayoutEffect: function (create, deps) {
          currentHookNameInDev = 'useLayoutEffect';
          updateHookTypesDev();
          return updateLayoutEffect(create, deps);
        },
        useMemo: function (create, deps) {
          currentHookNameInDev = 'useMemo';
          updateHookTypesDev();
          var prevDispatcher = ReactCurrentDispatcher.current;
          ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;

          try {
            return updateMemo(create, deps);
          } finally {
            ReactCurrentDispatcher.current = prevDispatcher;
          }
        },
        useReducer: function (reducer, initialArg, init) {
          currentHookNameInDev = 'useReducer';
          updateHookTypesDev();
          var prevDispatcher = ReactCurrentDispatcher.current;
          ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;

          try {
            return updateReducer(reducer, initialArg, init);
          } finally {
            ReactCurrentDispatcher.current = prevDispatcher;
          }
        },
        useRef: function (initialValue) {
          currentHookNameInDev = 'useRef';
          updateHookTypesDev();
          return updateRef();
        },
        useState: function (initialState) {
          currentHookNameInDev = 'useState';
          updateHookTypesDev();
          var prevDispatcher = ReactCurrentDispatcher.current;
          ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;

          try {
            return updateState(initialState);
          } finally {
            ReactCurrentDispatcher.current = prevDispatcher;
          }
        },
        useDebugValue: function (value, formatterFn) {
          currentHookNameInDev = 'useDebugValue';
          updateHookTypesDev();
          return updateDebugValue();
        },
        useResponder: function (responder, props) {
          currentHookNameInDev = 'useResponder';
          updateHookTypesDev();
          return createDeprecatedResponderListener(responder, props);
        },
        useDeferredValue: function (value, config) {
          currentHookNameInDev = 'useDeferredValue';
          updateHookTypesDev();
          return updateDeferredValue(value, config);
        },
        useTransition: function (config) {
          currentHookNameInDev = 'useTransition';
          updateHookTypesDev();
          return updateTransition(config);
        }
      };
      HooksDispatcherOnRerenderInDEV = {
        readContext: function (context, observedBits) {
          return readContext(context, observedBits);
        },
        useCallback: function (callback, deps) {
          currentHookNameInDev = 'useCallback';
          updateHookTypesDev();
          return updateCallback(callback, deps);
        },
        useContext: function (context, observedBits) {
          currentHookNameInDev = 'useContext';
          updateHookTypesDev();
          return readContext(context, observedBits);
        },
        useEffect: function (create, deps) {
          currentHookNameInDev = 'useEffect';
          updateHookTypesDev();
          return updateEffect(create, deps);
        },
        useImperativeHandle: function (ref, create, deps) {
          currentHookNameInDev = 'useImperativeHandle';
          updateHookTypesDev();
          return updateImperativeHandle(ref, create, deps);
        },
        useLayoutEffect: function (create, deps) {
          currentHookNameInDev = 'useLayoutEffect';
          updateHookTypesDev();
          return updateLayoutEffect(create, deps);
        },
        useMemo: function (create, deps) {
          currentHookNameInDev = 'useMemo';
          updateHookTypesDev();
          var prevDispatcher = ReactCurrentDispatcher.current;
          ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnRerenderInDEV;

          try {
            return updateMemo(create, deps);
          } finally {
            ReactCurrentDispatcher.current = prevDispatcher;
          }
        },
        useReducer: function (reducer, initialArg, init) {
          currentHookNameInDev = 'useReducer';
          updateHookTypesDev();
          var prevDispatcher = ReactCurrentDispatcher.current;
          ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnRerenderInDEV;

          try {
            return rerenderReducer(reducer, initialArg, init);
          } finally {
            ReactCurrentDispatcher.current = prevDispatcher;
          }
        },
        useRef: function (initialValue) {
          currentHookNameInDev = 'useRef';
          updateHookTypesDev();
          return updateRef();
        },
        useState: function (initialState) {
          currentHookNameInDev = 'useState';
          updateHookTypesDev();
          var prevDispatcher = ReactCurrentDispatcher.current;
          ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnRerenderInDEV;

          try {
            return rerenderState(initialState);
          } finally {
            ReactCurrentDispatcher.current = prevDispatcher;
          }
        },
        useDebugValue: function (value, formatterFn) {
          currentHookNameInDev = 'useDebugValue';
          updateHookTypesDev();
          return updateDebugValue();
        },
        useResponder: function (responder, props) {
          currentHookNameInDev = 'useResponder';
          updateHookTypesDev();
          return createDeprecatedResponderListener(responder, props);
        },
        useDeferredValue: function (value, config) {
          currentHookNameInDev = 'useDeferredValue';
          updateHookTypesDev();
          return rerenderDeferredValue(value, config);
        },
        useTransition: function (config) {
          currentHookNameInDev = 'useTransition';
          updateHookTypesDev();
          return rerenderTransition(config);
        }
      };
      InvalidNestedHooksDispatcherOnMountInDEV = {
        readContext: function (context, observedBits) {
          warnInvalidContextAccess();
          return readContext(context, observedBits);
        },
        useCallback: function (callback, deps) {
          currentHookNameInDev = 'useCallback';
          warnInvalidHookAccess();
          mountHookTypesDev();
          return mountCallback(callback, deps);
        },
        useContext: function (context, observedBits) {
          currentHookNameInDev = 'useContext';
          warnInvalidHookAccess();
          mountHookTypesDev();
          return readContext(context, observedBits);
        },
        useEffect: function (create, deps) {
          currentHookNameInDev = 'useEffect';
          warnInvalidHookAccess();
          mountHookTypesDev();
          return mountEffect(create, deps);
        },
        useImperativeHandle: function (ref, create, deps) {
          currentHookNameInDev = 'useImperativeHandle';
          warnInvalidHookAccess();
          mountHookTypesDev();
          return mountImperativeHandle(ref, create, deps);
        },
        useLayoutEffect: function (create, deps) {
          currentHookNameInDev = 'useLayoutEffect';
          warnInvalidHookAccess();
          mountHookTypesDev();
          return mountLayoutEffect(create, deps);
        },
        useMemo: function (create, deps) {
          currentHookNameInDev = 'useMemo';
          warnInvalidHookAccess();
          mountHookTypesDev();
          var prevDispatcher = ReactCurrentDispatcher.current;
          ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;

          try {
            return mountMemo(create, deps);
          } finally {
            ReactCurrentDispatcher.current = prevDispatcher;
          }
        },
        useReducer: function (reducer, initialArg, init) {
          currentHookNameInDev = 'useReducer';
          warnInvalidHookAccess();
          mountHookTypesDev();
          var prevDispatcher = ReactCurrentDispatcher.current;
          ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;

          try {
            return mountReducer(reducer, initialArg, init);
          } finally {
            ReactCurrentDispatcher.current = prevDispatcher;
          }
        },
        useRef: function (initialValue) {
          currentHookNameInDev = 'useRef';
          warnInvalidHookAccess();
          mountHookTypesDev();
          return mountRef(initialValue);
        },
        useState: function (initialState) {
          currentHookNameInDev = 'useState';
          warnInvalidHookAccess();
          mountHookTypesDev();
          var prevDispatcher = ReactCurrentDispatcher.current;
          ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;

          try {
            return mountState(initialState);
          } finally {
            ReactCurrentDispatcher.current = prevDispatcher;
          }
        },
        useDebugValue: function (value, formatterFn) {
          currentHookNameInDev = 'useDebugValue';
          warnInvalidHookAccess();
          mountHookTypesDev();
          return mountDebugValue();
        },
        useResponder: function (responder, props) {
          currentHookNameInDev = 'useResponder';
          warnInvalidHookAccess();
          mountHookTypesDev();
          return createDeprecatedResponderListener(responder, props);
        },
        useDeferredValue: function (value, config) {
          currentHookNameInDev = 'useDeferredValue';
          warnInvalidHookAccess();
          mountHookTypesDev();
          return mountDeferredValue(value, config);
        },
        useTransition: function (config) {
          currentHookNameInDev = 'useTransition';
          warnInvalidHookAccess();
          mountHookTypesDev();
          return mountTransition(config);
        }
      };
      InvalidNestedHooksDispatcherOnUpdateInDEV = {
        readContext: function (context, observedBits) {
          warnInvalidContextAccess();
          return readContext(context, observedBits);
        },
        useCallback: function (callback, deps) {
          currentHookNameInDev = 'useCallback';
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateCallback(callback, deps);
        },
        useContext: function (context, observedBits) {
          currentHookNameInDev = 'useContext';
          warnInvalidHookAccess();
          updateHookTypesDev();
          return readContext(context, observedBits);
        },
        useEffect: function (create, deps) {
          currentHookNameInDev = 'useEffect';
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateEffect(create, deps);
        },
        useImperativeHandle: function (ref, create, deps) {
          currentHookNameInDev = 'useImperativeHandle';
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateImperativeHandle(ref, create, deps);
        },
        useLayoutEffect: function (create, deps) {
          currentHookNameInDev = 'useLayoutEffect';
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateLayoutEffect(create, deps);
        },
        useMemo: function (create, deps) {
          currentHookNameInDev = 'useMemo';
          warnInvalidHookAccess();
          updateHookTypesDev();
          var prevDispatcher = ReactCurrentDispatcher.current;
          ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;

          try {
            return updateMemo(create, deps);
          } finally {
            ReactCurrentDispatcher.current = prevDispatcher;
          }
        },
        useReducer: function (reducer, initialArg, init) {
          currentHookNameInDev = 'useReducer';
          warnInvalidHookAccess();
          updateHookTypesDev();
          var prevDispatcher = ReactCurrentDispatcher.current;
          ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;

          try {
            return updateReducer(reducer, initialArg, init);
          } finally {
            ReactCurrentDispatcher.current = prevDispatcher;
          }
        },
        useRef: function (initialValue) {
          currentHookNameInDev = 'useRef';
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateRef();
        },
        useState: function (initialState) {
          currentHookNameInDev = 'useState';
          warnInvalidHookAccess();
          updateHookTypesDev();
          var prevDispatcher = ReactCurrentDispatcher.current;
          ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;

          try {
            return updateState(initialState);
          } finally {
            ReactCurrentDispatcher.current = prevDispatcher;
          }
        },
        useDebugValue: function (value, formatterFn) {
          currentHookNameInDev = 'useDebugValue';
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateDebugValue();
        },
        useResponder: function (responder, props) {
          currentHookNameInDev = 'useResponder';
          warnInvalidHookAccess();
          updateHookTypesDev();
          return createDeprecatedResponderListener(responder, props);
        },
        useDeferredValue: function (value, config) {
          currentHookNameInDev = 'useDeferredValue';
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateDeferredValue(value, config);
        },
        useTransition: function (config) {
          currentHookNameInDev = 'useTransition';
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateTransition(config);
        }
      };
      InvalidNestedHooksDispatcherOnRerenderInDEV = {
        readContext: function (context, observedBits) {
          warnInvalidContextAccess();
          return readContext(context, observedBits);
        },
        useCallback: function (callback, deps) {
          currentHookNameInDev = 'useCallback';
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateCallback(callback, deps);
        },
        useContext: function (context, observedBits) {
          currentHookNameInDev = 'useContext';
          warnInvalidHookAccess();
          updateHookTypesDev();
          return readContext(context, observedBits);
        },
        useEffect: function (create, deps) {
          currentHookNameInDev = 'useEffect';
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateEffect(create, deps);
        },
        useImperativeHandle: function (ref, create, deps) {
          currentHookNameInDev = 'useImperativeHandle';
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateImperativeHandle(ref, create, deps);
        },
        useLayoutEffect: function (create, deps) {
          currentHookNameInDev = 'useLayoutEffect';
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateLayoutEffect(create, deps);
        },
        useMemo: function (create, deps) {
          currentHookNameInDev = 'useMemo';
          warnInvalidHookAccess();
          updateHookTypesDev();
          var prevDispatcher = ReactCurrentDispatcher.current;
          ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;

          try {
            return updateMemo(create, deps);
          } finally {
            ReactCurrentDispatcher.current = prevDispatcher;
          }
        },
        useReducer: function (reducer, initialArg, init) {
          currentHookNameInDev = 'useReducer';
          warnInvalidHookAccess();
          updateHookTypesDev();
          var prevDispatcher = ReactCurrentDispatcher.current;
          ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;

          try {
            return rerenderReducer(reducer, initialArg, init);
          } finally {
            ReactCurrentDispatcher.current = prevDispatcher;
          }
        },
        useRef: function (initialValue) {
          currentHookNameInDev = 'useRef';
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateRef();
        },
        useState: function (initialState) {
          currentHookNameInDev = 'useState';
          warnInvalidHookAccess();
          updateHookTypesDev();
          var prevDispatcher = ReactCurrentDispatcher.current;
          ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;

          try {
            return rerenderState(initialState);
          } finally {
            ReactCurrentDispatcher.current = prevDispatcher;
          }
        },
        useDebugValue: function (value, formatterFn) {
          currentHookNameInDev = 'useDebugValue';
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateDebugValue();
        },
        useResponder: function (responder, props) {
          currentHookNameInDev = 'useResponder';
          warnInvalidHookAccess();
          updateHookTypesDev();
          return createDeprecatedResponderListener(responder, props);
        },
        useDeferredValue: function (value, config) {
          currentHookNameInDev = 'useDeferredValue';
          warnInvalidHookAccess();
          updateHookTypesDev();
          return rerenderDeferredValue(value, config);
        },
        useTransition: function (config) {
          currentHookNameInDev = 'useTransition';
          warnInvalidHookAccess();
          updateHookTypesDev();
          return rerenderTransition(config);
        }
      };
    }
    var now$1 = Scheduler.unstable_now;
    var commitTime = 0;
    var profilerStartTime = -1;

    function getCommitTime() {
      return commitTime;
    }

    function recordCommitTime() {
      commitTime = now$1();
    }

    function startProfilerTimer(fiber) {
      profilerStartTime = now$1();

      if (fiber.actualStartTime < 0) {
        fiber.actualStartTime = now$1();
      }
    }

    function stopProfilerTimerIfRunning(fiber) {
      profilerStartTime = -1;
    }

    function stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) {
      if (profilerStartTime >= 0) {
        var elapsedTime = now$1() - profilerStartTime;
        fiber.actualDuration += elapsedTime;

        if (overrideBaseTime) {
          fiber.selfBaseDuration = elapsedTime;
        }

        profilerStartTime = -1;
      }
    } // This may have been an insertion or a hydration.


    var hydrationParentFiber = null;
    var nextHydratableInstance = null;
    var isHydrating = false;

    function enterHydrationState(fiber) {
      var parentInstance = fiber.stateNode.containerInfo;
      nextHydratableInstance = getFirstHydratableChild(parentInstance);
      hydrationParentFiber = fiber;
      isHydrating = true;
      return true;
    }

    function deleteHydratableInstance(returnFiber, instance) {
      {
        switch (returnFiber.tag) {
          case HostRoot:
            didNotHydrateContainerInstance(returnFiber.stateNode.containerInfo, instance);
            break;

          case HostComponent:
            didNotHydrateInstance(returnFiber.type, returnFiber.memoizedProps, returnFiber.stateNode, instance);
            break;
        }
      }
      var childToDelete = createFiberFromHostInstanceForDeletion();
      childToDelete.stateNode = instance;
      childToDelete.return = returnFiber;
      childToDelete.effectTag = Deletion; // This might seem like it belongs on progressedFirstDeletion. However,
      // these children are not part of the reconciliation list of children.
      // Even if we abort and rereconcile the children, that will try to hydrate
      // again and the nodes are still in the host tree so these will be
      // recreated.

      if (returnFiber.lastEffect !== null) {
        returnFiber.lastEffect.nextEffect = childToDelete;
        returnFiber.lastEffect = childToDelete;
      } else {
        returnFiber.firstEffect = returnFiber.lastEffect = childToDelete;
      }
    }

    function insertNonHydratedInstance(returnFiber, fiber) {
      fiber.effectTag = fiber.effectTag & ~Hydrating | Placement;
      {
        switch (returnFiber.tag) {
          case HostRoot:
            {
              var parentContainer = returnFiber.stateNode.containerInfo;

              switch (fiber.tag) {
                case HostComponent:
                  var type = fiber.type;
                  var props = fiber.pendingProps;
                  didNotFindHydratableContainerInstance(parentContainer, type);
                  break;

                case HostText:
                  var text = fiber.pendingProps;
                  didNotFindHydratableContainerTextInstance(parentContainer, text);
                  break;
              }

              break;
            }

          case HostComponent:
            {
              var parentType = returnFiber.type;
              var parentProps = returnFiber.memoizedProps;
              var parentInstance = returnFiber.stateNode;

              switch (fiber.tag) {
                case HostComponent:
                  var _type = fiber.type;
                  var _props = fiber.pendingProps;
                  didNotFindHydratableInstance(parentType, parentProps, parentInstance, _type);
                  break;

                case HostText:
                  var _text = fiber.pendingProps;
                  didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, _text);
                  break;

                case SuspenseComponent:
                  didNotFindHydratableSuspenseInstance(parentType, parentProps);
                  break;
              }

              break;
            }

          default:
            return;
        }
      }
    }

    function tryHydrate(fiber, nextInstance) {
      switch (fiber.tag) {
        case HostComponent:
          {
            var type = fiber.type;
            var props = fiber.pendingProps;
            var instance = canHydrateInstance(nextInstance, type);

            if (instance !== null) {
              fiber.stateNode = instance;
              return true;
            }

            return false;
          }

        case HostText:
          {
            var text = fiber.pendingProps;
            var textInstance = canHydrateTextInstance(nextInstance, text);

            if (textInstance !== null) {
              fiber.stateNode = textInstance;
              return true;
            }

            return false;
          }

        case SuspenseComponent:
          {
            return false;
          }

        default:
          return false;
      }
    }

    function tryToClaimNextHydratableInstance(fiber) {
      if (!isHydrating) {
        return;
      }

      var nextInstance = nextHydratableInstance;

      if (!nextInstance) {
        // Nothing to hydrate. Make it an insertion.
        insertNonHydratedInstance(hydrationParentFiber, fiber);
        isHydrating = false;
        hydrationParentFiber = fiber;
        return;
      }

      var firstAttemptedInstance = nextInstance;

      if (!tryHydrate(fiber, nextInstance)) {
        // If we can't hydrate this instance let's try the next one.
        // We use this as a heuristic. It's based on intuition and not data so it
        // might be flawed or unnecessary.
        nextInstance = getNextHydratableSibling(firstAttemptedInstance);

        if (!nextInstance || !tryHydrate(fiber, nextInstance)) {
          // Nothing to hydrate. Make it an insertion.
          insertNonHydratedInstance(hydrationParentFiber, fiber);
          isHydrating = false;
          hydrationParentFiber = fiber;
          return;
        } // We matched the next one, we'll now assume that the first one was
        // superfluous and we'll delete it. Since we can't eagerly delete it
        // we'll have to schedule a deletion. To do that, this node needs a dummy
        // fiber associated with it.


        deleteHydratableInstance(hydrationParentFiber, firstAttemptedInstance);
      }

      hydrationParentFiber = fiber;
      nextHydratableInstance = getFirstHydratableChild(nextInstance);
    }

    function prepareToHydrateHostInstance(fiber, rootContainerInstance, hostContext) {
      var instance = fiber.stateNode;
      var updatePayload = hydrateInstance(instance, fiber.type, fiber.memoizedProps, rootContainerInstance, hostContext, fiber); // TODO: Type this specific to this type of component.

      fiber.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there
      // is a new ref we mark this as an update.

      if (updatePayload !== null) {
        return true;
      }

      return false;
    }

    function prepareToHydrateHostTextInstance(fiber) {
      var textInstance = fiber.stateNode;
      var textContent = fiber.memoizedProps;
      var shouldUpdate = hydrateTextInstance(textInstance, textContent, fiber);
      {
        if (shouldUpdate) {
          // We assume that prepareToHydrateHostTextInstance is called in a context where the
          // hydration parent is the parent host component of this host text.
          var returnFiber = hydrationParentFiber;

          if (returnFiber !== null) {
            switch (returnFiber.tag) {
              case HostRoot:
                {
                  var parentContainer = returnFiber.stateNode.containerInfo;
                  didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, textContent);
                  break;
                }

              case HostComponent:
                {
                  var parentType = returnFiber.type;
                  var parentProps = returnFiber.memoizedProps;
                  var parentInstance = returnFiber.stateNode;
                  didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, textContent);
                  break;
                }
            }
          }
        }
      }
      return shouldUpdate;
    }

    function skipPastDehydratedSuspenseInstance(fiber) {
      var suspenseState = fiber.memoizedState;
      var suspenseInstance = suspenseState !== null ? suspenseState.dehydrated : null;

      if (!suspenseInstance) {
        {
          throw Error("Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue.");
        }
      }

      return getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance);
    }

    function popToNextHostParent(fiber) {
      var parent = fiber.return;

      while (parent !== null && parent.tag !== HostComponent && parent.tag !== HostRoot && parent.tag !== SuspenseComponent) {
        parent = parent.return;
      }

      hydrationParentFiber = parent;
    }

    function popHydrationState(fiber) {
      if (fiber !== hydrationParentFiber) {
        // We're deeper than the current hydration context, inside an inserted
        // tree.
        return false;
      }

      if (!isHydrating) {
        // If we're not currently hydrating but we're in a hydration context, then
        // we were an insertion and now need to pop up reenter hydration of our
        // siblings.
        popToNextHostParent(fiber);
        isHydrating = true;
        return false;
      }

      var type = fiber.type; // If we have any remaining hydratable nodes, we need to delete them now.
      // We only do this deeper than head and body since they tend to have random
      // other nodes in them. We also ignore components with pure text content in
      // side of them.
      // TODO: Better heuristic.

      if (fiber.tag !== HostComponent || type !== 'head' && type !== 'body' && !shouldSetTextContent(type, fiber.memoizedProps)) {
        var nextInstance = nextHydratableInstance;

        while (nextInstance) {
          deleteHydratableInstance(fiber, nextInstance);
          nextInstance = getNextHydratableSibling(nextInstance);
        }
      }

      popToNextHostParent(fiber);

      if (fiber.tag === SuspenseComponent) {
        nextHydratableInstance = skipPastDehydratedSuspenseInstance(fiber);
      } else {
        nextHydratableInstance = hydrationParentFiber ? getNextHydratableSibling(fiber.stateNode) : null;
      }

      return true;
    }

    function resetHydrationState() {
      hydrationParentFiber = null;
      nextHydratableInstance = null;
      isHydrating = false;
    }

    var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;
    var didReceiveUpdate = false;
    var didWarnAboutBadClass;
    var didWarnAboutModulePatternComponent;
    var didWarnAboutContextTypeOnFunctionComponent;
    var didWarnAboutGetDerivedStateOnFunctionComponent;
    var didWarnAboutFunctionRefs;
    var didWarnAboutReassigningProps;
    var didWarnAboutRevealOrder;
    var didWarnAboutTailOptions;
    {
      didWarnAboutBadClass = {};
      didWarnAboutModulePatternComponent = {};
      didWarnAboutContextTypeOnFunctionComponent = {};
      didWarnAboutGetDerivedStateOnFunctionComponent = {};
      didWarnAboutFunctionRefs = {};
      didWarnAboutReassigningProps = false;
      didWarnAboutRevealOrder = {};
      didWarnAboutTailOptions = {};
    }

    function reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime) {
      if (current === null) {
        // If this is a fresh new component that hasn't been rendered yet, we
        // won't update its child set by applying minimal side-effects. Instead,
        // we will add them all to the child before it gets rendered. That means
        // we can optimize this reconciliation pass by not tracking side-effects.
        workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
      } else {
        // If the current child is the same as the work in progress, it means that
        // we haven't yet started any work on these children. Therefore, we use
        // the clone algorithm to create a copy of all the current children.
        // If we had any progressed work already, that is invalid at this point so
        // let's throw it out.
        workInProgress.child = reconcileChildFibers(workInProgress, current.child, nextChildren, renderExpirationTime);
      }
    }

    function forceUnmountCurrentAndReconcile(current, workInProgress, nextChildren, renderExpirationTime) {
      // This function is fork of reconcileChildren. It's used in cases where we
      // want to reconcile without matching against the existing set. This has the
      // effect of all current children being unmounted; even if the type and key
      // are the same, the old child is unmounted and a new child is created.
      //
      // To do this, we're going to go through the reconcile algorithm twice. In
      // the first pass, we schedule a deletion for all the current children by
      // passing null.
      workInProgress.child = reconcileChildFibers(workInProgress, current.child, null, renderExpirationTime); // In the second pass, we mount the new children. The trick here is that we
      // pass null in place of where we usually pass the current child set. This has
      // the effect of remounting all children regardless of whether their
      // identities match.

      workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
    }

    function updateForwardRef(current, workInProgress, Component, nextProps, renderExpirationTime) {
      // TODO: current can be non-null here even if the component
      // hasn't yet mounted. This happens after the first render suspends.
      // We'll need to figure out if this is fine or can cause issues.
      {
        if (workInProgress.type !== workInProgress.elementType) {
          // Lazy component props can't be validated in createElement
          // because they're only guaranteed to be resolved here.
          var innerPropTypes = Component.propTypes;

          if (innerPropTypes) {
            checkPropTypes(innerPropTypes, nextProps, // Resolved props
            'prop', getComponentName(Component), getCurrentFiberStackInDev);
          }
        }
      }
      var render = Component.render;
      var ref = workInProgress.ref; // The rest is a fork of updateFunctionComponent

      var nextChildren;
      prepareToReadContext(workInProgress, renderExpirationTime);
      {
        ReactCurrentOwner$1.current = workInProgress;
        setIsRendering(true);
        nextChildren = renderWithHooks(current, workInProgress, render, nextProps, ref, renderExpirationTime);

        if (workInProgress.mode & StrictMode) {
          // Only double-render components with Hooks
          if (workInProgress.memoizedState !== null) {
            nextChildren = renderWithHooks(current, workInProgress, render, nextProps, ref, renderExpirationTime);
          }
        }

        setIsRendering(false);
      }

      if (current !== null && !didReceiveUpdate) {
        bailoutHooks(current, workInProgress, renderExpirationTime);
        return bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);
      } // React DevTools reads this flag.


      workInProgress.effectTag |= PerformedWork;
      reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);
      return workInProgress.child;
    }

    function updateMemoComponent(current, workInProgress, Component, nextProps, updateExpirationTime, renderExpirationTime) {
      if (current === null) {
        var type = Component.type;

        if (isSimpleFunctionComponent(type) && Component.compare === null && // SimpleMemoComponent codepath doesn't resolve outer props either.
        Component.defaultProps === undefined) {
          var resolvedType = type;
          {
            resolvedType = resolveFunctionForHotReloading(type);
          } // If this is a plain function component without default props,
          // and with only the default shallow comparison, we upgrade it
          // to a SimpleMemoComponent to allow fast path updates.

          workInProgress.tag = SimpleMemoComponent;
          workInProgress.type = resolvedType;
          {
            validateFunctionComponentInDev(workInProgress, type);
          }
          return updateSimpleMemoComponent(current, workInProgress, resolvedType, nextProps, updateExpirationTime, renderExpirationTime);
        }

        {
          var innerPropTypes = type.propTypes;

          if (innerPropTypes) {
            // Inner memo component props aren't currently validated in createElement.
            // We could move it there, but we'd still need this for lazy code path.
            checkPropTypes(innerPropTypes, nextProps, // Resolved props
            'prop', getComponentName(type), getCurrentFiberStackInDev);
          }
        }
        var child = createFiberFromTypeAndProps(Component.type, null, nextProps, null, workInProgress.mode, renderExpirationTime);
        child.ref = workInProgress.ref;
        child.return = workInProgress;
        workInProgress.child = child;
        return child;
      }

      {
        var _type = Component.type;
        var _innerPropTypes = _type.propTypes;

        if (_innerPropTypes) {
          // Inner memo component props aren't currently validated in createElement.
          // We could move it there, but we'd still need this for lazy code path.
          checkPropTypes(_innerPropTypes, nextProps, // Resolved props
          'prop', getComponentName(_type), getCurrentFiberStackInDev);
        }
      }
      var currentChild = current.child; // This is always exactly one child

      if (updateExpirationTime < renderExpirationTime) {
        // This will be the props with resolved defaultProps,
        // unlike current.memoizedProps which will be the unresolved ones.
        var prevProps = currentChild.memoizedProps; // Default to shallow comparison

        var compare = Component.compare;
        compare = compare !== null ? compare : shallowEqual;

        if (compare(prevProps, nextProps) && current.ref === workInProgress.ref) {
          return bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);
        }
      } // React DevTools reads this flag.


      workInProgress.effectTag |= PerformedWork;
      var newChild = createWorkInProgress(currentChild, nextProps);
      newChild.ref = workInProgress.ref;
      newChild.return = workInProgress;
      workInProgress.child = newChild;
      return newChild;
    }

    function updateSimpleMemoComponent(current, workInProgress, Component, nextProps, updateExpirationTime, renderExpirationTime) {
      // TODO: current can be non-null here even if the component
      // hasn't yet mounted. This happens when the inner render suspends.
      // We'll need to figure out if this is fine or can cause issues.
      {
        if (workInProgress.type !== workInProgress.elementType) {
          // Lazy component props can't be validated in createElement
          // because they're only guaranteed to be resolved here.
          var outerMemoType = workInProgress.elementType;

          if (outerMemoType.$$typeof === REACT_LAZY_TYPE) {
            // We warn when you define propTypes on lazy()
            // so let's just skip over it to find memo() outer wrapper.
            // Inner props for memo are validated later.
            outerMemoType = refineResolvedLazyComponent(outerMemoType);
          }

          var outerPropTypes = outerMemoType && outerMemoType.propTypes;

          if (outerPropTypes) {
            checkPropTypes(outerPropTypes, nextProps, // Resolved (SimpleMemoComponent has no defaultProps)
            'prop', getComponentName(outerMemoType), getCurrentFiberStackInDev);
          } // Inner propTypes will be validated in the function component path.

        }
      }

      if (current !== null) {
        var prevProps = current.memoizedProps;

        if (shallowEqual(prevProps, nextProps) && current.ref === workInProgress.ref && // Prevent bailout if the implementation changed due to hot reload.
        workInProgress.type === current.type) {
          didReceiveUpdate = false;

          if (updateExpirationTime < renderExpirationTime) {
            // The pending update priority was cleared at the beginning of
            // beginWork. We're about to bail out, but there might be additional
            // updates at a lower priority. Usually, the priority level of the
            // remaining updates is accumlated during the evaluation of the
            // component (i.e. when processing the update queue). But since since
            // we're bailing out early *without* evaluating the component, we need
            // to account for it here, too. Reset to the value of the current fiber.
            // NOTE: This only applies to SimpleMemoComponent, not MemoComponent,
            // because a MemoComponent fiber does not have hooks or an update queue;
            // rather, it wraps around an inner component, which may or may not
            // contains hooks.
            // TODO: Move the reset at in beginWork out of the common path so that
            // this is no longer necessary.
            workInProgress.expirationTime = current.expirationTime;
            return bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);
          }
        }
      }

      return updateFunctionComponent(current, workInProgress, Component, nextProps, renderExpirationTime);
    }

    function updateFragment(current, workInProgress, renderExpirationTime) {
      var nextChildren = workInProgress.pendingProps;
      reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);
      return workInProgress.child;
    }

    function updateMode(current, workInProgress, renderExpirationTime) {
      var nextChildren = workInProgress.pendingProps.children;
      reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);
      return workInProgress.child;
    }

    function updateProfiler(current, workInProgress, renderExpirationTime) {
      {
        workInProgress.effectTag |= Update;
      }
      var nextProps = workInProgress.pendingProps;
      var nextChildren = nextProps.children;
      reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);
      return workInProgress.child;
    }

    function markRef(current, workInProgress) {
      var ref = workInProgress.ref;

      if (current === null && ref !== null || current !== null && current.ref !== ref) {
        // Schedule a Ref effect
        workInProgress.effectTag |= Ref;
      }
    }

    function updateFunctionComponent(current, workInProgress, Component, nextProps, renderExpirationTime) {
      {
        if (workInProgress.type !== workInProgress.elementType) {
          // Lazy component props can't be validated in createElement
          // because they're only guaranteed to be resolved here.
          var innerPropTypes = Component.propTypes;

          if (innerPropTypes) {
            checkPropTypes(innerPropTypes, nextProps, // Resolved props
            'prop', getComponentName(Component), getCurrentFiberStackInDev);
          }
        }
      }
      var context;
      {
        var unmaskedContext = getUnmaskedContext(workInProgress, Component, true);
        context = getMaskedContext(workInProgress, unmaskedContext);
      }
      var nextChildren;
      prepareToReadContext(workInProgress, renderExpirationTime);
      {
        ReactCurrentOwner$1.current = workInProgress;
        setIsRendering(true);
        nextChildren = renderWithHooks(current, workInProgress, Component, nextProps, context, renderExpirationTime);

        if (workInProgress.mode & StrictMode) {
          // Only double-render components with Hooks
          if (workInProgress.memoizedState !== null) {
            nextChildren = renderWithHooks(current, workInProgress, Component, nextProps, context, renderExpirationTime);
          }
        }

        setIsRendering(false);
      }

      if (current !== null && !didReceiveUpdate) {
        bailoutHooks(current, workInProgress, renderExpirationTime);
        return bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);
      } // React DevTools reads this flag.


      workInProgress.effectTag |= PerformedWork;
      reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);
      return workInProgress.child;
    }

    function updateClassComponent(current, workInProgress, Component, nextProps, renderExpirationTime) {
      {
        if (workInProgress.type !== workInProgress.elementType) {
          // Lazy component props can't be validated in createElement
          // because they're only guaranteed to be resolved here.
          var innerPropTypes = Component.propTypes;

          if (innerPropTypes) {
            checkPropTypes(innerPropTypes, nextProps, // Resolved props
            'prop', getComponentName(Component), getCurrentFiberStackInDev);
          }
        }
      } // Push context providers early to prevent context stack mismatches.
      // During mounting we don't know the child context yet as the instance doesn't exist.
      // We will invalidate the child context in finishClassComponent() right after rendering.

      var hasContext;

      if (isContextProvider(Component)) {
        hasContext = true;
        pushContextProvider(workInProgress);
      } else {
        hasContext = false;
      }

      prepareToReadContext(workInProgress, renderExpirationTime);
      var instance = workInProgress.stateNode;
      var shouldUpdate;

      if (instance === null) {
        if (current !== null) {
          // A class component without an instance only mounts if it suspended
          // inside a non-concurrent tree, in an inconsistent state. We want to
          // treat it like a new mount, even though an empty version of it already
          // committed. Disconnect the alternate pointers.
          current.alternate = null;
          workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect

          workInProgress.effectTag |= Placement;
        } // In the initial pass we might need to construct the instance.


        constructClassInstance(workInProgress, Component, nextProps);
        mountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
        shouldUpdate = true;
      } else if (current === null) {
        // In a resume, we'll already have an instance we can reuse.
        shouldUpdate = resumeMountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
      } else {
        shouldUpdate = updateClassInstance(current, workInProgress, Component, nextProps, renderExpirationTime);
      }

      var nextUnitOfWork = finishClassComponent(current, workInProgress, Component, shouldUpdate, hasContext, renderExpirationTime);
      {
        var inst = workInProgress.stateNode;

        if (inst.props !== nextProps) {
          if (!didWarnAboutReassigningProps) {
            error('It looks like %s is reassigning its own `this.props` while rendering. ' + 'This is not supported and can lead to confusing bugs.', getComponentName(workInProgress.type) || 'a component');
          }

          didWarnAboutReassigningProps = true;
        }
      }
      return nextUnitOfWork;
    }

    function finishClassComponent(current, workInProgress, Component, shouldUpdate, hasContext, renderExpirationTime) {
      // Refs should update even if shouldComponentUpdate returns false
      markRef(current, workInProgress);
      var didCaptureError = (workInProgress.effectTag & DidCapture) !== NoEffect;

      if (!shouldUpdate && !didCaptureError) {
        // Context providers should defer to sCU for rendering
        if (hasContext) {
          invalidateContextProvider(workInProgress, Component, false);
        }

        return bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);
      }

      var instance = workInProgress.stateNode; // Rerender

      ReactCurrentOwner$1.current = workInProgress;
      var nextChildren;

      if (didCaptureError && typeof Component.getDerivedStateFromError !== 'function') {
        // If we captured an error, but getDerivedStateFromError is not defined,
        // unmount all the children. componentDidCatch will schedule an update to
        // re-render a fallback. This is temporary until we migrate everyone to
        // the new API.
        // TODO: Warn in a future release.
        nextChildren = null;
        {
          stopProfilerTimerIfRunning();
        }
      } else {
        {
          setIsRendering(true);
          nextChildren = instance.render();

          if (workInProgress.mode & StrictMode) {
            instance.render();
          }

          setIsRendering(false);
        }
      } // React DevTools reads this flag.


      workInProgress.effectTag |= PerformedWork;

      if (current !== null && didCaptureError) {
        // If we're recovering from an error, reconcile without reusing any of
        // the existing children. Conceptually, the normal children and the children
        // that are shown on error are two different sets, so we shouldn't reuse
        // normal children even if their identities match.
        forceUnmountCurrentAndReconcile(current, workInProgress, nextChildren, renderExpirationTime);
      } else {
        reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);
      } // Memoize state using the values we just used to render.
      // TODO: Restructure so we never read values from the instance.


      workInProgress.memoizedState = instance.state; // The context might have changed so we need to recalculate it.

      if (hasContext) {
        invalidateContextProvider(workInProgress, Component, true);
      }

      return workInProgress.child;
    }

    function pushHostRootContext(workInProgress) {
      var root = workInProgress.stateNode;

      if (root.pendingContext) {
        pushTopLevelContextObject(workInProgress, root.pendingContext, root.pendingContext !== root.context);
      } else if (root.context) {
        // Should always be set
        pushTopLevelContextObject(workInProgress, root.context, false);
      }

      pushHostContainer(workInProgress, root.containerInfo);
    }

    function updateHostRoot(current, workInProgress, renderExpirationTime) {
      pushHostRootContext(workInProgress);
      var updateQueue = workInProgress.updateQueue;

      if (!(current !== null && updateQueue !== null)) {
        {
          throw Error("If the root does not have an updateQueue, we should have already bailed out. This error is likely caused by a bug in React. Please file an issue.");
        }
      }

      var nextProps = workInProgress.pendingProps;
      var prevState = workInProgress.memoizedState;
      var prevChildren = prevState !== null ? prevState.element : null;
      cloneUpdateQueue(current, workInProgress);
      processUpdateQueue(workInProgress, nextProps, null, renderExpirationTime);
      var nextState = workInProgress.memoizedState; // Caution: React DevTools currently depends on this property
      // being called "element".

      var nextChildren = nextState.element;

      if (nextChildren === prevChildren) {
        // If the state is the same as before, that's a bailout because we had
        // no work that expires at this time.
        resetHydrationState();
        return bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);
      }

      var root = workInProgress.stateNode;

      if (root.hydrate && enterHydrationState(workInProgress)) {
        // If we don't have any current children this might be the first pass.
        // We always try to hydrate. If this isn't a hydration pass there won't
        // be any children to hydrate which is effectively the same thing as
        // not hydrating.
        var child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
        workInProgress.child = child;
        var node = child;

        while (node) {
          // Mark each child as hydrating. This is a fast path to know whether this
          // tree is part of a hydrating tree. This is used to determine if a child
          // node has fully mounted yet, and for scheduling event replaying.
          // Conceptually this is similar to Placement in that a new subtree is
          // inserted into the React tree here. It just happens to not need DOM
          // mutations because it already exists.
          node.effectTag = node.effectTag & ~Placement | Hydrating;
          node = node.sibling;
        }
      } else {
        // Otherwise reset hydration state in case we aborted and resumed another
        // root.
        reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);
        resetHydrationState();
      }

      return workInProgress.child;
    }

    function updateHostComponent(current, workInProgress, renderExpirationTime) {
      pushHostContext(workInProgress);

      if (current === null) {
        tryToClaimNextHydratableInstance(workInProgress);
      }

      var type = workInProgress.type;
      var nextProps = workInProgress.pendingProps;
      var prevProps = current !== null ? current.memoizedProps : null;
      var nextChildren = nextProps.children;
      var isDirectTextChild = shouldSetTextContent(type, nextProps);

      if (isDirectTextChild) {
        // We special case a direct text child of a host node. This is a common
        // case. We won't handle it as a reified child. We will instead handle
        // this in the host environment that also has access to this prop. That
        // avoids allocating another HostText fiber and traversing it.
        nextChildren = null;
      } else if (prevProps !== null && shouldSetTextContent(type, prevProps)) {
        // If we're switching from a direct text child to a normal child, or to
        // empty, we need to schedule the text content to be reset.
        workInProgress.effectTag |= ContentReset;
      }

      markRef(current, workInProgress); // Check the host config to see if the children are offscreen/hidden.

      if (workInProgress.mode & ConcurrentMode && renderExpirationTime !== Never && shouldDeprioritizeSubtree(type, nextProps)) {
        {
          markSpawnedWork(Never);
        } // Schedule this fiber to re-render at offscreen priority. Then bailout.

        workInProgress.expirationTime = workInProgress.childExpirationTime = Never;
        return null;
      }

      reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);
      return workInProgress.child;
    }

    function updateHostText(current, workInProgress) {
      if (current === null) {
        tryToClaimNextHydratableInstance(workInProgress);
      } // Nothing to do here. This is terminal. We'll do the completion step
      // immediately after.


      return null;
    }

    function mountLazyComponent(_current, workInProgress, elementType, updateExpirationTime, renderExpirationTime) {
      if (_current !== null) {
        // A lazy component only mounts if it suspended inside a non-
        // concurrent tree, in an inconsistent state. We want to treat it like
        // a new mount, even though an empty version of it already committed.
        // Disconnect the alternate pointers.
        _current.alternate = null;
        workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect

        workInProgress.effectTag |= Placement;
      }

      var props = workInProgress.pendingProps; // We can't start a User Timing measurement with correct label yet.
      // Cancel and resume right after we know the tag.

      cancelWorkTimer(workInProgress);
      var Component = readLazyComponentType(elementType); // Store the unwrapped component in the type.

      workInProgress.type = Component;
      var resolvedTag = workInProgress.tag = resolveLazyComponentTag(Component);
      startWorkTimer(workInProgress);
      var resolvedProps = resolveDefaultProps(Component, props);
      var child;

      switch (resolvedTag) {
        case FunctionComponent:
          {
            {
              validateFunctionComponentInDev(workInProgress, Component);
              workInProgress.type = Component = resolveFunctionForHotReloading(Component);
            }
            child = updateFunctionComponent(null, workInProgress, Component, resolvedProps, renderExpirationTime);
            return child;
          }

        case ClassComponent:
          {
            {
              workInProgress.type = Component = resolveClassForHotReloading(Component);
            }
            child = updateClassComponent(null, workInProgress, Component, resolvedProps, renderExpirationTime);
            return child;
          }

        case ForwardRef:
          {
            {
              workInProgress.type = Component = resolveForwardRefForHotReloading(Component);
            }
            child = updateForwardRef(null, workInProgress, Component, resolvedProps, renderExpirationTime);
            return child;
          }

        case MemoComponent:
          {
            {
              if (workInProgress.type !== workInProgress.elementType) {
                var outerPropTypes = Component.propTypes;

                if (outerPropTypes) {
                  checkPropTypes(outerPropTypes, resolvedProps, // Resolved for outer only
                  'prop', getComponentName(Component), getCurrentFiberStackInDev);
                }
              }
            }
            child = updateMemoComponent(null, workInProgress, Component, resolveDefaultProps(Component.type, resolvedProps), // The inner type can have defaults too
            updateExpirationTime, renderExpirationTime);
            return child;
          }
      }

      var hint = '';
      {
        if (Component !== null && typeof Component === 'object' && Component.$$typeof === REACT_LAZY_TYPE) {
          hint = ' Did you wrap a component in React.lazy() more than once?';
        }
      } // This message intentionally doesn't mention ForwardRef or MemoComponent
      // because the fact that it's a separate type of work is an
      // implementation detail.

      {
        {
          throw Error("Element type is invalid. Received a promise that resolves to: " + Component + ". Lazy element type must resolve to a class or function." + hint);
        }
      }
    }

    function mountIncompleteClassComponent(_current, workInProgress, Component, nextProps, renderExpirationTime) {
      if (_current !== null) {
        // An incomplete component only mounts if it suspended inside a non-
        // concurrent tree, in an inconsistent state. We want to treat it like
        // a new mount, even though an empty version of it already committed.
        // Disconnect the alternate pointers.
        _current.alternate = null;
        workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect

        workInProgress.effectTag |= Placement;
      } // Promote the fiber to a class and try rendering again.


      workInProgress.tag = ClassComponent; // The rest of this function is a fork of `updateClassComponent`
      // Push context providers early to prevent context stack mismatches.
      // During mounting we don't know the child context yet as the instance doesn't exist.
      // We will invalidate the child context in finishClassComponent() right after rendering.

      var hasContext;

      if (isContextProvider(Component)) {
        hasContext = true;
        pushContextProvider(workInProgress);
      } else {
        hasContext = false;
      }

      prepareToReadContext(workInProgress, renderExpirationTime);
      constructClassInstance(workInProgress, Component, nextProps);
      mountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
      return finishClassComponent(null, workInProgress, Component, true, hasContext, renderExpirationTime);
    }

    function mountIndeterminateComponent(_current, workInProgress, Component, renderExpirationTime) {
      if (_current !== null) {
        // An indeterminate component only mounts if it suspended inside a non-
        // concurrent tree, in an inconsistent state. We want to treat it like
        // a new mount, even though an empty version of it already committed.
        // Disconnect the alternate pointers.
        _current.alternate = null;
        workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect

        workInProgress.effectTag |= Placement;
      }

      var props = workInProgress.pendingProps;
      var context;
      {
        var unmaskedContext = getUnmaskedContext(workInProgress, Component, false);
        context = getMaskedContext(workInProgress, unmaskedContext);
      }
      prepareToReadContext(workInProgress, renderExpirationTime);
      var value;
      {
        if (Component.prototype && typeof Component.prototype.render === 'function') {
          var componentName = getComponentName(Component) || 'Unknown';

          if (!didWarnAboutBadClass[componentName]) {
            error("The <%s /> component appears to have a render method, but doesn't extend React.Component. " + 'This is likely to cause errors. Change %s to extend React.Component instead.', componentName, componentName);
            didWarnAboutBadClass[componentName] = true;
          }
        }

        if (workInProgress.mode & StrictMode) {
          ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, null);
        }

        setIsRendering(true);
        ReactCurrentOwner$1.current = workInProgress;
        value = renderWithHooks(null, workInProgress, Component, props, context, renderExpirationTime);
        setIsRendering(false);
      } // React DevTools reads this flag.

      workInProgress.effectTag |= PerformedWork;

      if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {
        {
          var _componentName = getComponentName(Component) || 'Unknown';

          if (!didWarnAboutModulePatternComponent[_componentName]) {
            error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName, _componentName, _componentName);
            didWarnAboutModulePatternComponent[_componentName] = true;
          }
        } // Proceed under the assumption that this is a class instance

        workInProgress.tag = ClassComponent; // Throw out any hooks that were used.

        workInProgress.memoizedState = null;
        workInProgress.updateQueue = null; // Push context providers early to prevent context stack mismatches.
        // During mounting we don't know the child context yet as the instance doesn't exist.
        // We will invalidate the child context in finishClassComponent() right after rendering.

        var hasContext = false;

        if (isContextProvider(Component)) {
          hasContext = true;
          pushContextProvider(workInProgress);
        } else {
          hasContext = false;
        }

        workInProgress.memoizedState = value.state !== null && value.state !== undefined ? value.state : null;
        initializeUpdateQueue(workInProgress);
        var getDerivedStateFromProps = Component.getDerivedStateFromProps;

        if (typeof getDerivedStateFromProps === 'function') {
          applyDerivedStateFromProps(workInProgress, Component, getDerivedStateFromProps, props);
        }

        adoptClassInstance(workInProgress, value);
        mountClassInstance(workInProgress, Component, props, renderExpirationTime);
        return finishClassComponent(null, workInProgress, Component, true, hasContext, renderExpirationTime);
      } else {
        // Proceed under the assumption that this is a function component
        workInProgress.tag = FunctionComponent;
        {
          if (workInProgress.mode & StrictMode) {
            // Only double-render components with Hooks
            if (workInProgress.memoizedState !== null) {
              value = renderWithHooks(null, workInProgress, Component, props, context, renderExpirationTime);
            }
          }
        }
        reconcileChildren(null, workInProgress, value, renderExpirationTime);
        {
          validateFunctionComponentInDev(workInProgress, Component);
        }
        return workInProgress.child;
      }
    }

    function validateFunctionComponentInDev(workInProgress, Component) {
      {
        if (Component) {
          if (Component.childContextTypes) {
            error('%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component');
          }
        }

        if (workInProgress.ref !== null) {
          var info = '';
          var ownerName = getCurrentFiberOwnerNameInDevOrNull();

          if (ownerName) {
            info += '\n\nCheck the render method of `' + ownerName + '`.';
          }

          var warningKey = ownerName || workInProgress._debugID || '';
          var debugSource = workInProgress._debugSource;

          if (debugSource) {
            warningKey = debugSource.fileName + ':' + debugSource.lineNumber;
          }

          if (!didWarnAboutFunctionRefs[warningKey]) {
            didWarnAboutFunctionRefs[warningKey] = true;
            error('Function components cannot be given refs. ' + 'Attempts to access this ref will fail. ' + 'Did you mean to use React.forwardRef()?%s', info);
          }
        }

        if (typeof Component.getDerivedStateFromProps === 'function') {
          var _componentName2 = getComponentName(Component) || 'Unknown';

          if (!didWarnAboutGetDerivedStateOnFunctionComponent[_componentName2]) {
            error('%s: Function components do not support getDerivedStateFromProps.', _componentName2);
            didWarnAboutGetDerivedStateOnFunctionComponent[_componentName2] = true;
          }
        }

        if (typeof Component.contextType === 'object' && Component.contextType !== null) {
          var _componentName3 = getComponentName(Component) || 'Unknown';

          if (!didWarnAboutContextTypeOnFunctionComponent[_componentName3]) {
            error('%s: Function components do not support contextType.', _componentName3);
            didWarnAboutContextTypeOnFunctionComponent[_componentName3] = true;
          }
        }
      }
    }

    var SUSPENDED_MARKER = {
      dehydrated: null,
      retryTime: NoWork
    };

    function shouldRemainOnFallback(suspenseContext, current, workInProgress) {
      // If the context is telling us that we should show a fallback, and we're not
      // already showing content, then we should show the fallback instead.
      return hasSuspenseContext(suspenseContext, ForceSuspenseFallback) && (current === null || current.memoizedState !== null);
    }

    function updateSuspenseComponent(current, workInProgress, renderExpirationTime) {
      var mode = workInProgress.mode;
      var nextProps = workInProgress.pendingProps; // This is used by DevTools to force a boundary to suspend.

      {
        if (shouldSuspend(workInProgress)) {
          workInProgress.effectTag |= DidCapture;
        }
      }
      var suspenseContext = suspenseStackCursor.current;
      var nextDidTimeout = false;
      var didSuspend = (workInProgress.effectTag & DidCapture) !== NoEffect;

      if (didSuspend || shouldRemainOnFallback(suspenseContext, current)) {
        // Something in this boundary's subtree already suspended. Switch to
        // rendering the fallback children.
        nextDidTimeout = true;
        workInProgress.effectTag &= ~DidCapture;
      } else {
        // Attempting the main content
        if (current === null || current.memoizedState !== null) {
          // This is a new mount or this boundary is already showing a fallback state.
          // Mark this subtree context as having at least one invisible parent that could
          // handle the fallback state.
          // Boundaries without fallbacks or should be avoided are not considered since
          // they cannot handle preferred fallback states.
          if (nextProps.fallback !== undefined && nextProps.unstable_avoidThisFallback !== true) {
            suspenseContext = addSubtreeSuspenseContext(suspenseContext, InvisibleParentSuspenseContext);
          }
        }
      }

      suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
      pushSuspenseContext(workInProgress, suspenseContext); // This next part is a bit confusing. If the children timeout, we switch to
      // showing the fallback children in place of the "primary" children.
      // However, we don't want to delete the primary children because then their
      // state will be lost (both the React state and the host state, e.g.
      // uncontrolled form inputs). Instead we keep them mounted and hide them.
      // Both the fallback children AND the primary children are rendered at the
      // same time. Once the primary children are un-suspended, we can delete
      // the fallback children — don't need to preserve their state.
      //
      // The two sets of children are siblings in the host environment, but
      // semantically, for purposes of reconciliation, they are two separate sets.
      // So we store them using two fragment fibers.
      //
      // However, we want to avoid allocating extra fibers for every placeholder.
      // They're only necessary when the children time out, because that's the
      // only time when both sets are mounted.
      //
      // So, the extra fragment fibers are only used if the children time out.
      // Otherwise, we render the primary children directly. This requires some
      // custom reconciliation logic to preserve the state of the primary
      // children. It's essentially a very basic form of re-parenting.

      if (current === null) {
        // If we're currently hydrating, try to hydrate this boundary.
        // But only if this has a fallback.
        if (nextProps.fallback !== undefined) {
          tryToClaimNextHydratableInstance(workInProgress); // This could've been a dehydrated suspense component.
        } // This is the initial mount. This branch is pretty simple because there's
        // no previous state that needs to be preserved.


        if (nextDidTimeout) {
          // Mount separate fragments for primary and fallback children.
          var nextFallbackChildren = nextProps.fallback;
          var primaryChildFragment = createFiberFromFragment(null, mode, NoWork, null);
          primaryChildFragment.return = workInProgress;

          if ((workInProgress.mode & BlockingMode) === NoMode) {
            // Outside of blocking mode, we commit the effects from the
            // partially completed, timed-out tree, too.
            var progressedState = workInProgress.memoizedState;
            var progressedPrimaryChild = progressedState !== null ? workInProgress.child.child : workInProgress.child;
            primaryChildFragment.child = progressedPrimaryChild;
            var progressedChild = progressedPrimaryChild;

            while (progressedChild !== null) {
              progressedChild.return = primaryChildFragment;
              progressedChild = progressedChild.sibling;
            }
          }

          var fallbackChildFragment = createFiberFromFragment(nextFallbackChildren, mode, renderExpirationTime, null);
          fallbackChildFragment.return = workInProgress;
          primaryChildFragment.sibling = fallbackChildFragment; // Skip the primary children, and continue working on the
          // fallback children.

          workInProgress.memoizedState = SUSPENDED_MARKER;
          workInProgress.child = primaryChildFragment;
          return fallbackChildFragment;
        } else {
          // Mount the primary children without an intermediate fragment fiber.
          var nextPrimaryChildren = nextProps.children;
          workInProgress.memoizedState = null;
          return workInProgress.child = mountChildFibers(workInProgress, null, nextPrimaryChildren, renderExpirationTime);
        }
      } else {
        // This is an update. This branch is more complicated because we need to
        // ensure the state of the primary children is preserved.
        var prevState = current.memoizedState;

        if (prevState !== null) {
          // wrapped in a fragment fiber.
          var currentPrimaryChildFragment = current.child;
          var currentFallbackChildFragment = currentPrimaryChildFragment.sibling;

          if (nextDidTimeout) {
            // Still timed out. Reuse the current primary children by cloning
            // its fragment. We're going to skip over these entirely.
            var _nextFallbackChildren2 = nextProps.fallback;

            var _primaryChildFragment2 = createWorkInProgress(currentPrimaryChildFragment, currentPrimaryChildFragment.pendingProps);

            _primaryChildFragment2.return = workInProgress;

            if ((workInProgress.mode & BlockingMode) === NoMode) {
              // Outside of blocking mode, we commit the effects from the
              // partially completed, timed-out tree, too.
              var _progressedState = workInProgress.memoizedState;

              var _progressedPrimaryChild = _progressedState !== null ? workInProgress.child.child : workInProgress.child;

              if (_progressedPrimaryChild !== currentPrimaryChildFragment.child) {
                _primaryChildFragment2.child = _progressedPrimaryChild;
                var _progressedChild2 = _progressedPrimaryChild;

                while (_progressedChild2 !== null) {
                  _progressedChild2.return = _primaryChildFragment2;
                  _progressedChild2 = _progressedChild2.sibling;
                }
              }
            } // Because primaryChildFragment is a new fiber that we're inserting as the
            // parent of a new tree, we need to set its treeBaseDuration.


            if (workInProgress.mode & ProfileMode) {
              // treeBaseDuration is the sum of all the child tree base durations.
              var _treeBaseDuration = 0;
              var _hiddenChild = _primaryChildFragment2.child;

              while (_hiddenChild !== null) {
                _treeBaseDuration += _hiddenChild.treeBaseDuration;
                _hiddenChild = _hiddenChild.sibling;
              }

              _primaryChildFragment2.treeBaseDuration = _treeBaseDuration;
            } // Clone the fallback child fragment, too. These we'll continue
            // working on.


            var _fallbackChildFragment2 = createWorkInProgress(currentFallbackChildFragment, _nextFallbackChildren2);

            _fallbackChildFragment2.return = workInProgress;
            _primaryChildFragment2.sibling = _fallbackChildFragment2;
            _primaryChildFragment2.childExpirationTime = NoWork; // Skip the primary children, and continue working on the
            // fallback children.

            workInProgress.memoizedState = SUSPENDED_MARKER;
            workInProgress.child = _primaryChildFragment2;
            return _fallbackChildFragment2;
          } else {
            // No longer suspended. Switch back to showing the primary children,
            // and remove the intermediate fragment fiber.
            var _nextPrimaryChildren = nextProps.children;
            var currentPrimaryChild = currentPrimaryChildFragment.child;
            var primaryChild = reconcileChildFibers(workInProgress, currentPrimaryChild, _nextPrimaryChildren, renderExpirationTime); // If this render doesn't suspend, we need to delete the fallback
            // children. Wait until the complete phase, after we've confirmed the
            // fallback is no longer needed.
            // TODO: Would it be better to store the fallback fragment on
            // the stateNode?
            // Continue rendering the children, like we normally do.

            workInProgress.memoizedState = null;
            return workInProgress.child = primaryChild;
          }
        } else {
          // The current tree has not already timed out. That means the primary
          // children are not wrapped in a fragment fiber.
          var _currentPrimaryChild = current.child;

          if (nextDidTimeout) {
            // Timed out. Wrap the children in a fragment fiber to keep them
            // separate from the fallback children.
            var _nextFallbackChildren3 = nextProps.fallback;

            var _primaryChildFragment3 = createFiberFromFragment( // It shouldn't matter what the pending props are because we aren't
            // going to render this fragment.
            null, mode, NoWork, null);

            _primaryChildFragment3.return = workInProgress;
            _primaryChildFragment3.child = _currentPrimaryChild;

            if (_currentPrimaryChild !== null) {
              _currentPrimaryChild.return = _primaryChildFragment3;
            } // Even though we're creating a new fiber, there are no new children,
            // because we're reusing an already mounted tree. So we don't need to
            // schedule a placement.
            // primaryChildFragment.effectTag |= Placement;


            if ((workInProgress.mode & BlockingMode) === NoMode) {
              // Outside of blocking mode, we commit the effects from the
              // partially completed, timed-out tree, too.
              var _progressedState2 = workInProgress.memoizedState;

              var _progressedPrimaryChild2 = _progressedState2 !== null ? workInProgress.child.child : workInProgress.child;

              _primaryChildFragment3.child = _progressedPrimaryChild2;
              var _progressedChild3 = _progressedPrimaryChild2;

              while (_progressedChild3 !== null) {
                _progressedChild3.return = _primaryChildFragment3;
                _progressedChild3 = _progressedChild3.sibling;
              }
            } // Because primaryChildFragment is a new fiber that we're inserting as the
            // parent of a new tree, we need to set its treeBaseDuration.


            if (workInProgress.mode & ProfileMode) {
              // treeBaseDuration is the sum of all the child tree base durations.
              var _treeBaseDuration2 = 0;
              var _hiddenChild2 = _primaryChildFragment3.child;

              while (_hiddenChild2 !== null) {
                _treeBaseDuration2 += _hiddenChild2.treeBaseDuration;
                _hiddenChild2 = _hiddenChild2.sibling;
              }

              _primaryChildFragment3.treeBaseDuration = _treeBaseDuration2;
            } // Create a fragment from the fallback children, too.


            var _fallbackChildFragment3 = createFiberFromFragment(_nextFallbackChildren3, mode, renderExpirationTime, null);

            _fallbackChildFragment3.return = workInProgress;
            _primaryChildFragment3.sibling = _fallbackChildFragment3;
            _fallbackChildFragment3.effectTag |= Placement;
            _primaryChildFragment3.childExpirationTime = NoWork; // Skip the primary children, and continue working on the
            // fallback children.

            workInProgress.memoizedState = SUSPENDED_MARKER;
            workInProgress.child = _primaryChildFragment3;
            return _fallbackChildFragment3;
          } else {
            // Still haven't timed out. Continue rendering the children, like we
            // normally do.
            workInProgress.memoizedState = null;
            var _nextPrimaryChildren2 = nextProps.children;
            return workInProgress.child = reconcileChildFibers(workInProgress, _currentPrimaryChild, _nextPrimaryChildren2, renderExpirationTime);
          }
        }
      }
    }

    function scheduleWorkOnFiber(fiber, renderExpirationTime) {
      if (fiber.expirationTime < renderExpirationTime) {
        fiber.expirationTime = renderExpirationTime;
      }

      var alternate = fiber.alternate;

      if (alternate !== null && alternate.expirationTime < renderExpirationTime) {
        alternate.expirationTime = renderExpirationTime;
      }

      scheduleWorkOnParentPath(fiber.return, renderExpirationTime);
    }

    function propagateSuspenseContextChange(workInProgress, firstChild, renderExpirationTime) {
      // Mark any Suspense boundaries with fallbacks as having work to do.
      // If they were previously forced into fallbacks, they may now be able
      // to unblock.
      var node = firstChild;

      while (node !== null) {
        if (node.tag === SuspenseComponent) {
          var state = node.memoizedState;

          if (state !== null) {
            scheduleWorkOnFiber(node, renderExpirationTime);
          }
        } else if (node.tag === SuspenseListComponent) {
          // If the tail is hidden there might not be an Suspense boundaries
          // to schedule work on. In this case we have to schedule it on the
          // list itself.
          // We don't have to traverse to the children of the list since
          // the list will propagate the change when it rerenders.
          scheduleWorkOnFiber(node, renderExpirationTime);
        } else if (node.child !== null) {
          node.child.return = node;
          node = node.child;
          continue;
        }

        if (node === workInProgress) {
          return;
        }

        while (node.sibling === null) {
          if (node.return === null || node.return === workInProgress) {
            return;
          }

          node = node.return;
        }

        node.sibling.return = node.return;
        node = node.sibling;
      }
    }

    function findLastContentRow(firstChild) {
      // This is going to find the last row among these children that is already
      // showing content on the screen, as opposed to being in fallback state or
      // new. If a row has multiple Suspense boundaries, any of them being in the
      // fallback state, counts as the whole row being in a fallback state.
      // Note that the "rows" will be workInProgress, but any nested children
      // will still be current since we haven't rendered them yet. The mounted
      // order may not be the same as the new order. We use the new order.
      var row = firstChild;
      var lastContentRow = null;

      while (row !== null) {
        var currentRow = row.alternate; // New rows can't be content rows.

        if (currentRow !== null && findFirstSuspended(currentRow) === null) {
          lastContentRow = row;
        }

        row = row.sibling;
      }

      return lastContentRow;
    }

    function validateRevealOrder(revealOrder) {
      {
        if (revealOrder !== undefined && revealOrder !== 'forwards' && revealOrder !== 'backwards' && revealOrder !== 'together' && !didWarnAboutRevealOrder[revealOrder]) {
          didWarnAboutRevealOrder[revealOrder] = true;

          if (typeof revealOrder === 'string') {
            switch (revealOrder.toLowerCase()) {
              case 'together':
              case 'forwards':
              case 'backwards':
                {
                  error('"%s" is not a valid value for revealOrder on <SuspenseList />. ' + 'Use lowercase "%s" instead.', revealOrder, revealOrder.toLowerCase());
                  break;
                }

              case 'forward':
              case 'backward':
                {
                  error('"%s" is not a valid value for revealOrder on <SuspenseList />. ' + 'React uses the -s suffix in the spelling. Use "%ss" instead.', revealOrder, revealOrder.toLowerCase());
                  break;
                }

              default:
                error('"%s" is not a supported revealOrder on <SuspenseList />. ' + 'Did you mean "together", "forwards" or "backwards"?', revealOrder);
                break;
            }
          } else {
            error('%s is not a supported value for revealOrder on <SuspenseList />. ' + 'Did you mean "together", "forwards" or "backwards"?', revealOrder);
          }
        }
      }
    }

    function validateTailOptions(tailMode, revealOrder) {
      {
        if (tailMode !== undefined && !didWarnAboutTailOptions[tailMode]) {
          if (tailMode !== 'collapsed' && tailMode !== 'hidden') {
            didWarnAboutTailOptions[tailMode] = true;
            error('"%s" is not a supported value for tail on <SuspenseList />. ' + 'Did you mean "collapsed" or "hidden"?', tailMode);
          } else if (revealOrder !== 'forwards' && revealOrder !== 'backwards') {
            didWarnAboutTailOptions[tailMode] = true;
            error('<SuspenseList tail="%s" /> is only valid if revealOrder is ' + '"forwards" or "backwards". ' + 'Did you mean to specify revealOrder="forwards"?', tailMode);
          }
        }
      }
    }

    function validateSuspenseListNestedChild(childSlot, index) {
      {
        var isArray = Array.isArray(childSlot);
        var isIterable = !isArray && typeof getIteratorFn(childSlot) === 'function';

        if (isArray || isIterable) {
          var type = isArray ? 'array' : 'iterable';
          error('A nested %s was passed to row #%s in <SuspenseList />. Wrap it in ' + 'an additional SuspenseList to configure its revealOrder: ' + '<SuspenseList revealOrder=...> ... ' + '<SuspenseList revealOrder=...>{%s}</SuspenseList> ... ' + '</SuspenseList>', type, index, type);
          return false;
        }
      }
      return true;
    }

    function validateSuspenseListChildren(children, revealOrder) {
      {
        if ((revealOrder === 'forwards' || revealOrder === 'backwards') && children !== undefined && children !== null && children !== false) {
          if (Array.isArray(children)) {
            for (var i = 0; i < children.length; i++) {
              if (!validateSuspenseListNestedChild(children[i], i)) {
                return;
              }
            }
          } else {
            var iteratorFn = getIteratorFn(children);

            if (typeof iteratorFn === 'function') {
              var childrenIterator = iteratorFn.call(children);

              if (childrenIterator) {
                var step = childrenIterator.next();
                var _i = 0;

                for (; !step.done; step = childrenIterator.next()) {
                  if (!validateSuspenseListNestedChild(step.value, _i)) {
                    return;
                  }

                  _i++;
                }
              }
            } else {
              error('A single row was passed to a <SuspenseList revealOrder="%s" />. ' + 'This is not useful since it needs multiple rows. ' + 'Did you mean to pass multiple children or an array?', revealOrder);
            }
          }
        }
      }
    }

    function initSuspenseListRenderState(workInProgress, isBackwards, tail, lastContentRow, tailMode, lastEffectBeforeRendering) {
      var renderState = workInProgress.memoizedState;

      if (renderState === null) {
        workInProgress.memoizedState = {
          isBackwards: isBackwards,
          rendering: null,
          renderingStartTime: 0,
          last: lastContentRow,
          tail: tail,
          tailExpiration: 0,
          tailMode: tailMode,
          lastEffect: lastEffectBeforeRendering
        };
      } else {
        // We can reuse the existing object from previous renders.
        renderState.isBackwards = isBackwards;
        renderState.rendering = null;
        renderState.renderingStartTime = 0;
        renderState.last = lastContentRow;
        renderState.tail = tail;
        renderState.tailExpiration = 0;
        renderState.tailMode = tailMode;
        renderState.lastEffect = lastEffectBeforeRendering;
      }
    } // This can end up rendering this component multiple passes.
    // The first pass splits the children fibers into two sets. A head and tail.
    // We first render the head. If anything is in fallback state, we do another
    // pass through beginWork to rerender all children (including the tail) with
    // the force suspend context. If the first render didn't have anything in
    // in fallback state. Then we render each row in the tail one-by-one.
    // That happens in the completeWork phase without going back to beginWork.


    function updateSuspenseListComponent(current, workInProgress, renderExpirationTime) {
      var nextProps = workInProgress.pendingProps;
      var revealOrder = nextProps.revealOrder;
      var tailMode = nextProps.tail;
      var newChildren = nextProps.children;
      validateRevealOrder(revealOrder);
      validateTailOptions(tailMode, revealOrder);
      validateSuspenseListChildren(newChildren, revealOrder);
      reconcileChildren(current, workInProgress, newChildren, renderExpirationTime);
      var suspenseContext = suspenseStackCursor.current;
      var shouldForceFallback = hasSuspenseContext(suspenseContext, ForceSuspenseFallback);

      if (shouldForceFallback) {
        suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback);
        workInProgress.effectTag |= DidCapture;
      } else {
        var didSuspendBefore = current !== null && (current.effectTag & DidCapture) !== NoEffect;

        if (didSuspendBefore) {
          // If we previously forced a fallback, we need to schedule work
          // on any nested boundaries to let them know to try to render
          // again. This is the same as context updating.
          propagateSuspenseContextChange(workInProgress, workInProgress.child, renderExpirationTime);
        }

        suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
      }

      pushSuspenseContext(workInProgress, suspenseContext);

      if ((workInProgress.mode & BlockingMode) === NoMode) {
        // Outside of blocking mode, SuspenseList doesn't work so we just
        // use make it a noop by treating it as the default revealOrder.
        workInProgress.memoizedState = null;
      } else {
        switch (revealOrder) {
          case 'forwards':
            {
              var lastContentRow = findLastContentRow(workInProgress.child);
              var tail;

              if (lastContentRow === null) {
                // The whole list is part of the tail.
                // TODO: We could fast path by just rendering the tail now.
                tail = workInProgress.child;
                workInProgress.child = null;
              } else {
                // Disconnect the tail rows after the content row.
                // We're going to render them separately later.
                tail = lastContentRow.sibling;
                lastContentRow.sibling = null;
              }

              initSuspenseListRenderState(workInProgress, false, // isBackwards
              tail, lastContentRow, tailMode, workInProgress.lastEffect);
              break;
            }

          case 'backwards':
            {
              // We're going to find the first row that has existing content.
              // At the same time we're going to reverse the list of everything
              // we pass in the meantime. That's going to be our tail in reverse
              // order.
              var _tail = null;
              var row = workInProgress.child;
              workInProgress.child = null;

              while (row !== null) {
                var currentRow = row.alternate; // New rows can't be content rows.

                if (currentRow !== null && findFirstSuspended(currentRow) === null) {
                  // This is the beginning of the main content.
                  workInProgress.child = row;
                  break;
                }

                var nextRow = row.sibling;
                row.sibling = _tail;
                _tail = row;
                row = nextRow;
              } // TODO: If workInProgress.child is null, we can continue on the tail immediately.


              initSuspenseListRenderState(workInProgress, true, // isBackwards
              _tail, null, // last
              tailMode, workInProgress.lastEffect);
              break;
            }

          case 'together':
            {
              initSuspenseListRenderState(workInProgress, false, // isBackwards
              null, // tail
              null, // last
              undefined, workInProgress.lastEffect);
              break;
            }

          default:
            {
              // The default reveal order is the same as not having
              // a boundary.
              workInProgress.memoizedState = null;
            }
        }
      }

      return workInProgress.child;
    }

    function updatePortalComponent(current, workInProgress, renderExpirationTime) {
      pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
      var nextChildren = workInProgress.pendingProps;

      if (current === null) {
        // Portals are special because we don't append the children during mount
        // but at commit. Therefore we need to track insertions which the normal
        // flow doesn't do during mount. This doesn't happen at the root because
        // the root always starts with a "current" with a null child.
        // TODO: Consider unifying this with how the root works.
        workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
      } else {
        reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);
      }

      return workInProgress.child;
    }

    function updateContextProvider(current, workInProgress, renderExpirationTime) {
      var providerType = workInProgress.type;
      var context = providerType._context;
      var newProps = workInProgress.pendingProps;
      var oldProps = workInProgress.memoizedProps;
      var newValue = newProps.value;
      {
        var providerPropTypes = workInProgress.type.propTypes;

        if (providerPropTypes) {
          checkPropTypes(providerPropTypes, newProps, 'prop', 'Context.Provider', getCurrentFiberStackInDev);
        }
      }
      pushProvider(workInProgress, newValue);

      if (oldProps !== null) {
        var oldValue = oldProps.value;
        var changedBits = calculateChangedBits(context, newValue, oldValue);

        if (changedBits === 0) {
          // No change. Bailout early if children are the same.
          if (oldProps.children === newProps.children && !hasContextChanged()) {
            return bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);
          }
        } else {
          // The context value changed. Search for matching consumers and schedule
          // them to update.
          propagateContextChange(workInProgress, context, changedBits, renderExpirationTime);
        }
      }

      var newChildren = newProps.children;
      reconcileChildren(current, workInProgress, newChildren, renderExpirationTime);
      return workInProgress.child;
    }

    var hasWarnedAboutUsingContextAsConsumer = false;

    function updateContextConsumer(current, workInProgress, renderExpirationTime) {
      var context = workInProgress.type; // The logic below for Context differs depending on PROD or DEV mode. In
      // DEV mode, we create a separate object for Context.Consumer that acts
      // like a proxy to Context. This proxy object adds unnecessary code in PROD
      // so we use the old behaviour (Context.Consumer references Context) to
      // reduce size and overhead. The separate object references context via
      // a property called "_context", which also gives us the ability to check
      // in DEV mode if this property exists or not and warn if it does not.

      {
        if (context._context === undefined) {
          // This may be because it's a Context (rather than a Consumer).
          // Or it may be because it's older React where they're the same thing.
          // We only want to warn if we're sure it's a new React.
          if (context !== context.Consumer) {
            if (!hasWarnedAboutUsingContextAsConsumer) {
              hasWarnedAboutUsingContextAsConsumer = true;
              error('Rendering <Context> directly is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?');
            }
          }
        } else {
          context = context._context;
        }
      }
      var newProps = workInProgress.pendingProps;
      var render = newProps.children;
      {
        if (typeof render !== 'function') {
          error('A context consumer was rendered with multiple children, or a child ' + "that isn't a function. A context consumer expects a single child " + 'that is a function. If you did pass a function, make sure there ' + 'is no trailing or leading whitespace around it.');
        }
      }
      prepareToReadContext(workInProgress, renderExpirationTime);
      var newValue = readContext(context, newProps.unstable_observedBits);
      var newChildren;
      {
        ReactCurrentOwner$1.current = workInProgress;
        setIsRendering(true);
        newChildren = render(newValue);
        setIsRendering(false);
      } // React DevTools reads this flag.

      workInProgress.effectTag |= PerformedWork;
      reconcileChildren(current, workInProgress, newChildren, renderExpirationTime);
      return workInProgress.child;
    }

    function markWorkInProgressReceivedUpdate() {
      didReceiveUpdate = true;
    }

    function bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime) {
      cancelWorkTimer(workInProgress);

      if (current !== null) {
        // Reuse previous dependencies
        workInProgress.dependencies = current.dependencies;
      }

      {
        // Don't update "base" render times for bailouts.
        stopProfilerTimerIfRunning();
      }
      var updateExpirationTime = workInProgress.expirationTime;

      if (updateExpirationTime !== NoWork) {
        markUnprocessedUpdateTime(updateExpirationTime);
      } // Check if the children have any pending work.


      var childExpirationTime = workInProgress.childExpirationTime;

      if (childExpirationTime < renderExpirationTime) {
        // The children don't have any work either. We can skip them.
        // TODO: Once we add back resuming, we should check if the children are
        // a work-in-progress set. If so, we need to transfer their effects.
        return null;
      } else {
        // This fiber doesn't have work, but its subtree does. Clone the child
        // fibers and continue.
        cloneChildFibers(current, workInProgress);
        return workInProgress.child;
      }
    }

    function remountFiber(current, oldWorkInProgress, newWorkInProgress) {
      {
        var returnFiber = oldWorkInProgress.return;

        if (returnFiber === null) {
          throw new Error('Cannot swap the root fiber.');
        } // Disconnect from the old current.
        // It will get deleted.


        current.alternate = null;
        oldWorkInProgress.alternate = null; // Connect to the new tree.

        newWorkInProgress.index = oldWorkInProgress.index;
        newWorkInProgress.sibling = oldWorkInProgress.sibling;
        newWorkInProgress.return = oldWorkInProgress.return;
        newWorkInProgress.ref = oldWorkInProgress.ref; // Replace the child/sibling pointers above it.

        if (oldWorkInProgress === returnFiber.child) {
          returnFiber.child = newWorkInProgress;
        } else {
          var prevSibling = returnFiber.child;

          if (prevSibling === null) {
            throw new Error('Expected parent to have a child.');
          }

          while (prevSibling.sibling !== oldWorkInProgress) {
            prevSibling = prevSibling.sibling;

            if (prevSibling === null) {
              throw new Error('Expected to find the previous sibling.');
            }
          }

          prevSibling.sibling = newWorkInProgress;
        } // Delete the old fiber and place the new one.
        // Since the old fiber is disconnected, we have to schedule it manually.


        var last = returnFiber.lastEffect;

        if (last !== null) {
          last.nextEffect = current;
          returnFiber.lastEffect = current;
        } else {
          returnFiber.firstEffect = returnFiber.lastEffect = current;
        }

        current.nextEffect = null;
        current.effectTag = Deletion;
        newWorkInProgress.effectTag |= Placement; // Restart work from the new fiber.

        return newWorkInProgress;
      }
    }

    function beginWork(current, workInProgress, renderExpirationTime) {
      var updateExpirationTime = workInProgress.expirationTime;
      {
        if (workInProgress._debugNeedsRemount && current !== null) {
          // This will restart the begin phase with a new fiber.
          return remountFiber(current, workInProgress, createFiberFromTypeAndProps(workInProgress.type, workInProgress.key, workInProgress.pendingProps, workInProgress._debugOwner || null, workInProgress.mode, workInProgress.expirationTime));
        }
      }

      if (current !== null) {
        var oldProps = current.memoizedProps;
        var newProps = workInProgress.pendingProps;

        if (oldProps !== newProps || hasContextChanged() || // Force a re-render if the implementation changed due to hot reload:
        workInProgress.type !== current.type) {
          // If props or context changed, mark the fiber as having performed work.
          // This may be unset if the props are determined to be equal later (memo).
          didReceiveUpdate = true;
        } else if (updateExpirationTime < renderExpirationTime) {
          didReceiveUpdate = false; // This fiber does not have any pending work. Bailout without entering
          // the begin phase. There's still some bookkeeping we that needs to be done
          // in this optimized path, mostly pushing stuff onto the stack.

          switch (workInProgress.tag) {
            case HostRoot:
              pushHostRootContext(workInProgress);
              resetHydrationState();
              break;

            case HostComponent:
              pushHostContext(workInProgress);

              if (workInProgress.mode & ConcurrentMode && renderExpirationTime !== Never && shouldDeprioritizeSubtree(workInProgress.type, newProps)) {
                {
                  markSpawnedWork(Never);
                } // Schedule this fiber to re-render at offscreen priority. Then bailout.

                workInProgress.expirationTime = workInProgress.childExpirationTime = Never;
                return null;
              }

              break;

            case ClassComponent:
              {
                var Component = workInProgress.type;

                if (isContextProvider(Component)) {
                  pushContextProvider(workInProgress);
                }

                break;
              }

            case HostPortal:
              pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
              break;

            case ContextProvider:
              {
                var newValue = workInProgress.memoizedProps.value;
                pushProvider(workInProgress, newValue);
                break;
              }

            case Profiler:
              {
                // Profiler should only call onRender when one of its descendants actually rendered.
                var hasChildWork = workInProgress.childExpirationTime >= renderExpirationTime;

                if (hasChildWork) {
                  workInProgress.effectTag |= Update;
                }
              }
              break;

            case SuspenseComponent:
              {
                var state = workInProgress.memoizedState;

                if (state !== null) {
                  // whether to retry the primary children, or to skip over it and
                  // go straight to the fallback. Check the priority of the primary
                  // child fragment.
                  var primaryChildFragment = workInProgress.child;
                  var primaryChildExpirationTime = primaryChildFragment.childExpirationTime;

                  if (primaryChildExpirationTime !== NoWork && primaryChildExpirationTime >= renderExpirationTime) {
                    // The primary children have pending work. Use the normal path
                    // to attempt to render the primary children again.
                    return updateSuspenseComponent(current, workInProgress, renderExpirationTime);
                  } else {
                    pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); // The primary children do not have pending work with sufficient
                    // priority. Bailout.

                    var child = bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);

                    if (child !== null) {
                      // The fallback children have pending work. Skip over the
                      // primary children and work on the fallback.
                      return child.sibling;
                    } else {
                      return null;
                    }
                  }
                } else {
                  pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current));
                }

                break;
              }

            case SuspenseListComponent:
              {
                var didSuspendBefore = (current.effectTag & DidCapture) !== NoEffect;

                var _hasChildWork = workInProgress.childExpirationTime >= renderExpirationTime;

                if (didSuspendBefore) {
                  if (_hasChildWork) {
                    // If something was in fallback state last time, and we have all the
                    // same children then we're still in progressive loading state.
                    // Something might get unblocked by state updates or retries in the
                    // tree which will affect the tail. So we need to use the normal
                    // path to compute the correct tail.
                    return updateSuspenseListComponent(current, workInProgress, renderExpirationTime);
                  } // If none of the children had any work, that means that none of
                  // them got retried so they'll still be blocked in the same way
                  // as before. We can fast bail out.


                  workInProgress.effectTag |= DidCapture;
                } // If nothing suspended before and we're rendering the same children,
                // then the tail doesn't matter. Anything new that suspends will work
                // in the "together" mode, so we can continue from the state we had.


                var renderState = workInProgress.memoizedState;

                if (renderState !== null) {
                  // Reset to the "together" mode in case we've started a different
                  // update in the past but didn't complete it.
                  renderState.rendering = null;
                  renderState.tail = null;
                }

                pushSuspenseContext(workInProgress, suspenseStackCursor.current);

                if (_hasChildWork) {
                  break;
                } else {
                  // If none of the children had any work, that means that none of
                  // them got retried so they'll still be blocked in the same way
                  // as before. We can fast bail out.
                  return null;
                }
              }
          }

          return bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);
        } else {
          // An update was scheduled on this fiber, but there are no new props
          // nor legacy context. Set this to false. If an update queue or context
          // consumer produces a changed value, it will set this to true. Otherwise,
          // the component will assume the children have not changed and bail out.
          didReceiveUpdate = false;
        }
      } else {
        didReceiveUpdate = false;
      } // Before entering the begin phase, clear pending update priority.
      // TODO: This assumes that we're about to evaluate the component and process
      // the update queue. However, there's an exception: SimpleMemoComponent
      // sometimes bails out later in the begin phase. This indicates that we should
      // move this assignment out of the common path and into each branch.


      workInProgress.expirationTime = NoWork;

      switch (workInProgress.tag) {
        case IndeterminateComponent:
          {
            return mountIndeterminateComponent(current, workInProgress, workInProgress.type, renderExpirationTime);
          }

        case LazyComponent:
          {
            var elementType = workInProgress.elementType;
            return mountLazyComponent(current, workInProgress, elementType, updateExpirationTime, renderExpirationTime);
          }

        case FunctionComponent:
          {
            var _Component = workInProgress.type;
            var unresolvedProps = workInProgress.pendingProps;
            var resolvedProps = workInProgress.elementType === _Component ? unresolvedProps : resolveDefaultProps(_Component, unresolvedProps);
            return updateFunctionComponent(current, workInProgress, _Component, resolvedProps, renderExpirationTime);
          }

        case ClassComponent:
          {
            var _Component2 = workInProgress.type;
            var _unresolvedProps = workInProgress.pendingProps;

            var _resolvedProps = workInProgress.elementType === _Component2 ? _unresolvedProps : resolveDefaultProps(_Component2, _unresolvedProps);

            return updateClassComponent(current, workInProgress, _Component2, _resolvedProps, renderExpirationTime);
          }

        case HostRoot:
          return updateHostRoot(current, workInProgress, renderExpirationTime);

        case HostComponent:
          return updateHostComponent(current, workInProgress, renderExpirationTime);

        case HostText:
          return updateHostText(current, workInProgress);

        case SuspenseComponent:
          return updateSuspenseComponent(current, workInProgress, renderExpirationTime);

        case HostPortal:
          return updatePortalComponent(current, workInProgress, renderExpirationTime);

        case ForwardRef:
          {
            var type = workInProgress.type;
            var _unresolvedProps2 = workInProgress.pendingProps;

            var _resolvedProps2 = workInProgress.elementType === type ? _unresolvedProps2 : resolveDefaultProps(type, _unresolvedProps2);

            return updateForwardRef(current, workInProgress, type, _resolvedProps2, renderExpirationTime);
          }

        case Fragment:
          return updateFragment(current, workInProgress, renderExpirationTime);

        case Mode:
          return updateMode(current, workInProgress, renderExpirationTime);

        case Profiler:
          return updateProfiler(current, workInProgress, renderExpirationTime);

        case ContextProvider:
          return updateContextProvider(current, workInProgress, renderExpirationTime);

        case ContextConsumer:
          return updateContextConsumer(current, workInProgress, renderExpirationTime);

        case MemoComponent:
          {
            var _type2 = workInProgress.type;
            var _unresolvedProps3 = workInProgress.pendingProps; // Resolve outer props first, then resolve inner props.

            var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3);

            {
              if (workInProgress.type !== workInProgress.elementType) {
                var outerPropTypes = _type2.propTypes;

                if (outerPropTypes) {
                  checkPropTypes(outerPropTypes, _resolvedProps3, // Resolved for outer only
                  'prop', getComponentName(_type2), getCurrentFiberStackInDev);
                }
              }
            }
            _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3);
            return updateMemoComponent(current, workInProgress, _type2, _resolvedProps3, updateExpirationTime, renderExpirationTime);
          }

        case SimpleMemoComponent:
          {
            return updateSimpleMemoComponent(current, workInProgress, workInProgress.type, workInProgress.pendingProps, updateExpirationTime, renderExpirationTime);
          }

        case IncompleteClassComponent:
          {
            var _Component3 = workInProgress.type;
            var _unresolvedProps4 = workInProgress.pendingProps;

            var _resolvedProps4 = workInProgress.elementType === _Component3 ? _unresolvedProps4 : resolveDefaultProps(_Component3, _unresolvedProps4);

            return mountIncompleteClassComponent(current, workInProgress, _Component3, _resolvedProps4, renderExpirationTime);
          }

        case SuspenseListComponent:
          {
            return updateSuspenseListComponent(current, workInProgress, renderExpirationTime);
          }
      }

      {
        {
          throw Error("Unknown unit of work tag (" + workInProgress.tag + "). This error is likely caused by a bug in React. Please file an issue.");
        }
      }
    }

    function markUpdate(workInProgress) {
      // Tag the fiber with an update effect. This turns a Placement into
      // a PlacementAndUpdate.
      workInProgress.effectTag |= Update;
    }

    function markRef$1(workInProgress) {
      workInProgress.effectTag |= Ref;
    }

    var appendAllChildren;
    var updateHostContainer;
    var updateHostComponent$1;
    var updateHostText$1;
    {
      // Mutation mode
      appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) {
        // We only have the top Fiber that was created but we need recurse down its
        // children to find all the terminal nodes.
        var node = workInProgress.child;

        while (node !== null) {
          if (node.tag === HostComponent || node.tag === HostText) {
            appendInitialChild(parent, node.stateNode);
          } else if (node.tag === HostPortal) ;else if (node.child !== null) {
            node.child.return = node;
            node = node.child;
            continue;
          }

          if (node === workInProgress) {
            return;
          }

          while (node.sibling === null) {
            if (node.return === null || node.return === workInProgress) {
              return;
            }

            node = node.return;
          }

          node.sibling.return = node.return;
          node = node.sibling;
        }
      };

      updateHostContainer = function (workInProgress) {// Noop
      };

      updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
        // If we have an alternate, that means this is an update and we need to
        // schedule a side-effect to do the updates.
        var oldProps = current.memoizedProps;

        if (oldProps === newProps) {
          // In mutation mode, this is sufficient for a bailout because
          // we won't touch this node even if children changed.
          return;
        } // If we get updated because one of our children updated, we don't
        // have newProps so we'll have to reuse them.
        // TODO: Split the update API as separate for the props vs. children.
        // Even better would be if children weren't special cased at all tho.


        var instance = workInProgress.stateNode;
        var currentHostContext = getHostContext(); // TODO: Experiencing an error where oldProps is null. Suggests a host
        // component is hitting the resume path. Figure out why. Possibly
        // related to `hidden`.

        var updatePayload = prepareUpdate(instance, type, oldProps, newProps, rootContainerInstance, currentHostContext); // TODO: Type this specific to this type of component.

        workInProgress.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there
        // is a new ref we mark this as an update. All the work is done in commitWork.

        if (updatePayload) {
          markUpdate(workInProgress);
        }
      };

      updateHostText$1 = function (current, workInProgress, oldText, newText) {
        // If the text differs, mark it as an update. All the work in done in commitWork.
        if (oldText !== newText) {
          markUpdate(workInProgress);
        }
      };
    }

    function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) {
      switch (renderState.tailMode) {
        case 'hidden':
          {
            // Any insertions at the end of the tail list after this point
            // should be invisible. If there are already mounted boundaries
            // anything before them are not considered for collapsing.
            // Therefore we need to go through the whole tail to find if
            // there are any.
            var tailNode = renderState.tail;
            var lastTailNode = null;

            while (tailNode !== null) {
              if (tailNode.alternate !== null) {
                lastTailNode = tailNode;
              }

              tailNode = tailNode.sibling;
            } // Next we're simply going to delete all insertions after the
            // last rendered item.


            if (lastTailNode === null) {
              // All remaining items in the tail are insertions.
              renderState.tail = null;
            } else {
              // Detach the insertion after the last node that was already
              // inserted.
              lastTailNode.sibling = null;
            }

            break;
          }

        case 'collapsed':
          {
            // Any insertions at the end of the tail list after this point
            // should be invisible. If there are already mounted boundaries
            // anything before them are not considered for collapsing.
            // Therefore we need to go through the whole tail to find if
            // there are any.
            var _tailNode = renderState.tail;
            var _lastTailNode = null;

            while (_tailNode !== null) {
              if (_tailNode.alternate !== null) {
                _lastTailNode = _tailNode;
              }

              _tailNode = _tailNode.sibling;
            } // Next we're simply going to delete all insertions after the
            // last rendered item.


            if (_lastTailNode === null) {
              // All remaining items in the tail are insertions.
              if (!hasRenderedATailFallback && renderState.tail !== null) {
                // We suspended during the head. We want to show at least one
                // row at the tail. So we'll keep on and cut off the rest.
                renderState.tail.sibling = null;
              } else {
                renderState.tail = null;
              }
            } else {
              // Detach the insertion after the last node that was already
              // inserted.
              _lastTailNode.sibling = null;
            }

            break;
          }
      }
    }

    function completeWork(current, workInProgress, renderExpirationTime) {
      var newProps = workInProgress.pendingProps;

      switch (workInProgress.tag) {
        case IndeterminateComponent:
        case LazyComponent:
        case SimpleMemoComponent:
        case FunctionComponent:
        case ForwardRef:
        case Fragment:
        case Mode:
        case Profiler:
        case ContextConsumer:
        case MemoComponent:
          return null;

        case ClassComponent:
          {
            var Component = workInProgress.type;

            if (isContextProvider(Component)) {
              popContext(workInProgress);
            }

            return null;
          }

        case HostRoot:
          {
            popHostContainer(workInProgress);
            popTopLevelContextObject(workInProgress);
            var fiberRoot = workInProgress.stateNode;

            if (fiberRoot.pendingContext) {
              fiberRoot.context = fiberRoot.pendingContext;
              fiberRoot.pendingContext = null;
            }

            if (current === null || current.child === null) {
              // If we hydrated, pop so that we can delete any remaining children
              // that weren't hydrated.
              var wasHydrated = popHydrationState(workInProgress);

              if (wasHydrated) {
                // If we hydrated, then we'll need to schedule an update for
                // the commit side-effects on the root.
                markUpdate(workInProgress);
              }
            }

            updateHostContainer(workInProgress);
            return null;
          }

        case HostComponent:
          {
            popHostContext(workInProgress);
            var rootContainerInstance = getRootHostContainer();
            var type = workInProgress.type;

            if (current !== null && workInProgress.stateNode != null) {
              updateHostComponent$1(current, workInProgress, type, newProps, rootContainerInstance);

              if (current.ref !== workInProgress.ref) {
                markRef$1(workInProgress);
              }
            } else {
              if (!newProps) {
                if (!(workInProgress.stateNode !== null)) {
                  {
                    throw Error("We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue.");
                  }
                } // This can happen when we abort work.


                return null;
              }

              var currentHostContext = getHostContext(); // TODO: Move createInstance to beginWork and keep it on a context
              // "stack" as the parent. Then append children as we go in beginWork
              // or completeWork depending on whether we want to add them top->down or
              // bottom->up. Top->down is faster in IE11.

              var _wasHydrated = popHydrationState(workInProgress);

              if (_wasHydrated) {
                // TODO: Move this and createInstance step into the beginPhase
                // to consolidate.
                if (prepareToHydrateHostInstance(workInProgress, rootContainerInstance, currentHostContext)) {
                  // If changes to the hydrated node need to be applied at the
                  // commit-phase we mark this as such.
                  markUpdate(workInProgress);
                }
              } else {
                var instance = createInstance(type, newProps, rootContainerInstance, currentHostContext, workInProgress);
                appendAllChildren(instance, workInProgress, false, false); // This needs to be set before we mount Flare event listeners

                workInProgress.stateNode = instance; // (eg DOM renderer supports auto-focus for certain elements).
                // Make sure such renderers get scheduled for later work.

                if (finalizeInitialChildren(instance, type, newProps, rootContainerInstance)) {
                  markUpdate(workInProgress);
                }
              }

              if (workInProgress.ref !== null) {
                // If there is a ref on a host node we need to schedule a callback
                markRef$1(workInProgress);
              }
            }

            return null;
          }

        case HostText:
          {
            var newText = newProps;

            if (current && workInProgress.stateNode != null) {
              var oldText = current.memoizedProps; // If we have an alternate, that means this is an update and we need
              // to schedule a side-effect to do the updates.

              updateHostText$1(current, workInProgress, oldText, newText);
            } else {
              if (typeof newText !== 'string') {
                if (!(workInProgress.stateNode !== null)) {
                  {
                    throw Error("We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue.");
                  }
                } // This can happen when we abort work.

              }

              var _rootContainerInstance = getRootHostContainer();

              var _currentHostContext = getHostContext();

              var _wasHydrated2 = popHydrationState(workInProgress);

              if (_wasHydrated2) {
                if (prepareToHydrateHostTextInstance(workInProgress)) {
                  markUpdate(workInProgress);
                }
              } else {
                workInProgress.stateNode = createTextInstance(newText, _rootContainerInstance, _currentHostContext, workInProgress);
              }
            }

            return null;
          }

        case SuspenseComponent:
          {
            popSuspenseContext(workInProgress);
            var nextState = workInProgress.memoizedState;

            if ((workInProgress.effectTag & DidCapture) !== NoEffect) {
              // Something suspended. Re-render with the fallback children.
              workInProgress.expirationTime = renderExpirationTime; // Do not reset the effect list.

              return workInProgress;
            }

            var nextDidTimeout = nextState !== null;
            var prevDidTimeout = false;

            if (current === null) {
              if (workInProgress.memoizedProps.fallback !== undefined) {
                popHydrationState(workInProgress);
              }
            } else {
              var prevState = current.memoizedState;
              prevDidTimeout = prevState !== null;

              if (!nextDidTimeout && prevState !== null) {
                // We just switched from the fallback to the normal children.
                // Delete the fallback.
                // TODO: Would it be better to store the fallback fragment on
                // the stateNode during the begin phase?
                var currentFallbackChild = current.child.sibling;

                if (currentFallbackChild !== null) {
                  // Deletions go at the beginning of the return fiber's effect list
                  var first = workInProgress.firstEffect;

                  if (first !== null) {
                    workInProgress.firstEffect = currentFallbackChild;
                    currentFallbackChild.nextEffect = first;
                  } else {
                    workInProgress.firstEffect = workInProgress.lastEffect = currentFallbackChild;
                    currentFallbackChild.nextEffect = null;
                  }

                  currentFallbackChild.effectTag = Deletion;
                }
              }
            }

            if (nextDidTimeout && !prevDidTimeout) {
              // If this subtreee is running in blocking mode we can suspend,
              // otherwise we won't suspend.
              // TODO: This will still suspend a synchronous tree if anything
              // in the concurrent tree already suspended during this render.
              // This is a known bug.
              if ((workInProgress.mode & BlockingMode) !== NoMode) {
                // TODO: Move this back to throwException because this is too late
                // if this is a large tree which is common for initial loads. We
                // don't know if we should restart a render or not until we get
                // this marker, and this is too late.
                // If this render already had a ping or lower pri updates,
                // and this is the first time we know we're going to suspend we
                // should be able to immediately restart from within throwException.
                var hasInvisibleChildContext = current === null && workInProgress.memoizedProps.unstable_avoidThisFallback !== true;

                if (hasInvisibleChildContext || hasSuspenseContext(suspenseStackCursor.current, InvisibleParentSuspenseContext)) {
                  // If this was in an invisible tree or a new render, then showing
                  // this boundary is ok.
                  renderDidSuspend();
                } else {
                  // Otherwise, we're going to have to hide content so we should
                  // suspend for longer if possible.
                  renderDidSuspendDelayIfPossible();
                }
              }
            }

            {
              // TODO: Only schedule updates if these values are non equal, i.e. it changed.
              if (nextDidTimeout || prevDidTimeout) {
                // If this boundary just timed out, schedule an effect to attach a
                // retry listener to the promise. This flag is also used to hide the
                // primary children. In mutation mode, we also need the flag to
                // *unhide* children that were previously hidden, so check if this
                // is currently timed out, too.
                workInProgress.effectTag |= Update;
              }
            }
            return null;
          }

        case HostPortal:
          popHostContainer(workInProgress);
          updateHostContainer(workInProgress);
          return null;

        case ContextProvider:
          // Pop provider fiber
          popProvider(workInProgress);
          return null;

        case IncompleteClassComponent:
          {
            // Same as class component case. I put it down here so that the tags are
            // sequential to ensure this switch is compiled to a jump table.
            var _Component = workInProgress.type;

            if (isContextProvider(_Component)) {
              popContext(workInProgress);
            }

            return null;
          }

        case SuspenseListComponent:
          {
            popSuspenseContext(workInProgress);
            var renderState = workInProgress.memoizedState;

            if (renderState === null) {
              // We're running in the default, "independent" mode.
              // We don't do anything in this mode.
              return null;
            }

            var didSuspendAlready = (workInProgress.effectTag & DidCapture) !== NoEffect;
            var renderedTail = renderState.rendering;

            if (renderedTail === null) {
              // We just rendered the head.
              if (!didSuspendAlready) {
                // This is the first pass. We need to figure out if anything is still
                // suspended in the rendered set.
                // If new content unsuspended, but there's still some content that
                // didn't. Then we need to do a second pass that forces everything
                // to keep showing their fallbacks.
                // We might be suspended if something in this render pass suspended, or
                // something in the previous committed pass suspended. Otherwise,
                // there's no chance so we can skip the expensive call to
                // findFirstSuspended.
                var cannotBeSuspended = renderHasNotSuspendedYet() && (current === null || (current.effectTag & DidCapture) === NoEffect);

                if (!cannotBeSuspended) {
                  var row = workInProgress.child;

                  while (row !== null) {
                    var suspended = findFirstSuspended(row);

                    if (suspended !== null) {
                      didSuspendAlready = true;
                      workInProgress.effectTag |= DidCapture;
                      cutOffTailIfNeeded(renderState, false); // If this is a newly suspended tree, it might not get committed as
                      // part of the second pass. In that case nothing will subscribe to
                      // its thennables. Instead, we'll transfer its thennables to the
                      // SuspenseList so that it can retry if they resolve.
                      // There might be multiple of these in the list but since we're
                      // going to wait for all of them anyway, it doesn't really matter
                      // which ones gets to ping. In theory we could get clever and keep
                      // track of how many dependencies remain but it gets tricky because
                      // in the meantime, we can add/remove/change items and dependencies.
                      // We might bail out of the loop before finding any but that
                      // doesn't matter since that means that the other boundaries that
                      // we did find already has their listeners attached.

                      var newThennables = suspended.updateQueue;

                      if (newThennables !== null) {
                        workInProgress.updateQueue = newThennables;
                        workInProgress.effectTag |= Update;
                      } // Rerender the whole list, but this time, we'll force fallbacks
                      // to stay in place.
                      // Reset the effect list before doing the second pass since that's now invalid.


                      if (renderState.lastEffect === null) {
                        workInProgress.firstEffect = null;
                      }

                      workInProgress.lastEffect = renderState.lastEffect; // Reset the child fibers to their original state.

                      resetChildFibers(workInProgress, renderExpirationTime); // Set up the Suspense Context to force suspense and immediately
                      // rerender the children.

                      pushSuspenseContext(workInProgress, setShallowSuspenseContext(suspenseStackCursor.current, ForceSuspenseFallback));
                      return workInProgress.child;
                    }

                    row = row.sibling;
                  }
                }
              } else {
                cutOffTailIfNeeded(renderState, false);
              } // Next we're going to render the tail.

            } else {
              // Append the rendered row to the child list.
              if (!didSuspendAlready) {
                var _suspended = findFirstSuspended(renderedTail);

                if (_suspended !== null) {
                  workInProgress.effectTag |= DidCapture;
                  didSuspendAlready = true; // Ensure we transfer the update queue to the parent so that it doesn't
                  // get lost if this row ends up dropped during a second pass.

                  var _newThennables = _suspended.updateQueue;

                  if (_newThennables !== null) {
                    workInProgress.updateQueue = _newThennables;
                    workInProgress.effectTag |= Update;
                  }

                  cutOffTailIfNeeded(renderState, true); // This might have been modified.

                  if (renderState.tail === null && renderState.tailMode === 'hidden' && !renderedTail.alternate) {
                    // We need to delete the row we just rendered.
                    // Reset the effect list to what it was before we rendered this
                    // child. The nested children have already appended themselves.
                    var lastEffect = workInProgress.lastEffect = renderState.lastEffect; // Remove any effects that were appended after this point.

                    if (lastEffect !== null) {
                      lastEffect.nextEffect = null;
                    } // We're done.


                    return null;
                  }
                } else if ( // The time it took to render last row is greater than time until
                // the expiration.
                now() * 2 - renderState.renderingStartTime > renderState.tailExpiration && renderExpirationTime > Never) {
                  // We have now passed our CPU deadline and we'll just give up further
                  // attempts to render the main content and only render fallbacks.
                  // The assumption is that this is usually faster.
                  workInProgress.effectTag |= DidCapture;
                  didSuspendAlready = true;
                  cutOffTailIfNeeded(renderState, false); // Since nothing actually suspended, there will nothing to ping this
                  // to get it started back up to attempt the next item. If we can show
                  // them, then they really have the same priority as this render.
                  // So we'll pick it back up the very next render pass once we've had
                  // an opportunity to yield for paint.

                  var nextPriority = renderExpirationTime - 1;
                  workInProgress.expirationTime = workInProgress.childExpirationTime = nextPriority;
                  {
                    markSpawnedWork(nextPriority);
                  }
                }
              }

              if (renderState.isBackwards) {
                // The effect list of the backwards tail will have been added
                // to the end. This breaks the guarantee that life-cycles fire in
                // sibling order but that isn't a strong guarantee promised by React.
                // Especially since these might also just pop in during future commits.
                // Append to the beginning of the list.
                renderedTail.sibling = workInProgress.child;
                workInProgress.child = renderedTail;
              } else {
                var previousSibling = renderState.last;

                if (previousSibling !== null) {
                  previousSibling.sibling = renderedTail;
                } else {
                  workInProgress.child = renderedTail;
                }

                renderState.last = renderedTail;
              }
            }

            if (renderState.tail !== null) {
              // We still have tail rows to render.
              if (renderState.tailExpiration === 0) {
                // Heuristic for how long we're willing to spend rendering rows
                // until we just give up and show what we have so far.
                var TAIL_EXPIRATION_TIMEOUT_MS = 500;
                renderState.tailExpiration = now() + TAIL_EXPIRATION_TIMEOUT_MS; // TODO: This is meant to mimic the train model or JND but this
                // is a per component value. It should really be since the start
                // of the total render or last commit. Consider using something like
                // globalMostRecentFallbackTime. That doesn't account for being
                // suspended for part of the time or when it's a new render.
                // It should probably use a global start time value instead.
              } // Pop a row.


              var next = renderState.tail;
              renderState.rendering = next;
              renderState.tail = next.sibling;
              renderState.lastEffect = workInProgress.lastEffect;
              renderState.renderingStartTime = now();
              next.sibling = null; // Restore the context.
              // TODO: We can probably just avoid popping it instead and only
              // setting it the first time we go from not suspended to suspended.

              var suspenseContext = suspenseStackCursor.current;

              if (didSuspendAlready) {
                suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback);
              } else {
                suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
              }

              pushSuspenseContext(workInProgress, suspenseContext); // Do a pass over the next row.

              return next;
            }

            return null;
          }
      }

      {
        {
          throw Error("Unknown unit of work tag (" + workInProgress.tag + "). This error is likely caused by a bug in React. Please file an issue.");
        }
      }
    }

    function unwindWork(workInProgress, renderExpirationTime) {
      switch (workInProgress.tag) {
        case ClassComponent:
          {
            var Component = workInProgress.type;

            if (isContextProvider(Component)) {
              popContext(workInProgress);
            }

            var effectTag = workInProgress.effectTag;

            if (effectTag & ShouldCapture) {
              workInProgress.effectTag = effectTag & ~ShouldCapture | DidCapture;
              return workInProgress;
            }

            return null;
          }

        case HostRoot:
          {
            popHostContainer(workInProgress);
            popTopLevelContextObject(workInProgress);
            var _effectTag = workInProgress.effectTag;

            if (!((_effectTag & DidCapture) === NoEffect)) {
              {
                throw Error("The root failed to unmount after an error. This is likely a bug in React. Please file an issue.");
              }
            }

            workInProgress.effectTag = _effectTag & ~ShouldCapture | DidCapture;
            return workInProgress;
          }

        case HostComponent:
          {
            // TODO: popHydrationState
            popHostContext(workInProgress);
            return null;
          }

        case SuspenseComponent:
          {
            popSuspenseContext(workInProgress);
            var _effectTag2 = workInProgress.effectTag;

            if (_effectTag2 & ShouldCapture) {
              workInProgress.effectTag = _effectTag2 & ~ShouldCapture | DidCapture; // Captured a suspense effect. Re-render the boundary.

              return workInProgress;
            }

            return null;
          }

        case SuspenseListComponent:
          {
            popSuspenseContext(workInProgress); // SuspenseList doesn't actually catch anything. It should've been
            // caught by a nested boundary. If not, it should bubble through.

            return null;
          }

        case HostPortal:
          popHostContainer(workInProgress);
          return null;

        case ContextProvider:
          popProvider(workInProgress);
          return null;

        default:
          return null;
      }
    }

    function unwindInterruptedWork(interruptedWork) {
      switch (interruptedWork.tag) {
        case ClassComponent:
          {
            var childContextTypes = interruptedWork.type.childContextTypes;

            if (childContextTypes !== null && childContextTypes !== undefined) {
              popContext(interruptedWork);
            }

            break;
          }

        case HostRoot:
          {
            popHostContainer(interruptedWork);
            popTopLevelContextObject(interruptedWork);
            break;
          }

        case HostComponent:
          {
            popHostContext(interruptedWork);
            break;
          }

        case HostPortal:
          popHostContainer(interruptedWork);
          break;

        case SuspenseComponent:
          popSuspenseContext(interruptedWork);
          break;

        case SuspenseListComponent:
          popSuspenseContext(interruptedWork);
          break;

        case ContextProvider:
          popProvider(interruptedWork);
          break;
      }
    }

    function createCapturedValue(value, source) {
      // If the value is an error, call this function immediately after it is thrown
      // so the stack is accurate.
      return {
        value: value,
        source: source,
        stack: getStackByFiberInDevAndProd(source)
      };
    }

    function logCapturedError(capturedError) {
      var error = capturedError.error;
      {
        var componentName = capturedError.componentName,
            componentStack = capturedError.componentStack,
            errorBoundaryName = capturedError.errorBoundaryName,
            errorBoundaryFound = capturedError.errorBoundaryFound,
            willRetry = capturedError.willRetry; // Browsers support silencing uncaught errors by calling
        // `preventDefault()` in window `error` handler.
        // We record this information as an expando on the error.

        if (error != null && error._suppressLogging) {
          if (errorBoundaryFound && willRetry) {
            // The error is recoverable and was silenced.
            // Ignore it and don't print the stack addendum.
            // This is handy for testing error boundaries without noise.
            return;
          } // The error is fatal. Since the silencing might have
          // been accidental, we'll surface it anyway.
          // However, the browser would have silenced the original error
          // so we'll print it first, and then print the stack addendum.


          console['error'](error); // Don't transform to our wrapper
          // For a more detailed description of this block, see:
          // https://github.com/facebook/react/pull/13384
        }

        var componentNameMessage = componentName ? "The above error occurred in the <" + componentName + "> component:" : 'The above error occurred in one of your React components:';
        var errorBoundaryMessage; // errorBoundaryFound check is sufficient; errorBoundaryName check is to satisfy Flow.

        if (errorBoundaryFound && errorBoundaryName) {
          if (willRetry) {
            errorBoundaryMessage = "React will try to recreate this component tree from scratch " + ("using the error boundary you provided, " + errorBoundaryName + ".");
          } else {
            errorBoundaryMessage = "This error was initially handled by the error boundary " + errorBoundaryName + ".\n" + "Recreating the tree from scratch failed so React will unmount the tree.";
          }
        } else {
          errorBoundaryMessage = 'Consider adding an error boundary to your tree to customize error handling behavior.\n' + 'Visit https://fb.me/react-error-boundaries to learn more about error boundaries.';
        }

        var combinedMessage = "" + componentNameMessage + componentStack + "\n\n" + ("" + errorBoundaryMessage); // In development, we provide our own message with just the component stack.
        // We don't include the original error message and JS stack because the browser
        // has already printed it. Even if the application swallows the error, it is still
        // displayed by the browser thanks to the DEV-only fake event trick in ReactErrorUtils.

        console['error'](combinedMessage); // Don't transform to our wrapper
      }
    }

    var didWarnAboutUndefinedSnapshotBeforeUpdate = null;
    {
      didWarnAboutUndefinedSnapshotBeforeUpdate = new Set();
    }
    var PossiblyWeakSet = typeof WeakSet === 'function' ? WeakSet : Set;

    function logError(boundary, errorInfo) {
      var source = errorInfo.source;
      var stack = errorInfo.stack;

      if (stack === null && source !== null) {
        stack = getStackByFiberInDevAndProd(source);
      }

      var capturedError = {
        componentName: source !== null ? getComponentName(source.type) : null,
        componentStack: stack !== null ? stack : '',
        error: errorInfo.value,
        errorBoundary: null,
        errorBoundaryName: null,
        errorBoundaryFound: false,
        willRetry: false
      };

      if (boundary !== null && boundary.tag === ClassComponent) {
        capturedError.errorBoundary = boundary.stateNode;
        capturedError.errorBoundaryName = getComponentName(boundary.type);
        capturedError.errorBoundaryFound = true;
        capturedError.willRetry = true;
      }

      try {
        logCapturedError(capturedError);
      } catch (e) {
        // This method must not throw, or React internal state will get messed up.
        // If console.error is overridden, or logCapturedError() shows a dialog that throws,
        // we want to report this error outside of the normal stack as a last resort.
        // https://github.com/facebook/react/issues/13188
        setTimeout(function () {
          throw e;
        });
      }
    }

    var callComponentWillUnmountWithTimer = function (current, instance) {
      startPhaseTimer(current, 'componentWillUnmount');
      instance.props = current.memoizedProps;
      instance.state = current.memoizedState;
      instance.componentWillUnmount();
      stopPhaseTimer();
    }; // Capture errors so they don't interrupt unmounting.


    function safelyCallComponentWillUnmount(current, instance) {
      {
        invokeGuardedCallback(null, callComponentWillUnmountWithTimer, null, current, instance);

        if (hasCaughtError()) {
          var unmountError = clearCaughtError();
          captureCommitPhaseError(current, unmountError);
        }
      }
    }

    function safelyDetachRef(current) {
      var ref = current.ref;

      if (ref !== null) {
        if (typeof ref === 'function') {
          {
            invokeGuardedCallback(null, ref, null, null);

            if (hasCaughtError()) {
              var refError = clearCaughtError();
              captureCommitPhaseError(current, refError);
            }
          }
        } else {
          ref.current = null;
        }
      }
    }

    function safelyCallDestroy(current, destroy) {
      {
        invokeGuardedCallback(null, destroy, null);

        if (hasCaughtError()) {
          var error = clearCaughtError();
          captureCommitPhaseError(current, error);
        }
      }
    }

    function commitBeforeMutationLifeCycles(current, finishedWork) {
      switch (finishedWork.tag) {
        case FunctionComponent:
        case ForwardRef:
        case SimpleMemoComponent:
        case Block:
          {
            return;
          }

        case ClassComponent:
          {
            if (finishedWork.effectTag & Snapshot) {
              if (current !== null) {
                var prevProps = current.memoizedProps;
                var prevState = current.memoizedState;
                startPhaseTimer(finishedWork, 'getSnapshotBeforeUpdate');
                var instance = finishedWork.stateNode; // We could update instance props and state here,
                // but instead we rely on them being set during last render.
                // TODO: revisit this when we implement resuming.

                {
                  if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
                    if (instance.props !== finishedWork.memoizedProps) {
                      error('Expected %s props to match memoized props before ' + 'getSnapshotBeforeUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance');
                    }

                    if (instance.state !== finishedWork.memoizedState) {
                      error('Expected %s state to match memoized state before ' + 'getSnapshotBeforeUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance');
                    }
                  }
                }
                var snapshot = instance.getSnapshotBeforeUpdate(finishedWork.elementType === finishedWork.type ? prevProps : resolveDefaultProps(finishedWork.type, prevProps), prevState);
                {
                  var didWarnSet = didWarnAboutUndefinedSnapshotBeforeUpdate;

                  if (snapshot === undefined && !didWarnSet.has(finishedWork.type)) {
                    didWarnSet.add(finishedWork.type);
                    error('%s.getSnapshotBeforeUpdate(): A snapshot value (or null) ' + 'must be returned. You have returned undefined.', getComponentName(finishedWork.type));
                  }
                }
                instance.__reactInternalSnapshotBeforeUpdate = snapshot;
                stopPhaseTimer();
              }
            }

            return;
          }

        case HostRoot:
        case HostComponent:
        case HostText:
        case HostPortal:
        case IncompleteClassComponent:
          // Nothing to do for these component types
          return;
      }

      {
        {
          throw Error("This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.");
        }
      }
    }

    function commitHookEffectListUnmount(tag, finishedWork) {
      var updateQueue = finishedWork.updateQueue;
      var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;

      if (lastEffect !== null) {
        var firstEffect = lastEffect.next;
        var effect = firstEffect;

        do {
          if ((effect.tag & tag) === tag) {
            // Unmount
            var destroy = effect.destroy;
            effect.destroy = undefined;

            if (destroy !== undefined) {
              destroy();
            }
          }

          effect = effect.next;
        } while (effect !== firstEffect);
      }
    }

    function commitHookEffectListMount(tag, finishedWork) {
      var updateQueue = finishedWork.updateQueue;
      var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;

      if (lastEffect !== null) {
        var firstEffect = lastEffect.next;
        var effect = firstEffect;

        do {
          if ((effect.tag & tag) === tag) {
            // Mount
            var create = effect.create;
            effect.destroy = create();
            {
              var destroy = effect.destroy;

              if (destroy !== undefined && typeof destroy !== 'function') {
                var addendum = void 0;

                if (destroy === null) {
                  addendum = ' You returned null. If your effect does not require clean ' + 'up, return undefined (or nothing).';
                } else if (typeof destroy.then === 'function') {
                  addendum = '\n\nIt looks like you wrote useEffect(async () => ...) or returned a Promise. ' + 'Instead, write the async function inside your effect ' + 'and call it immediately:\n\n' + 'useEffect(() => {\n' + '  async function fetchData() {\n' + '    // You can await here\n' + '    const response = await MyAPI.getData(someId);\n' + '    // ...\n' + '  }\n' + '  fetchData();\n' + "}, [someId]); // Or [] if effect doesn't need props or state\n\n" + 'Learn more about data fetching with Hooks: https://fb.me/react-hooks-data-fetching';
                } else {
                  addendum = ' You returned: ' + destroy;
                }

                error('An effect function must not return anything besides a function, ' + 'which is used for clean-up.%s%s', addendum, getStackByFiberInDevAndProd(finishedWork));
              }
            }
          }

          effect = effect.next;
        } while (effect !== firstEffect);
      }
    }

    function commitPassiveHookEffects(finishedWork) {
      if ((finishedWork.effectTag & Passive) !== NoEffect) {
        switch (finishedWork.tag) {
          case FunctionComponent:
          case ForwardRef:
          case SimpleMemoComponent:
          case Block:
            {
              // TODO (#17945) We should call all passive destroy functions (for all fibers)
              // before calling any create functions. The current approach only serializes
              // these for a single fiber.
              commitHookEffectListUnmount(Passive$1 | HasEffect, finishedWork);
              commitHookEffectListMount(Passive$1 | HasEffect, finishedWork);
              break;
            }
        }
      }
    }

    function commitLifeCycles(finishedRoot, current, finishedWork, committedExpirationTime) {
      switch (finishedWork.tag) {
        case FunctionComponent:
        case ForwardRef:
        case SimpleMemoComponent:
        case Block:
          {
            // At this point layout effects have already been destroyed (during mutation phase).
            // This is done to prevent sibling component effects from interfering with each other,
            // e.g. a destroy function in one component should never override a ref set
            // by a create function in another component during the same commit.
            commitHookEffectListMount(Layout | HasEffect, finishedWork);
            return;
          }

        case ClassComponent:
          {
            var instance = finishedWork.stateNode;

            if (finishedWork.effectTag & Update) {
              if (current === null) {
                startPhaseTimer(finishedWork, 'componentDidMount'); // We could update instance props and state here,
                // but instead we rely on them being set during last render.
                // TODO: revisit this when we implement resuming.

                {
                  if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
                    if (instance.props !== finishedWork.memoizedProps) {
                      error('Expected %s props to match memoized props before ' + 'componentDidMount. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance');
                    }

                    if (instance.state !== finishedWork.memoizedState) {
                      error('Expected %s state to match memoized state before ' + 'componentDidMount. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance');
                    }
                  }
                }
                instance.componentDidMount();
                stopPhaseTimer();
              } else {
                var prevProps = finishedWork.elementType === finishedWork.type ? current.memoizedProps : resolveDefaultProps(finishedWork.type, current.memoizedProps);
                var prevState = current.memoizedState;
                startPhaseTimer(finishedWork, 'componentDidUpdate'); // We could update instance props and state here,
                // but instead we rely on them being set during last render.
                // TODO: revisit this when we implement resuming.

                {
                  if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
                    if (instance.props !== finishedWork.memoizedProps) {
                      error('Expected %s props to match memoized props before ' + 'componentDidUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance');
                    }

                    if (instance.state !== finishedWork.memoizedState) {
                      error('Expected %s state to match memoized state before ' + 'componentDidUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance');
                    }
                  }
                }
                instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate);
                stopPhaseTimer();
              }
            }

            var updateQueue = finishedWork.updateQueue;

            if (updateQueue !== null) {
              {
                if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
                  if (instance.props !== finishedWork.memoizedProps) {
                    error('Expected %s props to match memoized props before ' + 'processing the update queue. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance');
                  }

                  if (instance.state !== finishedWork.memoizedState) {
                    error('Expected %s state to match memoized state before ' + 'processing the update queue. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance');
                  }
                }
              } // We could update instance props and state here,
              // but instead we rely on them being set during last render.
              // TODO: revisit this when we implement resuming.

              commitUpdateQueue(finishedWork, updateQueue, instance);
            }

            return;
          }

        case HostRoot:
          {
            var _updateQueue = finishedWork.updateQueue;

            if (_updateQueue !== null) {
              var _instance = null;

              if (finishedWork.child !== null) {
                switch (finishedWork.child.tag) {
                  case HostComponent:
                    _instance = getPublicInstance(finishedWork.child.stateNode);
                    break;

                  case ClassComponent:
                    _instance = finishedWork.child.stateNode;
                    break;
                }
              }

              commitUpdateQueue(finishedWork, _updateQueue, _instance);
            }

            return;
          }

        case HostComponent:
          {
            var _instance2 = finishedWork.stateNode; // Renderers may schedule work to be done after host components are mounted
            // (eg DOM renderer may schedule auto-focus for inputs and form controls).
            // These effects should only be committed when components are first mounted,
            // aka when there is no current/alternate.

            if (current === null && finishedWork.effectTag & Update) {
              var type = finishedWork.type;
              var props = finishedWork.memoizedProps;
              commitMount(_instance2, type, props);
            }

            return;
          }

        case HostText:
          {
            // We have no life-cycles associated with text.
            return;
          }

        case HostPortal:
          {
            // We have no life-cycles associated with portals.
            return;
          }

        case Profiler:
          {
            {
              var onRender = finishedWork.memoizedProps.onRender;

              if (typeof onRender === 'function') {
                {
                  onRender(finishedWork.memoizedProps.id, current === null ? 'mount' : 'update', finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, getCommitTime(), finishedRoot.memoizedInteractions);
                }
              }
            }
            return;
          }

        case SuspenseComponent:
          {
            commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
            return;
          }

        case SuspenseListComponent:
        case IncompleteClassComponent:
        case FundamentalComponent:
        case ScopeComponent:
          return;
      }

      {
        {
          throw Error("This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.");
        }
      }
    }

    function hideOrUnhideAllChildren(finishedWork, isHidden) {
      {
        // We only have the top Fiber that was inserted but we need to recurse down its
        // children to find all the terminal nodes.
        var node = finishedWork;

        while (true) {
          if (node.tag === HostComponent) {
            var instance = node.stateNode;

            if (isHidden) {
              hideInstance(instance);
            } else {
              unhideInstance(node.stateNode, node.memoizedProps);
            }
          } else if (node.tag === HostText) {
            var _instance3 = node.stateNode;

            if (isHidden) {
              hideTextInstance(_instance3);
            } else {
              unhideTextInstance(_instance3, node.memoizedProps);
            }
          } else if (node.tag === SuspenseComponent && node.memoizedState !== null && node.memoizedState.dehydrated === null) {
            // Found a nested Suspense component that timed out. Skip over the
            // primary child fragment, which should remain hidden.
            var fallbackChildFragment = node.child.sibling;
            fallbackChildFragment.return = node;
            node = fallbackChildFragment;
            continue;
          } else if (node.child !== null) {
            node.child.return = node;
            node = node.child;
            continue;
          }

          if (node === finishedWork) {
            return;
          }

          while (node.sibling === null) {
            if (node.return === null || node.return === finishedWork) {
              return;
            }

            node = node.return;
          }

          node.sibling.return = node.return;
          node = node.sibling;
        }
      }
    }

    function commitAttachRef(finishedWork) {
      var ref = finishedWork.ref;

      if (ref !== null) {
        var instance = finishedWork.stateNode;
        var instanceToUse;

        switch (finishedWork.tag) {
          case HostComponent:
            instanceToUse = getPublicInstance(instance);
            break;

          default:
            instanceToUse = instance;
        } // Moved outside to ensure DCE works with this flag


        if (typeof ref === 'function') {
          ref(instanceToUse);
        } else {
          {
            if (!ref.hasOwnProperty('current')) {
              error('Unexpected ref object provided for %s. ' + 'Use either a ref-setter function or React.createRef().%s', getComponentName(finishedWork.type), getStackByFiberInDevAndProd(finishedWork));
            }
          }
          ref.current = instanceToUse;
        }
      }
    }

    function commitDetachRef(current) {
      var currentRef = current.ref;

      if (currentRef !== null) {
        if (typeof currentRef === 'function') {
          currentRef(null);
        } else {
          currentRef.current = null;
        }
      }
    } // User-originating errors (lifecycles and refs) should not interrupt
    // deletion, so don't let them throw. Host-originating errors should
    // interrupt deletion, so it's okay


    function commitUnmount(finishedRoot, current, renderPriorityLevel) {
      onCommitUnmount(current);

      switch (current.tag) {
        case FunctionComponent:
        case ForwardRef:
        case MemoComponent:
        case SimpleMemoComponent:
        case Block:
          {
            var updateQueue = current.updateQueue;

            if (updateQueue !== null) {
              var lastEffect = updateQueue.lastEffect;

              if (lastEffect !== null) {
                var firstEffect = lastEffect.next;
                {
                  // When the owner fiber is deleted, the destroy function of a passive
                  // effect hook is called during the synchronous commit phase. This is
                  // a concession to implementation complexity. Calling it in the
                  // passive effect phase (like they usually are, when dependencies
                  // change during an update) would require either traversing the
                  // children of the deleted fiber again, or including unmount effects
                  // as part of the fiber effect list.
                  //
                  // Because this is during the sync commit phase, we need to change
                  // the priority.
                  //
                  // TODO: Reconsider this implementation trade off.
                  var priorityLevel = renderPriorityLevel > NormalPriority ? NormalPriority : renderPriorityLevel;
                  runWithPriority$1(priorityLevel, function () {
                    var effect = firstEffect;

                    do {
                      var _destroy = effect.destroy;

                      if (_destroy !== undefined) {
                        safelyCallDestroy(current, _destroy);
                      }

                      effect = effect.next;
                    } while (effect !== firstEffect);
                  });
                }
              }
            }

            return;
          }

        case ClassComponent:
          {
            safelyDetachRef(current);
            var instance = current.stateNode;

            if (typeof instance.componentWillUnmount === 'function') {
              safelyCallComponentWillUnmount(current, instance);
            }

            return;
          }

        case HostComponent:
          {
            safelyDetachRef(current);
            return;
          }

        case HostPortal:
          {
            // TODO: this is recursive.
            // We are also not using this parent because
            // the portal will get pushed immediately.
            {
              unmountHostComponents(finishedRoot, current, renderPriorityLevel);
            }
            return;
          }

        case FundamentalComponent:
          {
            return;
          }

        case DehydratedFragment:
          {
            return;
          }

        case ScopeComponent:
          {
            return;
          }
      }
    }

    function commitNestedUnmounts(finishedRoot, root, renderPriorityLevel) {
      // While we're inside a removed host node we don't want to call
      // removeChild on the inner nodes because they're removed by the top
      // call anyway. We also want to call componentWillUnmount on all
      // composites before this host node is removed from the tree. Therefore
      // we do an inner loop while we're still inside the host node.
      var node = root;

      while (true) {
        commitUnmount(finishedRoot, node, renderPriorityLevel); // Visit children because they may contain more composite or host nodes.
        // Skip portals because commitUnmount() currently visits them recursively.

        if (node.child !== null && // If we use mutation we drill down into portals using commitUnmount above.
        // If we don't use mutation we drill down into portals here instead.
        node.tag !== HostPortal) {
          node.child.return = node;
          node = node.child;
          continue;
        }

        if (node === root) {
          return;
        }

        while (node.sibling === null) {
          if (node.return === null || node.return === root) {
            return;
          }

          node = node.return;
        }

        node.sibling.return = node.return;
        node = node.sibling;
      }
    }

    function detachFiber(current) {
      var alternate = current.alternate; // Cut off the return pointers to disconnect it from the tree. Ideally, we
      // should clear the child pointer of the parent alternate to let this
      // get GC:ed but we don't know which for sure which parent is the current
      // one so we'll settle for GC:ing the subtree of this child. This child
      // itself will be GC:ed when the parent updates the next time.

      current.return = null;
      current.child = null;
      current.memoizedState = null;
      current.updateQueue = null;
      current.dependencies = null;
      current.alternate = null;
      current.firstEffect = null;
      current.lastEffect = null;
      current.pendingProps = null;
      current.memoizedProps = null;
      current.stateNode = null;

      if (alternate !== null) {
        detachFiber(alternate);
      }
    }

    function getHostParentFiber(fiber) {
      var parent = fiber.return;

      while (parent !== null) {
        if (isHostParent(parent)) {
          return parent;
        }

        parent = parent.return;
      }

      {
        {
          throw Error("Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.");
        }
      }
    }

    function isHostParent(fiber) {
      return fiber.tag === HostComponent || fiber.tag === HostRoot || fiber.tag === HostPortal;
    }

    function getHostSibling(fiber) {
      // We're going to search forward into the tree until we find a sibling host
      // node. Unfortunately, if multiple insertions are done in a row we have to
      // search past them. This leads to exponential search for the next sibling.
      // TODO: Find a more efficient way to do this.
      var node = fiber;

      siblings: while (true) {
        // If we didn't find anything, let's try the next sibling.
        while (node.sibling === null) {
          if (node.return === null || isHostParent(node.return)) {
            // If we pop out of the root or hit the parent the fiber we are the
            // last sibling.
            return null;
          }

          node = node.return;
        }

        node.sibling.return = node.return;
        node = node.sibling;

        while (node.tag !== HostComponent && node.tag !== HostText && node.tag !== DehydratedFragment) {
          // If it is not host node and, we might have a host node inside it.
          // Try to search down until we find one.
          if (node.effectTag & Placement) {
            // If we don't have a child, try the siblings instead.
            continue siblings;
          } // If we don't have a child, try the siblings instead.
          // We also skip portals because they are not part of this host tree.


          if (node.child === null || node.tag === HostPortal) {
            continue siblings;
          } else {
            node.child.return = node;
            node = node.child;
          }
        } // Check if this host node is stable or about to be placed.


        if (!(node.effectTag & Placement)) {
          // Found it!
          return node.stateNode;
        }
      }
    }

    function commitPlacement(finishedWork) {
      var parentFiber = getHostParentFiber(finishedWork); // Note: these two variables *must* always be updated together.

      var parent;
      var isContainer;
      var parentStateNode = parentFiber.stateNode;

      switch (parentFiber.tag) {
        case HostComponent:
          parent = parentStateNode;
          isContainer = false;
          break;

        case HostRoot:
          parent = parentStateNode.containerInfo;
          isContainer = true;
          break;

        case HostPortal:
          parent = parentStateNode.containerInfo;
          isContainer = true;
          break;

        case FundamentalComponent: // eslint-disable-next-line-no-fallthrough

        default:
          {
            {
              throw Error("Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue.");
            }
          }
      }

      if (parentFiber.effectTag & ContentReset) {
        // Reset the text content of the parent before doing any insertions
        resetTextContent(parent); // Clear ContentReset from the effect tag

        parentFiber.effectTag &= ~ContentReset;
      }

      var before = getHostSibling(finishedWork); // We only have the top Fiber that was inserted but we need to recurse down its
      // children to find all the terminal nodes.

      if (isContainer) {
        insertOrAppendPlacementNodeIntoContainer(finishedWork, before, parent);
      } else {
        insertOrAppendPlacementNode(finishedWork, before, parent);
      }
    }

    function insertOrAppendPlacementNodeIntoContainer(node, before, parent) {
      var tag = node.tag;
      var isHost = tag === HostComponent || tag === HostText;

      if (isHost || enableFundamentalAPI) {
        var stateNode = isHost ? node.stateNode : node.stateNode.instance;

        if (before) {
          insertInContainerBefore(parent, stateNode, before);
        } else {
          appendChildToContainer(parent, stateNode);
        }
      } else if (tag === HostPortal) ;else {
        var child = node.child;

        if (child !== null) {
          insertOrAppendPlacementNodeIntoContainer(child, before, parent);
          var sibling = child.sibling;

          while (sibling !== null) {
            insertOrAppendPlacementNodeIntoContainer(sibling, before, parent);
            sibling = sibling.sibling;
          }
        }
      }
    }

    function insertOrAppendPlacementNode(node, before, parent) {
      var tag = node.tag;
      var isHost = tag === HostComponent || tag === HostText;

      if (isHost || enableFundamentalAPI) {
        var stateNode = isHost ? node.stateNode : node.stateNode.instance;

        if (before) {
          insertBefore(parent, stateNode, before);
        } else {
          appendChild(parent, stateNode);
        }
      } else if (tag === HostPortal) ;else {
        var child = node.child;

        if (child !== null) {
          insertOrAppendPlacementNode(child, before, parent);
          var sibling = child.sibling;

          while (sibling !== null) {
            insertOrAppendPlacementNode(sibling, before, parent);
            sibling = sibling.sibling;
          }
        }
      }
    }

    function unmountHostComponents(finishedRoot, current, renderPriorityLevel) {
      // We only have the top Fiber that was deleted but we need to recurse down its
      // children to find all the terminal nodes.
      var node = current; // Each iteration, currentParent is populated with node's host parent if not
      // currentParentIsValid.

      var currentParentIsValid = false; // Note: these two variables *must* always be updated together.

      var currentParent;
      var currentParentIsContainer;

      while (true) {
        if (!currentParentIsValid) {
          var parent = node.return;

          findParent: while (true) {
            if (!(parent !== null)) {
              {
                throw Error("Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.");
              }
            }

            var parentStateNode = parent.stateNode;

            switch (parent.tag) {
              case HostComponent:
                currentParent = parentStateNode;
                currentParentIsContainer = false;
                break findParent;

              case HostRoot:
                currentParent = parentStateNode.containerInfo;
                currentParentIsContainer = true;
                break findParent;

              case HostPortal:
                currentParent = parentStateNode.containerInfo;
                currentParentIsContainer = true;
                break findParent;
            }

            parent = parent.return;
          }

          currentParentIsValid = true;
        }

        if (node.tag === HostComponent || node.tag === HostText) {
          commitNestedUnmounts(finishedRoot, node, renderPriorityLevel); // After all the children have unmounted, it is now safe to remove the
          // node from the tree.

          if (currentParentIsContainer) {
            removeChildFromContainer(currentParent, node.stateNode);
          } else {
            removeChild(currentParent, node.stateNode);
          } // Don't visit children because we already visited them.

        } else if (node.tag === HostPortal) {
          if (node.child !== null) {
            // When we go into a portal, it becomes the parent to remove from.
            // We will reassign it back when we pop the portal on the way up.
            currentParent = node.stateNode.containerInfo;
            currentParentIsContainer = true; // Visit children because portals might contain host components.

            node.child.return = node;
            node = node.child;
            continue;
          }
        } else {
          commitUnmount(finishedRoot, node, renderPriorityLevel); // Visit children because we may find more host components below.

          if (node.child !== null) {
            node.child.return = node;
            node = node.child;
            continue;
          }
        }

        if (node === current) {
          return;
        }

        while (node.sibling === null) {
          if (node.return === null || node.return === current) {
            return;
          }

          node = node.return;

          if (node.tag === HostPortal) {
            // When we go out of the portal, we need to restore the parent.
            // Since we don't keep a stack of them, we will search for it.
            currentParentIsValid = false;
          }
        }

        node.sibling.return = node.return;
        node = node.sibling;
      }
    }

    function commitDeletion(finishedRoot, current, renderPriorityLevel) {
      {
        // Recursively delete all host nodes from the parent.
        // Detach refs and call componentWillUnmount() on the whole subtree.
        unmountHostComponents(finishedRoot, current, renderPriorityLevel);
      }
      detachFiber(current);
    }

    function commitWork(current, finishedWork) {
      switch (finishedWork.tag) {
        case FunctionComponent:
        case ForwardRef:
        case MemoComponent:
        case SimpleMemoComponent:
        case Block:
          {
            // Layout effects are destroyed during the mutation phase so that all
            // destroy functions for all fibers are called before any create functions.
            // This prevents sibling component effects from interfering with each other,
            // e.g. a destroy function in one component should never override a ref set
            // by a create function in another component during the same commit.
            commitHookEffectListUnmount(Layout | HasEffect, finishedWork);
            return;
          }

        case ClassComponent:
          {
            return;
          }

        case HostComponent:
          {
            var instance = finishedWork.stateNode;

            if (instance != null) {
              // Commit the work prepared earlier.
              var newProps = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps
              // as the newProps. The updatePayload will contain the real change in
              // this case.

              var oldProps = current !== null ? current.memoizedProps : newProps;
              var type = finishedWork.type; // TODO: Type the updateQueue to be specific to host components.

              var updatePayload = finishedWork.updateQueue;
              finishedWork.updateQueue = null;

              if (updatePayload !== null) {
                commitUpdate(instance, updatePayload, type, oldProps, newProps);
              }
            }

            return;
          }

        case HostText:
          {
            if (!(finishedWork.stateNode !== null)) {
              {
                throw Error("This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue.");
              }
            }

            var textInstance = finishedWork.stateNode;
            var newText = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps
            // as the newProps. The updatePayload will contain the real change in
            // this case.

            var oldText = current !== null ? current.memoizedProps : newText;
            commitTextUpdate(textInstance, oldText, newText);
            return;
          }

        case HostRoot:
          {
            {
              var _root = finishedWork.stateNode;

              if (_root.hydrate) {
                // We've just hydrated. No need to hydrate again.
                _root.hydrate = false;
                commitHydratedContainer(_root.containerInfo);
              }
            }
            return;
          }

        case Profiler:
          {
            return;
          }

        case SuspenseComponent:
          {
            commitSuspenseComponent(finishedWork);
            attachSuspenseRetryListeners(finishedWork);
            return;
          }

        case SuspenseListComponent:
          {
            attachSuspenseRetryListeners(finishedWork);
            return;
          }

        case IncompleteClassComponent:
          {
            return;
          }
      }

      {
        {
          throw Error("This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.");
        }
      }
    }

    function commitSuspenseComponent(finishedWork) {
      var newState = finishedWork.memoizedState;
      var newDidTimeout;
      var primaryChildParent = finishedWork;

      if (newState === null) {
        newDidTimeout = false;
      } else {
        newDidTimeout = true;
        primaryChildParent = finishedWork.child;
        markCommitTimeOfFallback();
      }

      if (primaryChildParent !== null) {
        hideOrUnhideAllChildren(primaryChildParent, newDidTimeout);
      }
    }

    function commitSuspenseHydrationCallbacks(finishedRoot, finishedWork) {
      var newState = finishedWork.memoizedState;

      if (newState === null) {
        var current = finishedWork.alternate;

        if (current !== null) {
          var prevState = current.memoizedState;

          if (prevState !== null) {
            var suspenseInstance = prevState.dehydrated;

            if (suspenseInstance !== null) {
              commitHydratedSuspenseInstance(suspenseInstance);
            }
          }
        }
      }
    }

    function attachSuspenseRetryListeners(finishedWork) {
      // If this boundary just timed out, then it will have a set of thenables.
      // For each thenable, attach a listener so that when it resolves, React
      // attempts to re-render the boundary in the primary (pre-timeout) state.
      var thenables = finishedWork.updateQueue;

      if (thenables !== null) {
        finishedWork.updateQueue = null;
        var retryCache = finishedWork.stateNode;

        if (retryCache === null) {
          retryCache = finishedWork.stateNode = new PossiblyWeakSet();
        }

        thenables.forEach(function (thenable) {
          // Memoize using the boundary fiber to prevent redundant listeners.
          var retry = resolveRetryThenable.bind(null, finishedWork, thenable);

          if (!retryCache.has(thenable)) {
            {
              if (thenable.__reactDoNotTraceInteractions !== true) {
                retry = tracing.unstable_wrap(retry);
              }
            }
            retryCache.add(thenable);
            thenable.then(retry, retry);
          }
        });
      }
    }

    function commitResetTextContent(current) {
      resetTextContent(current.stateNode);
    }

    var PossiblyWeakMap$1 = typeof WeakMap === 'function' ? WeakMap : Map;

    function createRootErrorUpdate(fiber, errorInfo, expirationTime) {
      var update = createUpdate(expirationTime, null); // Unmount the root by rendering null.

      update.tag = CaptureUpdate; // Caution: React DevTools currently depends on this property
      // being called "element".

      update.payload = {
        element: null
      };
      var error = errorInfo.value;

      update.callback = function () {
        onUncaughtError(error);
        logError(fiber, errorInfo);
      };

      return update;
    }

    function createClassErrorUpdate(fiber, errorInfo, expirationTime) {
      var update = createUpdate(expirationTime, null);
      update.tag = CaptureUpdate;
      var getDerivedStateFromError = fiber.type.getDerivedStateFromError;

      if (typeof getDerivedStateFromError === 'function') {
        var error$1 = errorInfo.value;

        update.payload = function () {
          logError(fiber, errorInfo);
          return getDerivedStateFromError(error$1);
        };
      }

      var inst = fiber.stateNode;

      if (inst !== null && typeof inst.componentDidCatch === 'function') {
        update.callback = function callback() {
          {
            markFailedErrorBoundaryForHotReloading(fiber);
          }

          if (typeof getDerivedStateFromError !== 'function') {
            // To preserve the preexisting retry behavior of error boundaries,
            // we keep track of which ones already failed during this batch.
            // This gets reset before we yield back to the browser.
            // TODO: Warn in strict mode if getDerivedStateFromError is
            // not defined.
            markLegacyErrorBoundaryAsFailed(this); // Only log here if componentDidCatch is the only error boundary method defined

            logError(fiber, errorInfo);
          }

          var error$1 = errorInfo.value;
          var stack = errorInfo.stack;
          this.componentDidCatch(error$1, {
            componentStack: stack !== null ? stack : ''
          });
          {
            if (typeof getDerivedStateFromError !== 'function') {
              // If componentDidCatch is the only error boundary method defined,
              // then it needs to call setState to recover from errors.
              // If no state update is scheduled then the boundary will swallow the error.
              if (fiber.expirationTime !== Sync) {
                error('%s: Error boundaries should implement getDerivedStateFromError(). ' + 'In that method, return a state update to display an error message or fallback UI.', getComponentName(fiber.type) || 'Unknown');
              }
            }
          }
        };
      } else {
        update.callback = function () {
          markFailedErrorBoundaryForHotReloading(fiber);
        };
      }

      return update;
    }

    function attachPingListener(root, renderExpirationTime, thenable) {
      // Attach a listener to the promise to "ping" the root and retry. But
      // only if one does not already exist for the current render expiration
      // time (which acts like a "thread ID" here).
      var pingCache = root.pingCache;
      var threadIDs;

      if (pingCache === null) {
        pingCache = root.pingCache = new PossiblyWeakMap$1();
        threadIDs = new Set();
        pingCache.set(thenable, threadIDs);
      } else {
        threadIDs = pingCache.get(thenable);

        if (threadIDs === undefined) {
          threadIDs = new Set();
          pingCache.set(thenable, threadIDs);
        }
      }

      if (!threadIDs.has(renderExpirationTime)) {
        // Memoize using the thread ID to prevent redundant listeners.
        threadIDs.add(renderExpirationTime);
        var ping = pingSuspendedRoot.bind(null, root, thenable, renderExpirationTime);
        thenable.then(ping, ping);
      }
    }

    function throwException(root, returnFiber, sourceFiber, value, renderExpirationTime) {
      // The source fiber did not complete.
      sourceFiber.effectTag |= Incomplete; // Its effect list is no longer valid.

      sourceFiber.firstEffect = sourceFiber.lastEffect = null;

      if (value !== null && typeof value === 'object' && typeof value.then === 'function') {
        // This is a thenable.
        var thenable = value;

        if ((sourceFiber.mode & BlockingMode) === NoMode) {
          // Reset the memoizedState to what it was before we attempted
          // to render it.
          var currentSource = sourceFiber.alternate;

          if (currentSource) {
            sourceFiber.updateQueue = currentSource.updateQueue;
            sourceFiber.memoizedState = currentSource.memoizedState;
            sourceFiber.expirationTime = currentSource.expirationTime;
          } else {
            sourceFiber.updateQueue = null;
            sourceFiber.memoizedState = null;
          }
        }

        var hasInvisibleParentBoundary = hasSuspenseContext(suspenseStackCursor.current, InvisibleParentSuspenseContext); // Schedule the nearest Suspense to re-render the timed out view.

        var _workInProgress = returnFiber;

        do {
          if (_workInProgress.tag === SuspenseComponent && shouldCaptureSuspense(_workInProgress, hasInvisibleParentBoundary)) {
            // Found the nearest boundary.
            // Stash the promise on the boundary fiber. If the boundary times out, we'll
            // attach another listener to flip the boundary back to its normal state.
            var thenables = _workInProgress.updateQueue;

            if (thenables === null) {
              var updateQueue = new Set();
              updateQueue.add(thenable);
              _workInProgress.updateQueue = updateQueue;
            } else {
              thenables.add(thenable);
            } // If the boundary is outside of blocking mode, we should *not*
            // suspend the commit. Pretend as if the suspended component rendered
            // null and keep rendering. In the commit phase, we'll schedule a
            // subsequent synchronous update to re-render the Suspense.
            //
            // Note: It doesn't matter whether the component that suspended was
            // inside a blocking mode tree. If the Suspense is outside of it, we
            // should *not* suspend the commit.


            if ((_workInProgress.mode & BlockingMode) === NoMode) {
              _workInProgress.effectTag |= DidCapture; // We're going to commit this fiber even though it didn't complete.
              // But we shouldn't call any lifecycle methods or callbacks. Remove
              // all lifecycle effect tags.

              sourceFiber.effectTag &= ~(LifecycleEffectMask | Incomplete);

              if (sourceFiber.tag === ClassComponent) {
                var currentSourceFiber = sourceFiber.alternate;

                if (currentSourceFiber === null) {
                  // This is a new mount. Change the tag so it's not mistaken for a
                  // completed class component. For example, we should not call
                  // componentWillUnmount if it is deleted.
                  sourceFiber.tag = IncompleteClassComponent;
                } else {
                  // When we try rendering again, we should not reuse the current fiber,
                  // since it's known to be in an inconsistent state. Use a force update to
                  // prevent a bail out.
                  var update = createUpdate(Sync, null);
                  update.tag = ForceUpdate;
                  enqueueUpdate(sourceFiber, update);
                }
              } // The source fiber did not complete. Mark it with Sync priority to
              // indicate that it still has pending work.


              sourceFiber.expirationTime = Sync; // Exit without suspending.

              return;
            } // Confirmed that the boundary is in a concurrent mode tree. Continue
            // with the normal suspend path.
            //
            // After this we'll use a set of heuristics to determine whether this
            // render pass will run to completion or restart or "suspend" the commit.
            // The actual logic for this is spread out in different places.
            //
            // This first principle is that if we're going to suspend when we complete
            // a root, then we should also restart if we get an update or ping that
            // might unsuspend it, and vice versa. The only reason to suspend is
            // because you think you might want to restart before committing. However,
            // it doesn't make sense to restart only while in the period we're suspended.
            //
            // Restarting too aggressively is also not good because it starves out any
            // intermediate loading state. So we use heuristics to determine when.
            // Suspense Heuristics
            //
            // If nothing threw a Promise or all the same fallbacks are already showing,
            // then don't suspend/restart.
            //
            // If this is an initial render of a new tree of Suspense boundaries and
            // those trigger a fallback, then don't suspend/restart. We want to ensure
            // that we can show the initial loading state as quickly as possible.
            //
            // If we hit a "Delayed" case, such as when we'd switch from content back into
            // a fallback, then we should always suspend/restart. SuspenseConfig applies to
            // this case. If none is defined, JND is used instead.
            //
            // If we're already showing a fallback and it gets "retried", allowing us to show
            // another level, but there's still an inner boundary that would show a fallback,
            // then we suspend/restart for 500ms since the last time we showed a fallback
            // anywhere in the tree. This effectively throttles progressive loading into a
            // consistent train of commits. This also gives us an opportunity to restart to
            // get to the completed state slightly earlier.
            //
            // If there's ambiguity due to batching it's resolved in preference of:
            // 1) "delayed", 2) "initial render", 3) "retry".
            //
            // We want to ensure that a "busy" state doesn't get force committed. We want to
            // ensure that new initial loading states can commit as soon as possible.


            attachPingListener(root, renderExpirationTime, thenable);
            _workInProgress.effectTag |= ShouldCapture;
            _workInProgress.expirationTime = renderExpirationTime;
            return;
          } // This boundary already captured during this render. Continue to the next
          // boundary.


          _workInProgress = _workInProgress.return;
        } while (_workInProgress !== null); // No boundary was found. Fallthrough to error mode.
        // TODO: Use invariant so the message is stripped in prod?


        value = new Error((getComponentName(sourceFiber.type) || 'A React component') + ' suspended while rendering, but no fallback UI was specified.\n' + '\n' + 'Add a <Suspense fallback=...> component higher in the tree to ' + 'provide a loading indicator or placeholder to display.' + getStackByFiberInDevAndProd(sourceFiber));
      } // We didn't find a boundary that could handle this type of exception. Start
      // over and traverse parent path again, this time treating the exception
      // as an error.


      renderDidError();
      value = createCapturedValue(value, sourceFiber);
      var workInProgress = returnFiber;

      do {
        switch (workInProgress.tag) {
          case HostRoot:
            {
              var _errorInfo = value;
              workInProgress.effectTag |= ShouldCapture;
              workInProgress.expirationTime = renderExpirationTime;

              var _update = createRootErrorUpdate(workInProgress, _errorInfo, renderExpirationTime);

              enqueueCapturedUpdate(workInProgress, _update);
              return;
            }

          case ClassComponent:
            // Capture and retry
            var errorInfo = value;
            var ctor = workInProgress.type;
            var instance = workInProgress.stateNode;

            if ((workInProgress.effectTag & DidCapture) === NoEffect && (typeof ctor.getDerivedStateFromError === 'function' || instance !== null && typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance))) {
              workInProgress.effectTag |= ShouldCapture;
              workInProgress.expirationTime = renderExpirationTime; // Schedule the error boundary to re-render using updated state

              var _update2 = createClassErrorUpdate(workInProgress, errorInfo, renderExpirationTime);

              enqueueCapturedUpdate(workInProgress, _update2);
              return;
            }

            break;
        }

        workInProgress = workInProgress.return;
      } while (workInProgress !== null);
    }

    var ceil = Math.ceil;
    var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher,
        ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner,
        IsSomeRendererActing = ReactSharedInternals.IsSomeRendererActing;
    var NoContext =
    /*                    */
    0;
    var BatchedContext =
    /*               */
    1;
    var EventContext =
    /*                 */
    2;
    var DiscreteEventContext =
    /*         */
    4;
    var LegacyUnbatchedContext =
    /*       */
    8;
    var RenderContext =
    /*                */
    16;
    var CommitContext =
    /*                */
    32;
    var RootIncomplete = 0;
    var RootFatalErrored = 1;
    var RootErrored = 2;
    var RootSuspended = 3;
    var RootSuspendedWithDelay = 4;
    var RootCompleted = 5; // Describes where we are in the React execution stack

    var executionContext = NoContext; // The root we're working on

    var workInProgressRoot = null; // The fiber we're working on

    var workInProgress = null; // The expiration time we're rendering

    var renderExpirationTime$1 = NoWork; // Whether to root completed, errored, suspended, etc.

    var workInProgressRootExitStatus = RootIncomplete; // A fatal error, if one is thrown

    var workInProgressRootFatalError = null; // Most recent event time among processed updates during this render.
    // This is conceptually a time stamp but expressed in terms of an ExpirationTime
    // because we deal mostly with expiration times in the hot path, so this avoids
    // the conversion happening in the hot path.

    var workInProgressRootLatestProcessedExpirationTime = Sync;
    var workInProgressRootLatestSuspenseTimeout = Sync;
    var workInProgressRootCanSuspendUsingConfig = null; // The work left over by components that were visited during this render. Only
    // includes unprocessed updates, not work in bailed out children.

    var workInProgressRootNextUnprocessedUpdateTime = NoWork; // If we're pinged while rendering we don't always restart immediately.
    // This flag determines if it might be worthwhile to restart if an opportunity
    // happens latere.

    var workInProgressRootHasPendingPing = false; // The most recent time we committed a fallback. This lets us ensure a train
    // model where we don't commit new loading states in too quick succession.

    var globalMostRecentFallbackTime = 0;
    var FALLBACK_THROTTLE_MS = 500;
    var nextEffect = null;
    var hasUncaughtError = false;
    var firstUncaughtError = null;
    var legacyErrorBoundariesThatAlreadyFailed = null;
    var rootDoesHavePassiveEffects = false;
    var rootWithPendingPassiveEffects = null;
    var pendingPassiveEffectsRenderPriority = NoPriority;
    var pendingPassiveEffectsExpirationTime = NoWork;
    var rootsWithPendingDiscreteUpdates = null; // Use these to prevent an infinite loop of nested updates

    var NESTED_UPDATE_LIMIT = 50;
    var nestedUpdateCount = 0;
    var rootWithNestedUpdates = null;
    var NESTED_PASSIVE_UPDATE_LIMIT = 50;
    var nestedPassiveUpdateCount = 0;
    var interruptedBy = null; // Marks the need to reschedule pending interactions at these expiration times
    // during the commit phase. This enables them to be traced across components
    // that spawn new work during render. E.g. hidden boundaries, suspended SSR
    // hydration or SuspenseList.

    var spawnedWorkDuringRender = null; // Expiration times are computed by adding to the current time (the start
    // time). However, if two updates are scheduled within the same event, we
    // should treat their start times as simultaneous, even if the actual clock
    // time has advanced between the first and second call.
    // In other words, because expiration times determine how updates are batched,
    // we want all updates of like priority that occur within the same event to
    // receive the same expiration time. Otherwise we get tearing.

    var currentEventTime = NoWork;

    function requestCurrentTimeForUpdate() {
      if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
        // We're inside React, so it's fine to read the actual time.
        return msToExpirationTime(now());
      } // We're not inside React, so we may be in the middle of a browser event.


      if (currentEventTime !== NoWork) {
        // Use the same start time for all updates until we enter React again.
        return currentEventTime;
      } // This is the first update since React yielded. Compute a new start time.


      currentEventTime = msToExpirationTime(now());
      return currentEventTime;
    }

    function getCurrentTime() {
      return msToExpirationTime(now());
    }

    function computeExpirationForFiber(currentTime, fiber, suspenseConfig) {
      var mode = fiber.mode;

      if ((mode & BlockingMode) === NoMode) {
        return Sync;
      }

      var priorityLevel = getCurrentPriorityLevel();

      if ((mode & ConcurrentMode) === NoMode) {
        return priorityLevel === ImmediatePriority ? Sync : Batched;
      }

      if ((executionContext & RenderContext) !== NoContext) {
        // Use whatever time we're already rendering
        // TODO: Should there be a way to opt out, like with `runWithPriority`?
        return renderExpirationTime$1;
      }

      var expirationTime;

      if (suspenseConfig !== null) {
        // Compute an expiration time based on the Suspense timeout.
        expirationTime = computeSuspenseExpiration(currentTime, suspenseConfig.timeoutMs | 0 || LOW_PRIORITY_EXPIRATION);
      } else {
        // Compute an expiration time based on the Scheduler priority.
        switch (priorityLevel) {
          case ImmediatePriority:
            expirationTime = Sync;
            break;

          case UserBlockingPriority$1:
            // TODO: Rename this to computeUserBlockingExpiration
            expirationTime = computeInteractiveExpiration(currentTime);
            break;

          case NormalPriority:
          case LowPriority:
            // TODO: Handle LowPriority
            // TODO: Rename this to... something better.
            expirationTime = computeAsyncExpiration(currentTime);
            break;

          case IdlePriority:
            expirationTime = Idle;
            break;

          default:
            {
              {
                throw Error("Expected a valid priority level");
              }
            }
        }
      } // If we're in the middle of rendering a tree, do not update at the same
      // expiration time that is already rendering.
      // TODO: We shouldn't have to do this if the update is on a different root.
      // Refactor computeExpirationForFiber + scheduleUpdate so we have access to
      // the root when we check for this condition.


      if (workInProgressRoot !== null && expirationTime === renderExpirationTime$1) {
        // This is a trick to move this update into a separate batch
        expirationTime -= 1;
      }

      return expirationTime;
    }

    function scheduleUpdateOnFiber(fiber, expirationTime) {
      checkForNestedUpdates();
      warnAboutRenderPhaseUpdatesInDEV(fiber);
      var root = markUpdateTimeFromFiberToRoot(fiber, expirationTime);

      if (root === null) {
        warnAboutUpdateOnUnmountedFiberInDEV(fiber);
        return;
      }

      checkForInterruption(fiber, expirationTime);
      recordScheduleUpdate(); // TODO: computeExpirationForFiber also reads the priority. Pass the
      // priority as an argument to that function and this one.

      var priorityLevel = getCurrentPriorityLevel();

      if (expirationTime === Sync) {
        if ( // Check if we're inside unbatchedUpdates
        (executionContext & LegacyUnbatchedContext) !== NoContext && // Check if we're not already rendering
        (executionContext & (RenderContext | CommitContext)) === NoContext) {
          // Register pending interactions on the root to avoid losing traced interaction data.
          schedulePendingInteractions(root, expirationTime); // This is a legacy edge case. The initial mount of a ReactDOM.render-ed
          // root inside of batchedUpdates should be synchronous, but layout updates
          // should be deferred until the end of the batch.

          performSyncWorkOnRoot(root);
        } else {
          ensureRootIsScheduled(root);
          schedulePendingInteractions(root, expirationTime);

          if (executionContext === NoContext) {
            // Flush the synchronous work now, unless we're already working or inside
            // a batch. This is intentionally inside scheduleUpdateOnFiber instead of
            // scheduleCallbackForFiber to preserve the ability to schedule a callback
            // without immediately flushing it. We only do this for user-initiated
            // updates, to preserve historical behavior of legacy mode.
            flushSyncCallbackQueue();
          }
        }
      } else {
        ensureRootIsScheduled(root);
        schedulePendingInteractions(root, expirationTime);
      }

      if ((executionContext & DiscreteEventContext) !== NoContext && ( // Only updates at user-blocking priority or greater are considered
      // discrete, even inside a discrete event.
      priorityLevel === UserBlockingPriority$1 || priorityLevel === ImmediatePriority)) {
        // This is the result of a discrete event. Track the lowest priority
        // discrete update per root so we can flush them early, if needed.
        if (rootsWithPendingDiscreteUpdates === null) {
          rootsWithPendingDiscreteUpdates = new Map([[root, expirationTime]]);
        } else {
          var lastDiscreteTime = rootsWithPendingDiscreteUpdates.get(root);

          if (lastDiscreteTime === undefined || lastDiscreteTime > expirationTime) {
            rootsWithPendingDiscreteUpdates.set(root, expirationTime);
          }
        }
      }
    }

    var scheduleWork = scheduleUpdateOnFiber; // This is split into a separate function so we can mark a fiber with pending
    // work without treating it as a typical update that originates from an event;
    // e.g. retrying a Suspense boundary isn't an update, but it does schedule work
    // on a fiber.

    function markUpdateTimeFromFiberToRoot(fiber, expirationTime) {
      // Update the source fiber's expiration time
      if (fiber.expirationTime < expirationTime) {
        fiber.expirationTime = expirationTime;
      }

      var alternate = fiber.alternate;

      if (alternate !== null && alternate.expirationTime < expirationTime) {
        alternate.expirationTime = expirationTime;
      } // Walk the parent path to the root and update the child expiration time.


      var node = fiber.return;
      var root = null;

      if (node === null && fiber.tag === HostRoot) {
        root = fiber.stateNode;
      } else {
        while (node !== null) {
          alternate = node.alternate;

          if (node.childExpirationTime < expirationTime) {
            node.childExpirationTime = expirationTime;

            if (alternate !== null && alternate.childExpirationTime < expirationTime) {
              alternate.childExpirationTime = expirationTime;
            }
          } else if (alternate !== null && alternate.childExpirationTime < expirationTime) {
            alternate.childExpirationTime = expirationTime;
          }

          if (node.return === null && node.tag === HostRoot) {
            root = node.stateNode;
            break;
          }

          node = node.return;
        }
      }

      if (root !== null) {
        if (workInProgressRoot === root) {
          // Received an update to a tree that's in the middle of rendering. Mark
          // that's unprocessed work on this root.
          markUnprocessedUpdateTime(expirationTime);

          if (workInProgressRootExitStatus === RootSuspendedWithDelay) {
            // The root already suspended with a delay, which means this render
            // definitely won't finish. Since we have a new update, let's mark it as
            // suspended now, right before marking the incoming update. This has the
            // effect of interrupting the current render and switching to the update.
            // TODO: This happens to work when receiving an update during the render
            // phase, because of the trick inside computeExpirationForFiber to
            // subtract 1 from `renderExpirationTime` to move it into a
            // separate bucket. But we should probably model it with an exception,
            // using the same mechanism we use to force hydration of a subtree.
            // TODO: This does not account for low pri updates that were already
            // scheduled before the root started rendering. Need to track the next
            // pending expiration time (perhaps by backtracking the return path) and
            // then trigger a restart in the `renderDidSuspendDelayIfPossible` path.
            markRootSuspendedAtTime(root, renderExpirationTime$1);
          }
        } // Mark that the root has a pending update.


        markRootUpdatedAtTime(root, expirationTime);
      }

      return root;
    }

    function getNextRootExpirationTimeToWorkOn(root) {
      // Determines the next expiration time that the root should render, taking
      // into account levels that may be suspended, or levels that may have
      // received a ping.
      var lastExpiredTime = root.lastExpiredTime;

      if (lastExpiredTime !== NoWork) {
        return lastExpiredTime;
      } // "Pending" refers to any update that hasn't committed yet, including if it
      // suspended. The "suspended" range is therefore a subset.


      var firstPendingTime = root.firstPendingTime;

      if (!isRootSuspendedAtTime(root, firstPendingTime)) {
        // The highest priority pending time is not suspended. Let's work on that.
        return firstPendingTime;
      } // If the first pending time is suspended, check if there's a lower priority
      // pending level that we know about. Or check if we received a ping. Work
      // on whichever is higher priority.


      var lastPingedTime = root.lastPingedTime;
      var nextKnownPendingLevel = root.nextKnownPendingLevel;
      var nextLevel = lastPingedTime > nextKnownPendingLevel ? lastPingedTime : nextKnownPendingLevel;

      if (nextLevel <= Idle && firstPendingTime !== nextLevel) {
        // Don't work on Idle/Never priority unless everything else is committed.
        return NoWork;
      }

      return nextLevel;
    } // Use this function to schedule a task for a root. There's only one task per
    // root; if a task was already scheduled, we'll check to make sure the
    // expiration time of the existing task is the same as the expiration time of
    // the next level that the root has work on. This function is called on every
    // update, and right before exiting a task.


    function ensureRootIsScheduled(root) {
      var lastExpiredTime = root.lastExpiredTime;

      if (lastExpiredTime !== NoWork) {
        // Special case: Expired work should flush synchronously.
        root.callbackExpirationTime = Sync;
        root.callbackPriority = ImmediatePriority;
        root.callbackNode = scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root));
        return;
      }

      var expirationTime = getNextRootExpirationTimeToWorkOn(root);
      var existingCallbackNode = root.callbackNode;

      if (expirationTime === NoWork) {
        // There's nothing to work on.
        if (existingCallbackNode !== null) {
          root.callbackNode = null;
          root.callbackExpirationTime = NoWork;
          root.callbackPriority = NoPriority;
        }

        return;
      } // TODO: If this is an update, we already read the current time. Pass the
      // time as an argument.


      var currentTime = requestCurrentTimeForUpdate();
      var priorityLevel = inferPriorityFromExpirationTime(currentTime, expirationTime); // If there's an existing render task, confirm it has the correct priority and
      // expiration time. Otherwise, we'll cancel it and schedule a new one.

      if (existingCallbackNode !== null) {
        var existingCallbackPriority = root.callbackPriority;
        var existingCallbackExpirationTime = root.callbackExpirationTime;

        if ( // Callback must have the exact same expiration time.
        existingCallbackExpirationTime === expirationTime && // Callback must have greater or equal priority.
        existingCallbackPriority >= priorityLevel) {
          // Existing callback is sufficient.
          return;
        } // Need to schedule a new task.
        // TODO: Instead of scheduling a new task, we should be able to change the
        // priority of the existing one.


        cancelCallback(existingCallbackNode);
      }

      root.callbackExpirationTime = expirationTime;
      root.callbackPriority = priorityLevel;
      var callbackNode;

      if (expirationTime === Sync) {
        // Sync React callbacks are scheduled on a special internal queue
        callbackNode = scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root));
      } else {
        callbackNode = scheduleCallback(priorityLevel, performConcurrentWorkOnRoot.bind(null, root), // Compute a task timeout based on the expiration time. This also affects
        // ordering because tasks are processed in timeout order.
        {
          timeout: expirationTimeToMs(expirationTime) - now()
        });
      }

      root.callbackNode = callbackNode;
    } // This is the entry point for every concurrent task, i.e. anything that
    // goes through Scheduler.


    function performConcurrentWorkOnRoot(root, didTimeout) {
      // Since we know we're in a React event, we can clear the current
      // event time. The next update will compute a new event time.
      currentEventTime = NoWork;

      if (didTimeout) {
        // The render task took too long to complete. Mark the current time as
        // expired to synchronously render all expired work in a single batch.
        var currentTime = requestCurrentTimeForUpdate();
        markRootExpiredAtTime(root, currentTime); // This will schedule a synchronous callback.

        ensureRootIsScheduled(root);
        return null;
      } // Determine the next expiration time to work on, using the fields stored
      // on the root.


      var expirationTime = getNextRootExpirationTimeToWorkOn(root);

      if (expirationTime !== NoWork) {
        var originalCallbackNode = root.callbackNode;

        if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {
          {
            throw Error("Should not already be working.");
          }
        }

        flushPassiveEffects(); // If the root or expiration time have changed, throw out the existing stack
        // and prepare a fresh one. Otherwise we'll continue where we left off.

        if (root !== workInProgressRoot || expirationTime !== renderExpirationTime$1) {
          prepareFreshStack(root, expirationTime);
          startWorkOnPendingInteractions(root, expirationTime);
        } // If we have a work-in-progress fiber, it means there's still work to do
        // in this root.


        if (workInProgress !== null) {
          var prevExecutionContext = executionContext;
          executionContext |= RenderContext;
          var prevDispatcher = pushDispatcher();
          var prevInteractions = pushInteractions(root);
          startWorkLoopTimer(workInProgress);

          do {
            try {
              workLoopConcurrent();
              break;
            } catch (thrownValue) {
              handleError(root, thrownValue);
            }
          } while (true);

          resetContextDependencies();
          executionContext = prevExecutionContext;
          popDispatcher(prevDispatcher);
          {
            popInteractions(prevInteractions);
          }

          if (workInProgressRootExitStatus === RootFatalErrored) {
            var fatalError = workInProgressRootFatalError;
            stopInterruptedWorkLoopTimer();
            prepareFreshStack(root, expirationTime);
            markRootSuspendedAtTime(root, expirationTime);
            ensureRootIsScheduled(root);
            throw fatalError;
          }

          if (workInProgress !== null) {
            // There's still work left over. Exit without committing.
            stopInterruptedWorkLoopTimer();
          } else {
            // We now have a consistent tree. The next step is either to commit it,
            // or, if something suspended, wait to commit it after a timeout.
            stopFinishedWorkLoopTimer();
            var finishedWork = root.finishedWork = root.current.alternate;
            root.finishedExpirationTime = expirationTime;
            finishConcurrentRender(root, finishedWork, workInProgressRootExitStatus, expirationTime);
          }

          ensureRootIsScheduled(root);

          if (root.callbackNode === originalCallbackNode) {
            // The task node scheduled for this root is the same one that's
            // currently executed. Need to return a continuation.
            return performConcurrentWorkOnRoot.bind(null, root);
          }
        }
      }

      return null;
    }

    function finishConcurrentRender(root, finishedWork, exitStatus, expirationTime) {
      // Set this to null to indicate there's no in-progress render.
      workInProgressRoot = null;

      switch (exitStatus) {
        case RootIncomplete:
        case RootFatalErrored:
          {
            {
              {
                throw Error("Root did not complete. This is a bug in React.");
              }
            }
          }
        // Flow knows about invariant, so it complains if I add a break
        // statement, but eslint doesn't know about invariant, so it complains
        // if I do. eslint-disable-next-line no-fallthrough

        case RootErrored:
          {
            // If this was an async render, the error may have happened due to
            // a mutation in a concurrent event. Try rendering one more time,
            // synchronously, to see if the error goes away. If there are
            // lower priority updates, let's include those, too, in case they
            // fix the inconsistency. Render at Idle to include all updates.
            // If it was Idle or Never or some not-yet-invented time, render
            // at that time.
            markRootExpiredAtTime(root, expirationTime > Idle ? Idle : expirationTime); // We assume that this second render pass will be synchronous
            // and therefore not hit this path again.

            break;
          }

        case RootSuspended:
          {
            markRootSuspendedAtTime(root, expirationTime);
            var lastSuspendedTime = root.lastSuspendedTime;

            if (expirationTime === lastSuspendedTime) {
              root.nextKnownPendingLevel = getRemainingExpirationTime(finishedWork);
            } // We have an acceptable loading state. We need to figure out if we
            // should immediately commit it or wait a bit.
            // If we have processed new updates during this render, we may now
            // have a new loading state ready. We want to ensure that we commit
            // that as soon as possible.


            var hasNotProcessedNewUpdates = workInProgressRootLatestProcessedExpirationTime === Sync;

            if (hasNotProcessedNewUpdates && // do not delay if we're inside an act() scope
            !IsThisRendererActing.current) {
              // If we have not processed any new updates during this pass, then
              // this is either a retry of an existing fallback state or a
              // hidden tree. Hidden trees shouldn't be batched with other work
              // and after that's fixed it can only be a retry. We're going to
              // throttle committing retries so that we don't show too many
              // loading states too quickly.
              var msUntilTimeout = globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now(); // Don't bother with a very short suspense time.

              if (msUntilTimeout > 10) {
                if (workInProgressRootHasPendingPing) {
                  var lastPingedTime = root.lastPingedTime;

                  if (lastPingedTime === NoWork || lastPingedTime >= expirationTime) {
                    // This render was pinged but we didn't get to restart
                    // earlier so try restarting now instead.
                    root.lastPingedTime = expirationTime;
                    prepareFreshStack(root, expirationTime);
                    break;
                  }
                }

                var nextTime = getNextRootExpirationTimeToWorkOn(root);

                if (nextTime !== NoWork && nextTime !== expirationTime) {
                  // There's additional work on this root.
                  break;
                }

                if (lastSuspendedTime !== NoWork && lastSuspendedTime !== expirationTime) {
                  // We should prefer to render the fallback of at the last
                  // suspended level. Ping the last suspended level to try
                  // rendering it again.
                  root.lastPingedTime = lastSuspendedTime;
                  break;
                } // The render is suspended, it hasn't timed out, and there's no
                // lower priority work to do. Instead of committing the fallback
                // immediately, wait for more data to arrive.


                root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root), msUntilTimeout);
                break;
              }
            } // The work expired. Commit immediately.


            commitRoot(root);
            break;
          }

        case RootSuspendedWithDelay:
          {
            markRootSuspendedAtTime(root, expirationTime);
            var _lastSuspendedTime = root.lastSuspendedTime;

            if (expirationTime === _lastSuspendedTime) {
              root.nextKnownPendingLevel = getRemainingExpirationTime(finishedWork);
            }

            if ( // do not delay if we're inside an act() scope
            !IsThisRendererActing.current) {
              // We're suspended in a state that should be avoided. We'll try to
              // avoid committing it for as long as the timeouts let us.
              if (workInProgressRootHasPendingPing) {
                var _lastPingedTime = root.lastPingedTime;

                if (_lastPingedTime === NoWork || _lastPingedTime >= expirationTime) {
                  // This render was pinged but we didn't get to restart earlier
                  // so try restarting now instead.
                  root.lastPingedTime = expirationTime;
                  prepareFreshStack(root, expirationTime);
                  break;
                }
              }

              var _nextTime = getNextRootExpirationTimeToWorkOn(root);

              if (_nextTime !== NoWork && _nextTime !== expirationTime) {
                // There's additional work on this root.
                break;
              }

              if (_lastSuspendedTime !== NoWork && _lastSuspendedTime !== expirationTime) {
                // We should prefer to render the fallback of at the last
                // suspended level. Ping the last suspended level to try
                // rendering it again.
                root.lastPingedTime = _lastSuspendedTime;
                break;
              }

              var _msUntilTimeout;

              if (workInProgressRootLatestSuspenseTimeout !== Sync) {
                // We have processed a suspense config whose expiration time we
                // can use as the timeout.
                _msUntilTimeout = expirationTimeToMs(workInProgressRootLatestSuspenseTimeout) - now();
              } else if (workInProgressRootLatestProcessedExpirationTime === Sync) {
                // This should never normally happen because only new updates
                // cause delayed states, so we should have processed something.
                // However, this could also happen in an offscreen tree.
                _msUntilTimeout = 0;
              } else {
                // If we don't have a suspense config, we're going to use a
                // heuristic to determine how long we can suspend.
                var eventTimeMs = inferTimeFromExpirationTime(workInProgressRootLatestProcessedExpirationTime);
                var currentTimeMs = now();
                var timeUntilExpirationMs = expirationTimeToMs(expirationTime) - currentTimeMs;
                var timeElapsed = currentTimeMs - eventTimeMs;

                if (timeElapsed < 0) {
                  // We get this wrong some time since we estimate the time.
                  timeElapsed = 0;
                }

                _msUntilTimeout = jnd(timeElapsed) - timeElapsed; // Clamp the timeout to the expiration time. TODO: Once the
                // event time is exact instead of inferred from expiration time
                // we don't need this.

                if (timeUntilExpirationMs < _msUntilTimeout) {
                  _msUntilTimeout = timeUntilExpirationMs;
                }
              } // Don't bother with a very short suspense time.


              if (_msUntilTimeout > 10) {
                // The render is suspended, it hasn't timed out, and there's no
                // lower priority work to do. Instead of committing the fallback
                // immediately, wait for more data to arrive.
                root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root), _msUntilTimeout);
                break;
              }
            } // The work expired. Commit immediately.


            commitRoot(root);
            break;
          }

        case RootCompleted:
          {
            // The work completed. Ready to commit.
            if ( // do not delay if we're inside an act() scope
            !IsThisRendererActing.current && workInProgressRootLatestProcessedExpirationTime !== Sync && workInProgressRootCanSuspendUsingConfig !== null) {
              // If we have exceeded the minimum loading delay, which probably
              // means we have shown a spinner already, we might have to suspend
              // a bit longer to ensure that the spinner is shown for
              // enough time.
              var _msUntilTimeout2 = computeMsUntilSuspenseLoadingDelay(workInProgressRootLatestProcessedExpirationTime, expirationTime, workInProgressRootCanSuspendUsingConfig);

              if (_msUntilTimeout2 > 10) {
                markRootSuspendedAtTime(root, expirationTime);
                root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root), _msUntilTimeout2);
                break;
              }
            }

            commitRoot(root);
            break;
          }

        default:
          {
            {
              {
                throw Error("Unknown root exit status.");
              }
            }
          }
      }
    } // This is the entry point for synchronous tasks that don't go
    // through Scheduler


    function performSyncWorkOnRoot(root) {
      // Check if there's expired work on this root. Otherwise, render at Sync.
      var lastExpiredTime = root.lastExpiredTime;
      var expirationTime = lastExpiredTime !== NoWork ? lastExpiredTime : Sync;

      if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {
        {
          throw Error("Should not already be working.");
        }
      }

      flushPassiveEffects(); // If the root or expiration time have changed, throw out the existing stack
      // and prepare a fresh one. Otherwise we'll continue where we left off.

      if (root !== workInProgressRoot || expirationTime !== renderExpirationTime$1) {
        prepareFreshStack(root, expirationTime);
        startWorkOnPendingInteractions(root, expirationTime);
      } // If we have a work-in-progress fiber, it means there's still work to do
      // in this root.


      if (workInProgress !== null) {
        var prevExecutionContext = executionContext;
        executionContext |= RenderContext;
        var prevDispatcher = pushDispatcher();
        var prevInteractions = pushInteractions(root);
        startWorkLoopTimer(workInProgress);

        do {
          try {
            workLoopSync();
            break;
          } catch (thrownValue) {
            handleError(root, thrownValue);
          }
        } while (true);

        resetContextDependencies();
        executionContext = prevExecutionContext;
        popDispatcher(prevDispatcher);
        {
          popInteractions(prevInteractions);
        }

        if (workInProgressRootExitStatus === RootFatalErrored) {
          var fatalError = workInProgressRootFatalError;
          stopInterruptedWorkLoopTimer();
          prepareFreshStack(root, expirationTime);
          markRootSuspendedAtTime(root, expirationTime);
          ensureRootIsScheduled(root);
          throw fatalError;
        }

        if (workInProgress !== null) {
          // This is a sync render, so we should have finished the whole tree.
          {
            {
              throw Error("Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue.");
            }
          }
        } else {
          // We now have a consistent tree. Because this is a sync render, we
          // will commit it even if something suspended.
          stopFinishedWorkLoopTimer();
          root.finishedWork = root.current.alternate;
          root.finishedExpirationTime = expirationTime;
          finishSyncRender(root);
        } // Before exiting, make sure there's a callback scheduled for the next
        // pending level.


        ensureRootIsScheduled(root);
      }

      return null;
    }

    function finishSyncRender(root) {
      // Set this to null to indicate there's no in-progress render.
      workInProgressRoot = null;
      commitRoot(root);
    }

    function flushDiscreteUpdates() {
      // TODO: Should be able to flush inside batchedUpdates, but not inside `act`.
      // However, `act` uses `batchedUpdates`, so there's no way to distinguish
      // those two cases. Need to fix this before exposing flushDiscreteUpdates
      // as a public API.
      if ((executionContext & (BatchedContext | RenderContext | CommitContext)) !== NoContext) {
        {
          if ((executionContext & RenderContext) !== NoContext) {
            error('unstable_flushDiscreteUpdates: Cannot flush updates when React is ' + 'already rendering.');
          }
        } // We're already rendering, so we can't synchronously flush pending work.
        // This is probably a nested event dispatch triggered by a lifecycle/effect,
        // like `el.focus()`. Exit.

        return;
      }

      flushPendingDiscreteUpdates(); // If the discrete updates scheduled passive effects, flush them now so that
      // they fire before the next serial event.

      flushPassiveEffects();
    }

    function syncUpdates(fn, a, b, c) {
      return runWithPriority$1(ImmediatePriority, fn.bind(null, a, b, c));
    }

    function flushPendingDiscreteUpdates() {
      if (rootsWithPendingDiscreteUpdates !== null) {
        // For each root with pending discrete updates, schedule a callback to
        // immediately flush them.
        var roots = rootsWithPendingDiscreteUpdates;
        rootsWithPendingDiscreteUpdates = null;
        roots.forEach(function (expirationTime, root) {
          markRootExpiredAtTime(root, expirationTime);
          ensureRootIsScheduled(root);
        }); // Now flush the immediate queue.

        flushSyncCallbackQueue();
      }
    }

    function batchedUpdates$1(fn, a) {
      var prevExecutionContext = executionContext;
      executionContext |= BatchedContext;

      try {
        return fn(a);
      } finally {
        executionContext = prevExecutionContext;

        if (executionContext === NoContext) {
          // Flush the immediate callbacks that were scheduled during this batch
          flushSyncCallbackQueue();
        }
      }
    }

    function batchedEventUpdates$1(fn, a) {
      var prevExecutionContext = executionContext;
      executionContext |= EventContext;

      try {
        return fn(a);
      } finally {
        executionContext = prevExecutionContext;

        if (executionContext === NoContext) {
          // Flush the immediate callbacks that were scheduled during this batch
          flushSyncCallbackQueue();
        }
      }
    }

    function discreteUpdates$1(fn, a, b, c, d) {
      var prevExecutionContext = executionContext;
      executionContext |= DiscreteEventContext;

      try {
        // Should this
        return runWithPriority$1(UserBlockingPriority$1, fn.bind(null, a, b, c, d));
      } finally {
        executionContext = prevExecutionContext;

        if (executionContext === NoContext) {
          // Flush the immediate callbacks that were scheduled during this batch
          flushSyncCallbackQueue();
        }
      }
    }

    function unbatchedUpdates(fn, a) {
      var prevExecutionContext = executionContext;
      executionContext &= ~BatchedContext;
      executionContext |= LegacyUnbatchedContext;

      try {
        return fn(a);
      } finally {
        executionContext = prevExecutionContext;

        if (executionContext === NoContext) {
          // Flush the immediate callbacks that were scheduled during this batch
          flushSyncCallbackQueue();
        }
      }
    }

    function flushSync(fn, a) {
      if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
        {
          {
            throw Error("flushSync was called from inside a lifecycle method. It cannot be called when React is already rendering.");
          }
        }
      }

      var prevExecutionContext = executionContext;
      executionContext |= BatchedContext;

      try {
        return runWithPriority$1(ImmediatePriority, fn.bind(null, a));
      } finally {
        executionContext = prevExecutionContext; // Flush the immediate callbacks that were scheduled during this batch.
        // Note that this will happen even if batchedUpdates is higher up
        // the stack.

        flushSyncCallbackQueue();
      }
    }

    function prepareFreshStack(root, expirationTime) {
      root.finishedWork = null;
      root.finishedExpirationTime = NoWork;
      var timeoutHandle = root.timeoutHandle;

      if (timeoutHandle !== noTimeout) {
        // The root previous suspended and scheduled a timeout to commit a fallback
        // state. Now that we have additional work, cancel the timeout.
        root.timeoutHandle = noTimeout; // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above

        cancelTimeout(timeoutHandle);
      }

      if (workInProgress !== null) {
        var interruptedWork = workInProgress.return;

        while (interruptedWork !== null) {
          unwindInterruptedWork(interruptedWork);
          interruptedWork = interruptedWork.return;
        }
      }

      workInProgressRoot = root;
      workInProgress = createWorkInProgress(root.current, null);
      renderExpirationTime$1 = expirationTime;
      workInProgressRootExitStatus = RootIncomplete;
      workInProgressRootFatalError = null;
      workInProgressRootLatestProcessedExpirationTime = Sync;
      workInProgressRootLatestSuspenseTimeout = Sync;
      workInProgressRootCanSuspendUsingConfig = null;
      workInProgressRootNextUnprocessedUpdateTime = NoWork;
      workInProgressRootHasPendingPing = false;
      {
        spawnedWorkDuringRender = null;
      }
      {
        ReactStrictModeWarnings.discardPendingWarnings();
      }
    }

    function handleError(root, thrownValue) {
      do {
        try {
          // Reset module-level state that was set during the render phase.
          resetContextDependencies();
          resetHooksAfterThrow();
          resetCurrentFiber();

          if (workInProgress === null || workInProgress.return === null) {
            // Expected to be working on a non-root fiber. This is a fatal error
            // because there's no ancestor that can handle it; the root is
            // supposed to capture all errors that weren't caught by an error
            // boundary.
            workInProgressRootExitStatus = RootFatalErrored;
            workInProgressRootFatalError = thrownValue; // Set `workInProgress` to null. This represents advancing to the next
            // sibling, or the parent if there are no siblings. But since the root
            // has no siblings nor a parent, we set it to null. Usually this is
            // handled by `completeUnitOfWork` or `unwindWork`, but since we're
            // interntionally not calling those, we need set it here.
            // TODO: Consider calling `unwindWork` to pop the contexts.

            workInProgress = null;
            return null;
          }

          if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
            // Record the time spent rendering before an error was thrown. This
            // avoids inaccurate Profiler durations in the case of a
            // suspended render.
            stopProfilerTimerIfRunningAndRecordDelta(workInProgress, true);
          }

          throwException(root, workInProgress.return, workInProgress, thrownValue, renderExpirationTime$1);
          workInProgress = completeUnitOfWork(workInProgress);
        } catch (yetAnotherThrownValue) {
          // Something in the return path also threw.
          thrownValue = yetAnotherThrownValue;
          continue;
        } // Return to the normal work loop.


        return;
      } while (true);
    }

    function pushDispatcher(root) {
      var prevDispatcher = ReactCurrentDispatcher$1.current;
      ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;

      if (prevDispatcher === null) {
        // The React isomorphic package does not include a default dispatcher.
        // Instead the first renderer will lazily attach one, in order to give
        // nicer error messages.
        return ContextOnlyDispatcher;
      } else {
        return prevDispatcher;
      }
    }

    function popDispatcher(prevDispatcher) {
      ReactCurrentDispatcher$1.current = prevDispatcher;
    }

    function pushInteractions(root) {
      {
        var prevInteractions = tracing.__interactionsRef.current;
        tracing.__interactionsRef.current = root.memoizedInteractions;
        return prevInteractions;
      }
    }

    function popInteractions(prevInteractions) {
      {
        tracing.__interactionsRef.current = prevInteractions;
      }
    }

    function markCommitTimeOfFallback() {
      globalMostRecentFallbackTime = now();
    }

    function markRenderEventTimeAndConfig(expirationTime, suspenseConfig) {
      if (expirationTime < workInProgressRootLatestProcessedExpirationTime && expirationTime > Idle) {
        workInProgressRootLatestProcessedExpirationTime = expirationTime;
      }

      if (suspenseConfig !== null) {
        if (expirationTime < workInProgressRootLatestSuspenseTimeout && expirationTime > Idle) {
          workInProgressRootLatestSuspenseTimeout = expirationTime; // Most of the time we only have one config and getting wrong is not bad.

          workInProgressRootCanSuspendUsingConfig = suspenseConfig;
        }
      }
    }

    function markUnprocessedUpdateTime(expirationTime) {
      if (expirationTime > workInProgressRootNextUnprocessedUpdateTime) {
        workInProgressRootNextUnprocessedUpdateTime = expirationTime;
      }
    }

    function renderDidSuspend() {
      if (workInProgressRootExitStatus === RootIncomplete) {
        workInProgressRootExitStatus = RootSuspended;
      }
    }

    function renderDidSuspendDelayIfPossible() {
      if (workInProgressRootExitStatus === RootIncomplete || workInProgressRootExitStatus === RootSuspended) {
        workInProgressRootExitStatus = RootSuspendedWithDelay;
      } // Check if there's a lower priority update somewhere else in the tree.


      if (workInProgressRootNextUnprocessedUpdateTime !== NoWork && workInProgressRoot !== null) {
        // Mark the current render as suspended, and then mark that there's a
        // pending update.
        // TODO: This should immediately interrupt the current render, instead
        // of waiting until the next time we yield.
        markRootSuspendedAtTime(workInProgressRoot, renderExpirationTime$1);
        markRootUpdatedAtTime(workInProgressRoot, workInProgressRootNextUnprocessedUpdateTime);
      }
    }

    function renderDidError() {
      if (workInProgressRootExitStatus !== RootCompleted) {
        workInProgressRootExitStatus = RootErrored;
      }
    } // Called during render to determine if anything has suspended.
    // Returns false if we're not sure.


    function renderHasNotSuspendedYet() {
      // If something errored or completed, we can't really be sure,
      // so those are false.
      return workInProgressRootExitStatus === RootIncomplete;
    }

    function inferTimeFromExpirationTime(expirationTime) {
      // We don't know exactly when the update was scheduled, but we can infer an
      // approximate start time from the expiration time.
      var earliestExpirationTimeMs = expirationTimeToMs(expirationTime);
      return earliestExpirationTimeMs - LOW_PRIORITY_EXPIRATION;
    }

    function inferTimeFromExpirationTimeWithSuspenseConfig(expirationTime, suspenseConfig) {
      // We don't know exactly when the update was scheduled, but we can infer an
      // approximate start time from the expiration time by subtracting the timeout
      // that was added to the event time.
      var earliestExpirationTimeMs = expirationTimeToMs(expirationTime);
      return earliestExpirationTimeMs - (suspenseConfig.timeoutMs | 0 || LOW_PRIORITY_EXPIRATION);
    } // The work loop is an extremely hot path. Tell Closure not to inline it.

    /** @noinline */


    function workLoopSync() {
      // Already timed out, so perform work without checking if we need to yield.
      while (workInProgress !== null) {
        workInProgress = performUnitOfWork(workInProgress);
      }
    }
    /** @noinline */


    function workLoopConcurrent() {
      // Perform work until Scheduler asks us to yield
      while (workInProgress !== null && !shouldYield()) {
        workInProgress = performUnitOfWork(workInProgress);
      }
    }

    function performUnitOfWork(unitOfWork) {
      // The current, flushed, state of this fiber is the alternate. Ideally
      // nothing should rely on this, but relying on it here means that we don't
      // need an additional field on the work in progress.
      var current = unitOfWork.alternate;
      startWorkTimer(unitOfWork);
      setCurrentFiber(unitOfWork);
      var next;

      if ((unitOfWork.mode & ProfileMode) !== NoMode) {
        startProfilerTimer(unitOfWork);
        next = beginWork$1(current, unitOfWork, renderExpirationTime$1);
        stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true);
      } else {
        next = beginWork$1(current, unitOfWork, renderExpirationTime$1);
      }

      resetCurrentFiber();
      unitOfWork.memoizedProps = unitOfWork.pendingProps;

      if (next === null) {
        // If this doesn't spawn new work, complete the current work.
        next = completeUnitOfWork(unitOfWork);
      }

      ReactCurrentOwner$2.current = null;
      return next;
    }

    function completeUnitOfWork(unitOfWork) {
      // Attempt to complete the current unit of work, then move to the next
      // sibling. If there are no more siblings, return to the parent fiber.
      workInProgress = unitOfWork;

      do {
        // The current, flushed, state of this fiber is the alternate. Ideally
        // nothing should rely on this, but relying on it here means that we don't
        // need an additional field on the work in progress.
        var current = workInProgress.alternate;
        var returnFiber = workInProgress.return; // Check if the work completed or if something threw.

        if ((workInProgress.effectTag & Incomplete) === NoEffect) {
          setCurrentFiber(workInProgress);
          var next = void 0;

          if ((workInProgress.mode & ProfileMode) === NoMode) {
            next = completeWork(current, workInProgress, renderExpirationTime$1);
          } else {
            startProfilerTimer(workInProgress);
            next = completeWork(current, workInProgress, renderExpirationTime$1); // Update render duration assuming we didn't error.

            stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false);
          }

          stopWorkTimer(workInProgress);
          resetCurrentFiber();
          resetChildExpirationTime(workInProgress);

          if (next !== null) {
            // Completing this fiber spawned new work. Work on that next.
            return next;
          }

          if (returnFiber !== null && // Do not append effects to parents if a sibling failed to complete
          (returnFiber.effectTag & Incomplete) === NoEffect) {
            // Append all the effects of the subtree and this fiber onto the effect
            // list of the parent. The completion order of the children affects the
            // side-effect order.
            if (returnFiber.firstEffect === null) {
              returnFiber.firstEffect = workInProgress.firstEffect;
            }

            if (workInProgress.lastEffect !== null) {
              if (returnFiber.lastEffect !== null) {
                returnFiber.lastEffect.nextEffect = workInProgress.firstEffect;
              }

              returnFiber.lastEffect = workInProgress.lastEffect;
            } // If this fiber had side-effects, we append it AFTER the children's
            // side-effects. We can perform certain side-effects earlier if needed,
            // by doing multiple passes over the effect list. We don't want to
            // schedule our own side-effect on our own list because if end up
            // reusing children we'll schedule this effect onto itself since we're
            // at the end.


            var effectTag = workInProgress.effectTag; // Skip both NoWork and PerformedWork tags when creating the effect
            // list. PerformedWork effect is read by React DevTools but shouldn't be
            // committed.

            if (effectTag > PerformedWork) {
              if (returnFiber.lastEffect !== null) {
                returnFiber.lastEffect.nextEffect = workInProgress;
              } else {
                returnFiber.firstEffect = workInProgress;
              }

              returnFiber.lastEffect = workInProgress;
            }
          }
        } else {
          // This fiber did not complete because something threw. Pop values off
          // the stack without entering the complete phase. If this is a boundary,
          // capture values if possible.
          var _next = unwindWork(workInProgress); // Because this fiber did not complete, don't reset its expiration time.


          if ((workInProgress.mode & ProfileMode) !== NoMode) {
            // Record the render duration for the fiber that errored.
            stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false); // Include the time spent working on failed children before continuing.

            var actualDuration = workInProgress.actualDuration;
            var child = workInProgress.child;

            while (child !== null) {
              actualDuration += child.actualDuration;
              child = child.sibling;
            }

            workInProgress.actualDuration = actualDuration;
          }

          if (_next !== null) {
            // If completing this work spawned new work, do that next. We'll come
            // back here again.
            // Since we're restarting, remove anything that is not a host effect
            // from the effect tag.
            // TODO: The name stopFailedWorkTimer is misleading because Suspense
            // also captures and restarts.
            stopFailedWorkTimer(workInProgress);
            _next.effectTag &= HostEffectMask;
            return _next;
          }

          stopWorkTimer(workInProgress);

          if (returnFiber !== null) {
            // Mark the parent fiber as incomplete and clear its effect list.
            returnFiber.firstEffect = returnFiber.lastEffect = null;
            returnFiber.effectTag |= Incomplete;
          }
        }

        var siblingFiber = workInProgress.sibling;

        if (siblingFiber !== null) {
          // If there is more work to do in this returnFiber, do that next.
          return siblingFiber;
        } // Otherwise, return to the parent


        workInProgress = returnFiber;
      } while (workInProgress !== null); // We've reached the root.


      if (workInProgressRootExitStatus === RootIncomplete) {
        workInProgressRootExitStatus = RootCompleted;
      }

      return null;
    }

    function getRemainingExpirationTime(fiber) {
      var updateExpirationTime = fiber.expirationTime;
      var childExpirationTime = fiber.childExpirationTime;
      return updateExpirationTime > childExpirationTime ? updateExpirationTime : childExpirationTime;
    }

    function resetChildExpirationTime(completedWork) {
      if (renderExpirationTime$1 !== Never && completedWork.childExpirationTime === Never) {
        // The children of this component are hidden. Don't bubble their
        // expiration times.
        return;
      }

      var newChildExpirationTime = NoWork; // Bubble up the earliest expiration time.

      if ((completedWork.mode & ProfileMode) !== NoMode) {
        // In profiling mode, resetChildExpirationTime is also used to reset
        // profiler durations.
        var actualDuration = completedWork.actualDuration;
        var treeBaseDuration = completedWork.selfBaseDuration; // When a fiber is cloned, its actualDuration is reset to 0. This value will
        // only be updated if work is done on the fiber (i.e. it doesn't bailout).
        // When work is done, it should bubble to the parent's actualDuration. If
        // the fiber has not been cloned though, (meaning no work was done), then
        // this value will reflect the amount of time spent working on a previous
        // render. In that case it should not bubble. We determine whether it was
        // cloned by comparing the child pointer.

        var shouldBubbleActualDurations = completedWork.alternate === null || completedWork.child !== completedWork.alternate.child;
        var child = completedWork.child;

        while (child !== null) {
          var childUpdateExpirationTime = child.expirationTime;
          var childChildExpirationTime = child.childExpirationTime;

          if (childUpdateExpirationTime > newChildExpirationTime) {
            newChildExpirationTime = childUpdateExpirationTime;
          }

          if (childChildExpirationTime > newChildExpirationTime) {
            newChildExpirationTime = childChildExpirationTime;
          }

          if (shouldBubbleActualDurations) {
            actualDuration += child.actualDuration;
          }

          treeBaseDuration += child.treeBaseDuration;
          child = child.sibling;
        }

        completedWork.actualDuration = actualDuration;
        completedWork.treeBaseDuration = treeBaseDuration;
      } else {
        var _child = completedWork.child;

        while (_child !== null) {
          var _childUpdateExpirationTime = _child.expirationTime;
          var _childChildExpirationTime = _child.childExpirationTime;

          if (_childUpdateExpirationTime > newChildExpirationTime) {
            newChildExpirationTime = _childUpdateExpirationTime;
          }

          if (_childChildExpirationTime > newChildExpirationTime) {
            newChildExpirationTime = _childChildExpirationTime;
          }

          _child = _child.sibling;
        }
      }

      completedWork.childExpirationTime = newChildExpirationTime;
    }

    function commitRoot(root) {
      var renderPriorityLevel = getCurrentPriorityLevel();
      runWithPriority$1(ImmediatePriority, commitRootImpl.bind(null, root, renderPriorityLevel));
      return null;
    }

    function commitRootImpl(root, renderPriorityLevel) {
      do {
        // `flushPassiveEffects` will call `flushSyncUpdateQueue` at the end, which
        // means `flushPassiveEffects` will sometimes result in additional
        // passive effects. So we need to keep flushing in a loop until there are
        // no more pending effects.
        // TODO: Might be better if `flushPassiveEffects` did not automatically
        // flush synchronous work at the end, to avoid factoring hazards like this.
        flushPassiveEffects();
      } while (rootWithPendingPassiveEffects !== null);

      flushRenderPhaseStrictModeWarningsInDEV();

      if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {
        {
          throw Error("Should not already be working.");
        }
      }

      var finishedWork = root.finishedWork;
      var expirationTime = root.finishedExpirationTime;

      if (finishedWork === null) {
        return null;
      }

      root.finishedWork = null;
      root.finishedExpirationTime = NoWork;

      if (!(finishedWork !== root.current)) {
        {
          throw Error("Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue.");
        }
      } // commitRoot never returns a continuation; it always finishes synchronously.
      // So we can clear these now to allow a new callback to be scheduled.


      root.callbackNode = null;
      root.callbackExpirationTime = NoWork;
      root.callbackPriority = NoPriority;
      root.nextKnownPendingLevel = NoWork;
      startCommitTimer(); // Update the first and last pending times on this root. The new first
      // pending time is whatever is left on the root fiber.

      var remainingExpirationTimeBeforeCommit = getRemainingExpirationTime(finishedWork);
      markRootFinishedAtTime(root, expirationTime, remainingExpirationTimeBeforeCommit);

      if (root === workInProgressRoot) {
        // We can reset these now that they are finished.
        workInProgressRoot = null;
        workInProgress = null;
        renderExpirationTime$1 = NoWork;
      } // This indicates that the last root we worked on is not the same one that
      // we're committing now. This most commonly happens when a suspended root
      // times out.
      // Get the list of effects.


      var firstEffect;

      if (finishedWork.effectTag > PerformedWork) {
        // A fiber's effect list consists only of its children, not itself. So if
        // the root has an effect, we need to add it to the end of the list. The
        // resulting list is the set that would belong to the root's parent, if it
        // had one; that is, all the effects in the tree including the root.
        if (finishedWork.lastEffect !== null) {
          finishedWork.lastEffect.nextEffect = finishedWork;
          firstEffect = finishedWork.firstEffect;
        } else {
          firstEffect = finishedWork;
        }
      } else {
        // There is no effect on the root.
        firstEffect = finishedWork.firstEffect;
      }

      if (firstEffect !== null) {
        var prevExecutionContext = executionContext;
        executionContext |= CommitContext;
        var prevInteractions = pushInteractions(root); // Reset this to null before calling lifecycles

        ReactCurrentOwner$2.current = null; // The commit phase is broken into several sub-phases. We do a separate pass
        // of the effect list for each phase: all mutation effects come before all
        // layout effects, and so on.
        // The first phase a "before mutation" phase. We use this phase to read the
        // state of the host tree right before we mutate it. This is where
        // getSnapshotBeforeUpdate is called.

        startCommitSnapshotEffectsTimer();
        prepareForCommit(root.containerInfo);
        nextEffect = firstEffect;

        do {
          {
            invokeGuardedCallback(null, commitBeforeMutationEffects, null);

            if (hasCaughtError()) {
              if (!(nextEffect !== null)) {
                {
                  throw Error("Should be working on an effect.");
                }
              }

              var error = clearCaughtError();
              captureCommitPhaseError(nextEffect, error);
              nextEffect = nextEffect.nextEffect;
            }
          }
        } while (nextEffect !== null);

        stopCommitSnapshotEffectsTimer();
        {
          // Mark the current commit time to be shared by all Profilers in this
          // batch. This enables them to be grouped later.
          recordCommitTime();
        } // The next phase is the mutation phase, where we mutate the host tree.

        startCommitHostEffectsTimer();
        nextEffect = firstEffect;

        do {
          {
            invokeGuardedCallback(null, commitMutationEffects, null, root, renderPriorityLevel);

            if (hasCaughtError()) {
              if (!(nextEffect !== null)) {
                {
                  throw Error("Should be working on an effect.");
                }
              }

              var _error = clearCaughtError();

              captureCommitPhaseError(nextEffect, _error);
              nextEffect = nextEffect.nextEffect;
            }
          }
        } while (nextEffect !== null);

        stopCommitHostEffectsTimer();
        resetAfterCommit(root.containerInfo); // The work-in-progress tree is now the current tree. This must come after
        // the mutation phase, so that the previous tree is still current during
        // componentWillUnmount, but before the layout phase, so that the finished
        // work is current during componentDidMount/Update.

        root.current = finishedWork; // The next phase is the layout phase, where we call effects that read
        // the host tree after it's been mutated. The idiomatic use case for this is
        // layout, but class component lifecycles also fire here for legacy reasons.

        startCommitLifeCyclesTimer();
        nextEffect = firstEffect;

        do {
          {
            invokeGuardedCallback(null, commitLayoutEffects, null, root, expirationTime);

            if (hasCaughtError()) {
              if (!(nextEffect !== null)) {
                {
                  throw Error("Should be working on an effect.");
                }
              }

              var _error2 = clearCaughtError();

              captureCommitPhaseError(nextEffect, _error2);
              nextEffect = nextEffect.nextEffect;
            }
          }
        } while (nextEffect !== null);

        stopCommitLifeCyclesTimer();
        nextEffect = null; // Tell Scheduler to yield at the end of the frame, so the browser has an
        // opportunity to paint.

        requestPaint();
        {
          popInteractions(prevInteractions);
        }
        executionContext = prevExecutionContext;
      } else {
        // No effects.
        root.current = finishedWork; // Measure these anyway so the flamegraph explicitly shows that there were
        // no effects.
        // TODO: Maybe there's a better way to report this.

        startCommitSnapshotEffectsTimer();
        stopCommitSnapshotEffectsTimer();
        {
          recordCommitTime();
        }
        startCommitHostEffectsTimer();
        stopCommitHostEffectsTimer();
        startCommitLifeCyclesTimer();
        stopCommitLifeCyclesTimer();
      }

      stopCommitTimer();
      var rootDidHavePassiveEffects = rootDoesHavePassiveEffects;

      if (rootDoesHavePassiveEffects) {
        // This commit has passive effects. Stash a reference to them. But don't
        // schedule a callback until after flushing layout work.
        rootDoesHavePassiveEffects = false;
        rootWithPendingPassiveEffects = root;
        pendingPassiveEffectsExpirationTime = expirationTime;
        pendingPassiveEffectsRenderPriority = renderPriorityLevel;
      } else {
        // We are done with the effect chain at this point so let's clear the
        // nextEffect pointers to assist with GC. If we have passive effects, we'll
        // clear this in flushPassiveEffects.
        nextEffect = firstEffect;

        while (nextEffect !== null) {
          var nextNextEffect = nextEffect.nextEffect;
          nextEffect.nextEffect = null;
          nextEffect = nextNextEffect;
        }
      } // Check if there's remaining work on this root


      var remainingExpirationTime = root.firstPendingTime;

      if (remainingExpirationTime !== NoWork) {
        {
          if (spawnedWorkDuringRender !== null) {
            var expirationTimes = spawnedWorkDuringRender;
            spawnedWorkDuringRender = null;

            for (var i = 0; i < expirationTimes.length; i++) {
              scheduleInteractions(root, expirationTimes[i], root.memoizedInteractions);
            }
          }

          schedulePendingInteractions(root, remainingExpirationTime);
        }
      } else {
        // If there's no remaining work, we can clear the set of already failed
        // error boundaries.
        legacyErrorBoundariesThatAlreadyFailed = null;
      }

      {
        if (!rootDidHavePassiveEffects) {
          // If there are no passive effects, then we can complete the pending interactions.
          // Otherwise, we'll wait until after the passive effects are flushed.
          // Wait to do this until after remaining work has been scheduled,
          // so that we don't prematurely signal complete for interactions when there's e.g. hidden work.
          finishPendingInteractions(root, expirationTime);
        }
      }

      if (remainingExpirationTime === Sync) {
        // Count the number of times the root synchronously re-renders without
        // finishing. If there are too many, it indicates an infinite update loop.
        if (root === rootWithNestedUpdates) {
          nestedUpdateCount++;
        } else {
          nestedUpdateCount = 0;
          rootWithNestedUpdates = root;
        }
      } else {
        nestedUpdateCount = 0;
      }

      onCommitRoot(finishedWork.stateNode, expirationTime); // Always call this before exiting `commitRoot`, to ensure that any
      // additional work on this root is scheduled.

      ensureRootIsScheduled(root);

      if (hasUncaughtError) {
        hasUncaughtError = false;
        var _error3 = firstUncaughtError;
        firstUncaughtError = null;
        throw _error3;
      }

      if ((executionContext & LegacyUnbatchedContext) !== NoContext) {
        // This is a legacy edge case. We just committed the initial mount of
        // a ReactDOM.render-ed root inside of batchedUpdates. The commit fired
        // synchronously, but layout updates should be deferred until the end
        // of the batch.
        return null;
      } // If layout work was scheduled, flush it now.


      flushSyncCallbackQueue();
      return null;
    }

    function commitBeforeMutationEffects() {
      while (nextEffect !== null) {
        var effectTag = nextEffect.effectTag;

        if ((effectTag & Snapshot) !== NoEffect) {
          setCurrentFiber(nextEffect);
          recordEffect();
          var current = nextEffect.alternate;
          commitBeforeMutationLifeCycles(current, nextEffect);
          resetCurrentFiber();
        }

        if ((effectTag & Passive) !== NoEffect) {
          // If there are passive effects, schedule a callback to flush at
          // the earliest opportunity.
          if (!rootDoesHavePassiveEffects) {
            rootDoesHavePassiveEffects = true;
            scheduleCallback(NormalPriority, function () {
              flushPassiveEffects();
              return null;
            });
          }
        }

        nextEffect = nextEffect.nextEffect;
      }
    }

    function commitMutationEffects(root, renderPriorityLevel) {
      // TODO: Should probably move the bulk of this function to commitWork.
      while (nextEffect !== null) {
        setCurrentFiber(nextEffect);
        var effectTag = nextEffect.effectTag;

        if (effectTag & ContentReset) {
          commitResetTextContent(nextEffect);
        }

        if (effectTag & Ref) {
          var current = nextEffect.alternate;

          if (current !== null) {
            commitDetachRef(current);
          }
        } // The following switch statement is only concerned about placement,
        // updates, and deletions. To avoid needing to add a case for every possible
        // bitmap value, we remove the secondary effects from the effect tag and
        // switch on that value.


        var primaryEffectTag = effectTag & (Placement | Update | Deletion | Hydrating);

        switch (primaryEffectTag) {
          case Placement:
            {
              commitPlacement(nextEffect); // Clear the "placement" from effect tag so that we know that this is
              // inserted, before any life-cycles like componentDidMount gets called.
              // TODO: findDOMNode doesn't rely on this any more but isMounted does
              // and isMounted is deprecated anyway so we should be able to kill this.

              nextEffect.effectTag &= ~Placement;
              break;
            }

          case PlacementAndUpdate:
            {
              // Placement
              commitPlacement(nextEffect); // Clear the "placement" from effect tag so that we know that this is
              // inserted, before any life-cycles like componentDidMount gets called.

              nextEffect.effectTag &= ~Placement; // Update

              var _current = nextEffect.alternate;
              commitWork(_current, nextEffect);
              break;
            }

          case Hydrating:
            {
              nextEffect.effectTag &= ~Hydrating;
              break;
            }

          case HydratingAndUpdate:
            {
              nextEffect.effectTag &= ~Hydrating; // Update

              var _current2 = nextEffect.alternate;
              commitWork(_current2, nextEffect);
              break;
            }

          case Update:
            {
              var _current3 = nextEffect.alternate;
              commitWork(_current3, nextEffect);
              break;
            }

          case Deletion:
            {
              commitDeletion(root, nextEffect, renderPriorityLevel);
              break;
            }
        } // TODO: Only record a mutation effect if primaryEffectTag is non-zero.


        recordEffect();
        resetCurrentFiber();
        nextEffect = nextEffect.nextEffect;
      }
    }

    function commitLayoutEffects(root, committedExpirationTime) {
      // TODO: Should probably move the bulk of this function to commitWork.
      while (nextEffect !== null) {
        setCurrentFiber(nextEffect);
        var effectTag = nextEffect.effectTag;

        if (effectTag & (Update | Callback)) {
          recordEffect();
          var current = nextEffect.alternate;
          commitLifeCycles(root, current, nextEffect);
        }

        if (effectTag & Ref) {
          recordEffect();
          commitAttachRef(nextEffect);
        }

        resetCurrentFiber();
        nextEffect = nextEffect.nextEffect;
      }
    }

    function flushPassiveEffects() {
      if (pendingPassiveEffectsRenderPriority !== NoPriority) {
        var priorityLevel = pendingPassiveEffectsRenderPriority > NormalPriority ? NormalPriority : pendingPassiveEffectsRenderPriority;
        pendingPassiveEffectsRenderPriority = NoPriority;
        return runWithPriority$1(priorityLevel, flushPassiveEffectsImpl);
      }
    }

    function flushPassiveEffectsImpl() {
      if (rootWithPendingPassiveEffects === null) {
        return false;
      }

      var root = rootWithPendingPassiveEffects;
      var expirationTime = pendingPassiveEffectsExpirationTime;
      rootWithPendingPassiveEffects = null;
      pendingPassiveEffectsExpirationTime = NoWork;

      if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {
        {
          throw Error("Cannot flush passive effects while already rendering.");
        }
      }

      var prevExecutionContext = executionContext;
      executionContext |= CommitContext;
      var prevInteractions = pushInteractions(root);
      {
        // Note: This currently assumes there are no passive effects on the root fiber
        // because the root is not part of its own effect list.
        // This could change in the future.
        var _effect2 = root.current.firstEffect;

        while (_effect2 !== null) {
          {
            setCurrentFiber(_effect2);
            invokeGuardedCallback(null, commitPassiveHookEffects, null, _effect2);

            if (hasCaughtError()) {
              if (!(_effect2 !== null)) {
                {
                  throw Error("Should be working on an effect.");
                }
              }

              var _error5 = clearCaughtError();

              captureCommitPhaseError(_effect2, _error5);
            }

            resetCurrentFiber();
          }
          var nextNextEffect = _effect2.nextEffect; // Remove nextEffect pointer to assist GC

          _effect2.nextEffect = null;
          _effect2 = nextNextEffect;
        }
      }
      {
        popInteractions(prevInteractions);
        finishPendingInteractions(root, expirationTime);
      }
      executionContext = prevExecutionContext;
      flushSyncCallbackQueue(); // If additional passive effects were scheduled, increment a counter. If this
      // exceeds the limit, we'll fire a warning.

      nestedPassiveUpdateCount = rootWithPendingPassiveEffects === null ? 0 : nestedPassiveUpdateCount + 1;
      return true;
    }

    function isAlreadyFailedLegacyErrorBoundary(instance) {
      return legacyErrorBoundariesThatAlreadyFailed !== null && legacyErrorBoundariesThatAlreadyFailed.has(instance);
    }

    function markLegacyErrorBoundaryAsFailed(instance) {
      if (legacyErrorBoundariesThatAlreadyFailed === null) {
        legacyErrorBoundariesThatAlreadyFailed = new Set([instance]);
      } else {
        legacyErrorBoundariesThatAlreadyFailed.add(instance);
      }
    }

    function prepareToThrowUncaughtError(error) {
      if (!hasUncaughtError) {
        hasUncaughtError = true;
        firstUncaughtError = error;
      }
    }

    var onUncaughtError = prepareToThrowUncaughtError;

    function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) {
      var errorInfo = createCapturedValue(error, sourceFiber);
      var update = createRootErrorUpdate(rootFiber, errorInfo, Sync);
      enqueueUpdate(rootFiber, update);
      var root = markUpdateTimeFromFiberToRoot(rootFiber, Sync);

      if (root !== null) {
        ensureRootIsScheduled(root);
        schedulePendingInteractions(root, Sync);
      }
    }

    function captureCommitPhaseError(sourceFiber, error) {
      if (sourceFiber.tag === HostRoot) {
        // Error was thrown at the root. There is no parent, so the root
        // itself should capture it.
        captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error);
        return;
      }

      var fiber = sourceFiber.return;

      while (fiber !== null) {
        if (fiber.tag === HostRoot) {
          captureCommitPhaseErrorOnRoot(fiber, sourceFiber, error);
          return;
        } else if (fiber.tag === ClassComponent) {
          var ctor = fiber.type;
          var instance = fiber.stateNode;

          if (typeof ctor.getDerivedStateFromError === 'function' || typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance)) {
            var errorInfo = createCapturedValue(error, sourceFiber);
            var update = createClassErrorUpdate(fiber, errorInfo, // TODO: This is always sync
            Sync);
            enqueueUpdate(fiber, update);
            var root = markUpdateTimeFromFiberToRoot(fiber, Sync);

            if (root !== null) {
              ensureRootIsScheduled(root);
              schedulePendingInteractions(root, Sync);
            }

            return;
          }
        }

        fiber = fiber.return;
      }
    }

    function pingSuspendedRoot(root, thenable, suspendedTime) {
      var pingCache = root.pingCache;

      if (pingCache !== null) {
        // The thenable resolved, so we no longer need to memoize, because it will
        // never be thrown again.
        pingCache.delete(thenable);
      }

      if (workInProgressRoot === root && renderExpirationTime$1 === suspendedTime) {
        // Received a ping at the same priority level at which we're currently
        // rendering. We might want to restart this render. This should mirror
        // the logic of whether or not a root suspends once it completes.
        // TODO: If we're rendering sync either due to Sync, Batched or expired,
        // we should probably never restart.
        // If we're suspended with delay, we'll always suspend so we can always
        // restart. If we're suspended without any updates, it might be a retry.
        // If it's early in the retry we can restart. We can't know for sure
        // whether we'll eventually process an update during this render pass,
        // but it's somewhat unlikely that we get to a ping before that, since
        // getting to the root most update is usually very fast.
        if (workInProgressRootExitStatus === RootSuspendedWithDelay || workInProgressRootExitStatus === RootSuspended && workInProgressRootLatestProcessedExpirationTime === Sync && now() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS) {
          // Restart from the root. Don't need to schedule a ping because
          // we're already working on this tree.
          prepareFreshStack(root, renderExpirationTime$1);
        } else {
          // Even though we can't restart right now, we might get an
          // opportunity later. So we mark this render as having a ping.
          workInProgressRootHasPendingPing = true;
        }

        return;
      }

      if (!isRootSuspendedAtTime(root, suspendedTime)) {
        // The root is no longer suspended at this time.
        return;
      }

      var lastPingedTime = root.lastPingedTime;

      if (lastPingedTime !== NoWork && lastPingedTime < suspendedTime) {
        // There's already a lower priority ping scheduled.
        return;
      } // Mark the time at which this ping was scheduled.


      root.lastPingedTime = suspendedTime;
      ensureRootIsScheduled(root);
      schedulePendingInteractions(root, suspendedTime);
    }

    function retryTimedOutBoundary(boundaryFiber, retryTime) {
      // The boundary fiber (a Suspense component or SuspenseList component)
      // previously was rendered in its fallback state. One of the promises that
      // suspended it has resolved, which means at least part of the tree was
      // likely unblocked. Try rendering again, at a new expiration time.
      if (retryTime === NoWork) {
        var suspenseConfig = null; // Retries don't carry over the already committed update.

        var currentTime = requestCurrentTimeForUpdate();
        retryTime = computeExpirationForFiber(currentTime, boundaryFiber, suspenseConfig);
      } // TODO: Special case idle priority?


      var root = markUpdateTimeFromFiberToRoot(boundaryFiber, retryTime);

      if (root !== null) {
        ensureRootIsScheduled(root);
        schedulePendingInteractions(root, retryTime);
      }
    }

    function resolveRetryThenable(boundaryFiber, thenable) {
      var retryTime = NoWork; // Default

      var retryCache;
      {
        retryCache = boundaryFiber.stateNode;
      }

      if (retryCache !== null) {
        // The thenable resolved, so we no longer need to memoize, because it will
        // never be thrown again.
        retryCache.delete(thenable);
      }

      retryTimedOutBoundary(boundaryFiber, retryTime);
    } // Computes the next Just Noticeable Difference (JND) boundary.
    // The theory is that a person can't tell the difference between small differences in time.
    // Therefore, if we wait a bit longer than necessary that won't translate to a noticeable
    // difference in the experience. However, waiting for longer might mean that we can avoid
    // showing an intermediate loading state. The longer we have already waited, the harder it
    // is to tell small differences in time. Therefore, the longer we've already waited,
    // the longer we can wait additionally. At some point we have to give up though.
    // We pick a train model where the next boundary commits at a consistent schedule.
    // These particular numbers are vague estimates. We expect to adjust them based on research.


    function jnd(timeElapsed) {
      return timeElapsed < 120 ? 120 : timeElapsed < 480 ? 480 : timeElapsed < 1080 ? 1080 : timeElapsed < 1920 ? 1920 : timeElapsed < 3000 ? 3000 : timeElapsed < 4320 ? 4320 : ceil(timeElapsed / 1960) * 1960;
    }

    function computeMsUntilSuspenseLoadingDelay(mostRecentEventTime, committedExpirationTime, suspenseConfig) {
      var busyMinDurationMs = suspenseConfig.busyMinDurationMs | 0;

      if (busyMinDurationMs <= 0) {
        return 0;
      }

      var busyDelayMs = suspenseConfig.busyDelayMs | 0; // Compute the time until this render pass would expire.

      var currentTimeMs = now();
      var eventTimeMs = inferTimeFromExpirationTimeWithSuspenseConfig(mostRecentEventTime, suspenseConfig);
      var timeElapsed = currentTimeMs - eventTimeMs;

      if (timeElapsed <= busyDelayMs) {
        // If we haven't yet waited longer than the initial delay, we don't
        // have to wait any additional time.
        return 0;
      }

      var msUntilTimeout = busyDelayMs + busyMinDurationMs - timeElapsed; // This is the value that is passed to `setTimeout`.

      return msUntilTimeout;
    }

    function checkForNestedUpdates() {
      if (nestedUpdateCount > NESTED_UPDATE_LIMIT) {
        nestedUpdateCount = 0;
        rootWithNestedUpdates = null;
        {
          {
            throw Error("Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.");
          }
        }
      }

      {
        if (nestedPassiveUpdateCount > NESTED_PASSIVE_UPDATE_LIMIT) {
          nestedPassiveUpdateCount = 0;
          error('Maximum update depth exceeded. This can happen when a component ' + "calls setState inside useEffect, but useEffect either doesn't " + 'have a dependency array, or one of the dependencies changes on ' + 'every render.');
        }
      }
    }

    function flushRenderPhaseStrictModeWarningsInDEV() {
      {
        ReactStrictModeWarnings.flushLegacyContextWarning();
        {
          ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings();
        }
      }
    }

    function stopFinishedWorkLoopTimer() {
      var didCompleteRoot = true;
      stopWorkLoopTimer(interruptedBy, didCompleteRoot);
      interruptedBy = null;
    }

    function stopInterruptedWorkLoopTimer() {
      // TODO: Track which fiber caused the interruption.
      var didCompleteRoot = false;
      stopWorkLoopTimer(interruptedBy, didCompleteRoot);
      interruptedBy = null;
    }

    function checkForInterruption(fiberThatReceivedUpdate, updateExpirationTime) {
      if (workInProgressRoot !== null && updateExpirationTime > renderExpirationTime$1) {
        interruptedBy = fiberThatReceivedUpdate;
      }
    }

    var didWarnStateUpdateForUnmountedComponent = null;

    function warnAboutUpdateOnUnmountedFiberInDEV(fiber) {
      {
        var tag = fiber.tag;

        if (tag !== HostRoot && tag !== ClassComponent && tag !== FunctionComponent && tag !== ForwardRef && tag !== MemoComponent && tag !== SimpleMemoComponent && tag !== Block) {
          // Only warn for user-defined components, not internal ones like Suspense.
          return;
        } // the problematic code almost always lies inside that component.


        var componentName = getComponentName(fiber.type) || 'ReactComponent';

        if (didWarnStateUpdateForUnmountedComponent !== null) {
          if (didWarnStateUpdateForUnmountedComponent.has(componentName)) {
            return;
          }

          didWarnStateUpdateForUnmountedComponent.add(componentName);
        } else {
          didWarnStateUpdateForUnmountedComponent = new Set([componentName]);
        }

        error("Can't perform a React state update on an unmounted component. This " + 'is a no-op, but it indicates a memory leak in your application. To ' + 'fix, cancel all subscriptions and asynchronous tasks in %s.%s', tag === ClassComponent ? 'the componentWillUnmount method' : 'a useEffect cleanup function', getStackByFiberInDevAndProd(fiber));
      }
    }

    var beginWork$1;
    {
      var dummyFiber = null;

      beginWork$1 = function (current, unitOfWork, expirationTime) {
        // If a component throws an error, we replay it again in a synchronously
        // dispatched event, so that the debugger will treat it as an uncaught
        // error See ReactErrorUtils for more information.
        // Before entering the begin phase, copy the work-in-progress onto a dummy
        // fiber. If beginWork throws, we'll use this to reset the state.
        var originalWorkInProgressCopy = assignFiberPropertiesInDEV(dummyFiber, unitOfWork);

        try {
          return beginWork(current, unitOfWork, expirationTime);
        } catch (originalError) {
          if (originalError !== null && typeof originalError === 'object' && typeof originalError.then === 'function') {
            // Don't replay promises. Treat everything else like an error.
            throw originalError;
          } // Keep this code in sync with handleError; any changes here must have
          // corresponding changes there.


          resetContextDependencies();
          resetHooksAfterThrow(); // Don't reset current debug fiber, since we're about to work on the
          // same fiber again.
          // Unwind the failed stack frame

          unwindInterruptedWork(unitOfWork); // Restore the original properties of the fiber.

          assignFiberPropertiesInDEV(unitOfWork, originalWorkInProgressCopy);

          if (unitOfWork.mode & ProfileMode) {
            // Reset the profiler timer.
            startProfilerTimer(unitOfWork);
          } // Run beginWork again.


          invokeGuardedCallback(null, beginWork, null, current, unitOfWork, expirationTime);

          if (hasCaughtError()) {
            var replayError = clearCaughtError(); // `invokeGuardedCallback` sometimes sets an expando `_suppressLogging`.
            // Rethrow this error instead of the original one.

            throw replayError;
          } else {
            // This branch is reachable if the render phase is impure.
            throw originalError;
          }
        }
      };
    }
    var didWarnAboutUpdateInRender = false;
    var didWarnAboutUpdateInRenderForAnotherComponent;
    {
      didWarnAboutUpdateInRenderForAnotherComponent = new Set();
    }

    function warnAboutRenderPhaseUpdatesInDEV(fiber) {
      {
        if (isRendering && (executionContext & RenderContext) !== NoContext) {
          switch (fiber.tag) {
            case FunctionComponent:
            case ForwardRef:
            case SimpleMemoComponent:
              {
                var renderingComponentName = workInProgress && getComponentName(workInProgress.type) || 'Unknown'; // Dedupe by the rendering component because it's the one that needs to be fixed.

                var dedupeKey = renderingComponentName;

                if (!didWarnAboutUpdateInRenderForAnotherComponent.has(dedupeKey)) {
                  didWarnAboutUpdateInRenderForAnotherComponent.add(dedupeKey);
                  var setStateComponentName = getComponentName(fiber.type) || 'Unknown';
                  error('Cannot update a component (`%s`) while rendering a ' + 'different component (`%s`). To locate the bad setState() call inside `%s`, ' + 'follow the stack trace as described in https://fb.me/setstate-in-render', setStateComponentName, renderingComponentName, renderingComponentName);
                }

                break;
              }

            case ClassComponent:
              {
                if (!didWarnAboutUpdateInRender) {
                  error('Cannot update during an existing state transition (such as ' + 'within `render`). Render methods should be a pure ' + 'function of props and state.');
                  didWarnAboutUpdateInRender = true;
                }

                break;
              }
          }
        }
      }
    } // a 'shared' variable that changes when act() opens/closes in tests.


    var IsThisRendererActing = {
      current: false
    };

    function warnIfNotScopedWithMatchingAct(fiber) {
      {
        if (IsSomeRendererActing.current === true && IsThisRendererActing.current !== true) {
          error("It looks like you're using the wrong act() around your test interactions.\n" + 'Be sure to use the matching version of act() corresponding to your renderer:\n\n' + '// for react-dom:\n' + "import {act} from 'react-dom/test-utils';\n" + '// ...\n' + 'act(() => ...);\n\n' + '// for react-test-renderer:\n' + "import TestRenderer from 'react-test-renderer';\n" + 'const {act} = TestRenderer;\n' + '// ...\n' + 'act(() => ...);' + '%s', getStackByFiberInDevAndProd(fiber));
        }
      }
    }

    function warnIfNotCurrentlyActingEffectsInDEV(fiber) {
      {
        if ((fiber.mode & StrictMode) !== NoMode && IsSomeRendererActing.current === false && IsThisRendererActing.current === false) {
          error('An update to %s ran an effect, but was not wrapped in act(...).\n\n' + 'When testing, code that causes React state updates should be ' + 'wrapped into act(...):\n\n' + 'act(() => {\n' + '  /* fire events that update state */\n' + '});\n' + '/* assert on the output */\n\n' + "This ensures that you're testing the behavior the user would see " + 'in the browser.' + ' Learn more at https://fb.me/react-wrap-tests-with-act' + '%s', getComponentName(fiber.type), getStackByFiberInDevAndProd(fiber));
        }
      }
    }

    function warnIfNotCurrentlyActingUpdatesInDEV(fiber) {
      {
        if (executionContext === NoContext && IsSomeRendererActing.current === false && IsThisRendererActing.current === false) {
          error('An update to %s inside a test was not wrapped in act(...).\n\n' + 'When testing, code that causes React state updates should be ' + 'wrapped into act(...):\n\n' + 'act(() => {\n' + '  /* fire events that update state */\n' + '});\n' + '/* assert on the output */\n\n' + "This ensures that you're testing the behavior the user would see " + 'in the browser.' + ' Learn more at https://fb.me/react-wrap-tests-with-act' + '%s', getComponentName(fiber.type), getStackByFiberInDevAndProd(fiber));
        }
      }
    }

    var warnIfNotCurrentlyActingUpdatesInDev = warnIfNotCurrentlyActingUpdatesInDEV; // In tests, we want to enforce a mocked scheduler.

    var didWarnAboutUnmockedScheduler = false; // TODO Before we release concurrent mode, revisit this and decide whether a mocked
    // scheduler is the actual recommendation. The alternative could be a testing build,
    // a new lib, or whatever; we dunno just yet. This message is for early adopters
    // to get their tests right.

    function warnIfUnmockedScheduler(fiber) {
      {
        if (didWarnAboutUnmockedScheduler === false && Scheduler.unstable_flushAllWithoutAsserting === undefined) {
          if (fiber.mode & BlockingMode || fiber.mode & ConcurrentMode) {
            didWarnAboutUnmockedScheduler = true;
            error('In Concurrent or Sync modes, the "scheduler" module needs to be mocked ' + 'to guarantee consistent behaviour across tests and browsers. ' + 'For example, with jest: \n' + "jest.mock('scheduler', () => require('scheduler/unstable_mock'));\n\n" + 'For more info, visit https://fb.me/react-mock-scheduler');
          }
        }
      }
    }

    function computeThreadID(root, expirationTime) {
      // Interaction threads are unique per root and expiration time.
      return expirationTime * 1000 + root.interactionThreadID;
    }

    function markSpawnedWork(expirationTime) {
      if (spawnedWorkDuringRender === null) {
        spawnedWorkDuringRender = [expirationTime];
      } else {
        spawnedWorkDuringRender.push(expirationTime);
      }
    }

    function scheduleInteractions(root, expirationTime, interactions) {
      if (interactions.size > 0) {
        var pendingInteractionMap = root.pendingInteractionMap;
        var pendingInteractions = pendingInteractionMap.get(expirationTime);

        if (pendingInteractions != null) {
          interactions.forEach(function (interaction) {
            if (!pendingInteractions.has(interaction)) {
              // Update the pending async work count for previously unscheduled interaction.
              interaction.__count++;
            }

            pendingInteractions.add(interaction);
          });
        } else {
          pendingInteractionMap.set(expirationTime, new Set(interactions)); // Update the pending async work count for the current interactions.

          interactions.forEach(function (interaction) {
            interaction.__count++;
          });
        }

        var subscriber = tracing.__subscriberRef.current;

        if (subscriber !== null) {
          var threadID = computeThreadID(root, expirationTime);
          subscriber.onWorkScheduled(interactions, threadID);
        }
      }
    }

    function schedulePendingInteractions(root, expirationTime) {
      scheduleInteractions(root, expirationTime, tracing.__interactionsRef.current);
    }

    function startWorkOnPendingInteractions(root, expirationTime) {
      // we can accurately attribute time spent working on it, And so that cascading
      // work triggered during the render phase will be associated with it.
      var interactions = new Set();
      root.pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) {
        if (scheduledExpirationTime >= expirationTime) {
          scheduledInteractions.forEach(function (interaction) {
            return interactions.add(interaction);
          });
        }
      }); // Store the current set of interactions on the FiberRoot for a few reasons:
      // We can re-use it in hot functions like performConcurrentWorkOnRoot()
      // without having to recalculate it. We will also use it in commitWork() to
      // pass to any Profiler onRender() hooks. This also provides DevTools with a
      // way to access it when the onCommitRoot() hook is called.

      root.memoizedInteractions = interactions;

      if (interactions.size > 0) {
        var subscriber = tracing.__subscriberRef.current;

        if (subscriber !== null) {
          var threadID = computeThreadID(root, expirationTime);

          try {
            subscriber.onWorkStarted(interactions, threadID);
          } catch (error) {
            // If the subscriber throws, rethrow it in a separate task
            scheduleCallback(ImmediatePriority, function () {
              throw error;
            });
          }
        }
      }
    }

    function finishPendingInteractions(root, committedExpirationTime) {
      var earliestRemainingTimeAfterCommit = root.firstPendingTime;
      var subscriber;

      try {
        subscriber = tracing.__subscriberRef.current;

        if (subscriber !== null && root.memoizedInteractions.size > 0) {
          var threadID = computeThreadID(root, committedExpirationTime);
          subscriber.onWorkStopped(root.memoizedInteractions, threadID);
        }
      } catch (error) {
        // If the subscriber throws, rethrow it in a separate task
        scheduleCallback(ImmediatePriority, function () {
          throw error;
        });
      } finally {
        // Clear completed interactions from the pending Map.
        // Unless the render was suspended or cascading work was scheduled,
        // In which case– leave pending interactions until the subsequent render.
        var pendingInteractionMap = root.pendingInteractionMap;
        pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) {
          // Only decrement the pending interaction count if we're done.
          // If there's still work at the current priority,
          // That indicates that we are waiting for suspense data.
          if (scheduledExpirationTime > earliestRemainingTimeAfterCommit) {
            pendingInteractionMap.delete(scheduledExpirationTime);
            scheduledInteractions.forEach(function (interaction) {
              interaction.__count--;

              if (subscriber !== null && interaction.__count === 0) {
                try {
                  subscriber.onInteractionScheduledWorkCompleted(interaction);
                } catch (error) {
                  // If the subscriber throws, rethrow it in a separate task
                  scheduleCallback(ImmediatePriority, function () {
                    throw error;
                  });
                }
              }
            });
          }
        });
      }
    }

    var onScheduleFiberRoot = null;
    var onCommitFiberRoot = null;
    var onCommitFiberUnmount = null;
    var hasLoggedError = false;
    var isDevToolsPresent = typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined';

    function injectInternals(internals) {
      if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
        // No DevTools
        return false;
      }

      var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__;

      if (hook.isDisabled) {
        // This isn't a real property on the hook, but it can be set to opt out
        // of DevTools integration and associated warnings and logs.
        // https://github.com/facebook/react/issues/3877
        return true;
      }

      if (!hook.supportsFiber) {
        {
          error('The installed version of React DevTools is too old and will not work ' + 'with the current version of React. Please update React DevTools. ' + 'https://fb.me/react-devtools');
        } // DevTools exists, even though it doesn't support Fiber.

        return true;
      }

      try {
        var rendererID = hook.inject(internals); // We have successfully injected, so now it is safe to set up hooks.

        if (true) {
          // Only used by Fast Refresh
          if (typeof hook.onScheduleFiberRoot === 'function') {
            onScheduleFiberRoot = function (root, children) {
              try {
                hook.onScheduleFiberRoot(rendererID, root, children);
              } catch (err) {
                if (true && !hasLoggedError) {
                  hasLoggedError = true;
                  error('React instrumentation encountered an error: %s', err);
                }
              }
            };
          }
        }

        onCommitFiberRoot = function (root, expirationTime) {
          try {
            var didError = (root.current.effectTag & DidCapture) === DidCapture;

            if (enableProfilerTimer) {
              var currentTime = getCurrentTime();
              var priorityLevel = inferPriorityFromExpirationTime(currentTime, expirationTime);
              hook.onCommitFiberRoot(rendererID, root, priorityLevel, didError);
            } else {
              hook.onCommitFiberRoot(rendererID, root, undefined, didError);
            }
          } catch (err) {
            if (true) {
              if (!hasLoggedError) {
                hasLoggedError = true;
                error('React instrumentation encountered an error: %s', err);
              }
            }
          }
        };

        onCommitFiberUnmount = function (fiber) {
          try {
            hook.onCommitFiberUnmount(rendererID, fiber);
          } catch (err) {
            if (true) {
              if (!hasLoggedError) {
                hasLoggedError = true;
                error('React instrumentation encountered an error: %s', err);
              }
            }
          }
        };
      } catch (err) {
        // Catch all errors because it is unsafe to throw during initialization.
        {
          error('React instrumentation encountered an error: %s.', err);
        }
      } // DevTools exists


      return true;
    }

    function onScheduleRoot(root, children) {
      if (typeof onScheduleFiberRoot === 'function') {
        onScheduleFiberRoot(root, children);
      }
    }

    function onCommitRoot(root, expirationTime) {
      if (typeof onCommitFiberRoot === 'function') {
        onCommitFiberRoot(root, expirationTime);
      }
    }

    function onCommitUnmount(fiber) {
      if (typeof onCommitFiberUnmount === 'function') {
        onCommitFiberUnmount(fiber);
      }
    }

    var hasBadMapPolyfill;
    {
      hasBadMapPolyfill = false;

      try {
        var nonExtensibleObject = Object.preventExtensions({});
        var testMap = new Map([[nonExtensibleObject, null]]);
        var testSet = new Set([nonExtensibleObject]); // This is necessary for Rollup to not consider these unused.
        // https://github.com/rollup/rollup/issues/1771
        // TODO: we can remove these if Rollup fixes the bug.

        testMap.set(0, 0);
        testSet.add(0);
      } catch (e) {
        // TODO: Consider warning about bad polyfills
        hasBadMapPolyfill = true;
      }
    }
    var debugCounter = 1;

    function FiberNode(tag, pendingProps, key, mode) {
      // Instance
      this.tag = tag;
      this.key = key;
      this.elementType = null;
      this.type = null;
      this.stateNode = null; // Fiber

      this.return = null;
      this.child = null;
      this.sibling = null;
      this.index = 0;
      this.ref = null;
      this.pendingProps = pendingProps;
      this.memoizedProps = null;
      this.updateQueue = null;
      this.memoizedState = null;
      this.dependencies = null;
      this.mode = mode; // Effects

      this.effectTag = NoEffect;
      this.nextEffect = null;
      this.firstEffect = null;
      this.lastEffect = null;
      this.expirationTime = NoWork;
      this.childExpirationTime = NoWork;
      this.alternate = null;
      {
        // Note: The following is done to avoid a v8 performance cliff.
        //
        // Initializing the fields below to smis and later updating them with
        // double values will cause Fibers to end up having separate shapes.
        // This behavior/bug has something to do with Object.preventExtension().
        // Fortunately this only impacts DEV builds.
        // Unfortunately it makes React unusably slow for some applications.
        // To work around this, initialize the fields below with doubles.
        //
        // Learn more about this here:
        // https://github.com/facebook/react/issues/14365
        // https://bugs.chromium.org/p/v8/issues/detail?id=8538
        this.actualDuration = Number.NaN;
        this.actualStartTime = Number.NaN;
        this.selfBaseDuration = Number.NaN;
        this.treeBaseDuration = Number.NaN; // It's okay to replace the initial doubles with smis after initialization.
        // This won't trigger the performance cliff mentioned above,
        // and it simplifies other profiler code (including DevTools).

        this.actualDuration = 0;
        this.actualStartTime = -1;
        this.selfBaseDuration = 0;
        this.treeBaseDuration = 0;
      } // This is normally DEV-only except www when it adds listeners.
      // TODO: remove the User Timing integration in favor of Root Events.

      {
        this._debugID = debugCounter++;
        this._debugIsCurrentlyTiming = false;
      }
      {
        this._debugSource = null;
        this._debugOwner = null;
        this._debugNeedsRemount = false;
        this._debugHookTypes = null;

        if (!hasBadMapPolyfill && typeof Object.preventExtensions === 'function') {
          Object.preventExtensions(this);
        }
      }
    } // This is a constructor function, rather than a POJO constructor, still
    // please ensure we do the following:
    // 1) Nobody should add any instance methods on this. Instance methods can be
    //    more difficult to predict when they get optimized and they are almost
    //    never inlined properly in static compilers.
    // 2) Nobody should rely on `instanceof Fiber` for type testing. We should
    //    always know when it is a fiber.
    // 3) We might want to experiment with using numeric keys since they are easier
    //    to optimize in a non-JIT environment.
    // 4) We can easily go from a constructor to a createFiber object literal if that
    //    is faster.
    // 5) It should be easy to port this to a C struct and keep a C implementation
    //    compatible.


    var createFiber = function (tag, pendingProps, key, mode) {
      // $FlowFixMe: the shapes are exact here but Flow doesn't like constructors
      return new FiberNode(tag, pendingProps, key, mode);
    };

    function shouldConstruct(Component) {
      var prototype = Component.prototype;
      return !!(prototype && prototype.isReactComponent);
    }

    function isSimpleFunctionComponent(type) {
      return typeof type === 'function' && !shouldConstruct(type) && type.defaultProps === undefined;
    }

    function resolveLazyComponentTag(Component) {
      if (typeof Component === 'function') {
        return shouldConstruct(Component) ? ClassComponent : FunctionComponent;
      } else if (Component !== undefined && Component !== null) {
        var $$typeof = Component.$$typeof;

        if ($$typeof === REACT_FORWARD_REF_TYPE) {
          return ForwardRef;
        }

        if ($$typeof === REACT_MEMO_TYPE) {
          return MemoComponent;
        }
      }

      return IndeterminateComponent;
    } // This is used to create an alternate fiber to do work on.


    function createWorkInProgress(current, pendingProps) {
      var workInProgress = current.alternate;

      if (workInProgress === null) {
        // We use a double buffering pooling technique because we know that we'll
        // only ever need at most two versions of a tree. We pool the "other" unused
        // node that we're free to reuse. This is lazily created to avoid allocating
        // extra objects for things that are never updated. It also allow us to
        // reclaim the extra memory if needed.
        workInProgress = createFiber(current.tag, pendingProps, current.key, current.mode);
        workInProgress.elementType = current.elementType;
        workInProgress.type = current.type;
        workInProgress.stateNode = current.stateNode;
        {
          // DEV-only fields
          {
            workInProgress._debugID = current._debugID;
          }
          workInProgress._debugSource = current._debugSource;
          workInProgress._debugOwner = current._debugOwner;
          workInProgress._debugHookTypes = current._debugHookTypes;
        }
        workInProgress.alternate = current;
        current.alternate = workInProgress;
      } else {
        workInProgress.pendingProps = pendingProps; // We already have an alternate.
        // Reset the effect tag.

        workInProgress.effectTag = NoEffect; // The effect list is no longer valid.

        workInProgress.nextEffect = null;
        workInProgress.firstEffect = null;
        workInProgress.lastEffect = null;
        {
          // We intentionally reset, rather than copy, actualDuration & actualStartTime.
          // This prevents time from endlessly accumulating in new commits.
          // This has the downside of resetting values for different priority renders,
          // But works for yielding (the common case) and should support resuming.
          workInProgress.actualDuration = 0;
          workInProgress.actualStartTime = -1;
        }
      }

      workInProgress.childExpirationTime = current.childExpirationTime;
      workInProgress.expirationTime = current.expirationTime;
      workInProgress.child = current.child;
      workInProgress.memoizedProps = current.memoizedProps;
      workInProgress.memoizedState = current.memoizedState;
      workInProgress.updateQueue = current.updateQueue; // Clone the dependencies object. This is mutated during the render phase, so
      // it cannot be shared with the current fiber.

      var currentDependencies = current.dependencies;
      workInProgress.dependencies = currentDependencies === null ? null : {
        expirationTime: currentDependencies.expirationTime,
        firstContext: currentDependencies.firstContext,
        responders: currentDependencies.responders
      }; // These will be overridden during the parent's reconciliation

      workInProgress.sibling = current.sibling;
      workInProgress.index = current.index;
      workInProgress.ref = current.ref;
      {
        workInProgress.selfBaseDuration = current.selfBaseDuration;
        workInProgress.treeBaseDuration = current.treeBaseDuration;
      }
      {
        workInProgress._debugNeedsRemount = current._debugNeedsRemount;

        switch (workInProgress.tag) {
          case IndeterminateComponent:
          case FunctionComponent:
          case SimpleMemoComponent:
            workInProgress.type = resolveFunctionForHotReloading(current.type);
            break;

          case ClassComponent:
            workInProgress.type = resolveClassForHotReloading(current.type);
            break;

          case ForwardRef:
            workInProgress.type = resolveForwardRefForHotReloading(current.type);
            break;
        }
      }
      return workInProgress;
    } // Used to reuse a Fiber for a second pass.


    function resetWorkInProgress(workInProgress, renderExpirationTime) {
      // This resets the Fiber to what createFiber or createWorkInProgress would
      // have set the values to before during the first pass. Ideally this wouldn't
      // be necessary but unfortunately many code paths reads from the workInProgress
      // when they should be reading from current and writing to workInProgress.
      // We assume pendingProps, index, key, ref, return are still untouched to
      // avoid doing another reconciliation.
      // Reset the effect tag but keep any Placement tags, since that's something
      // that child fiber is setting, not the reconciliation.
      workInProgress.effectTag &= Placement; // The effect list is no longer valid.

      workInProgress.nextEffect = null;
      workInProgress.firstEffect = null;
      workInProgress.lastEffect = null;
      var current = workInProgress.alternate;

      if (current === null) {
        // Reset to createFiber's initial values.
        workInProgress.childExpirationTime = NoWork;
        workInProgress.expirationTime = renderExpirationTime;
        workInProgress.child = null;
        workInProgress.memoizedProps = null;
        workInProgress.memoizedState = null;
        workInProgress.updateQueue = null;
        workInProgress.dependencies = null;
        {
          // Note: We don't reset the actualTime counts. It's useful to accumulate
          // actual time across multiple render passes.
          workInProgress.selfBaseDuration = 0;
          workInProgress.treeBaseDuration = 0;
        }
      } else {
        // Reset to the cloned values that createWorkInProgress would've.
        workInProgress.childExpirationTime = current.childExpirationTime;
        workInProgress.expirationTime = current.expirationTime;
        workInProgress.child = current.child;
        workInProgress.memoizedProps = current.memoizedProps;
        workInProgress.memoizedState = current.memoizedState;
        workInProgress.updateQueue = current.updateQueue; // Clone the dependencies object. This is mutated during the render phase, so
        // it cannot be shared with the current fiber.

        var currentDependencies = current.dependencies;
        workInProgress.dependencies = currentDependencies === null ? null : {
          expirationTime: currentDependencies.expirationTime,
          firstContext: currentDependencies.firstContext,
          responders: currentDependencies.responders
        };
        {
          // Note: We don't reset the actualTime counts. It's useful to accumulate
          // actual time across multiple render passes.
          workInProgress.selfBaseDuration = current.selfBaseDuration;
          workInProgress.treeBaseDuration = current.treeBaseDuration;
        }
      }

      return workInProgress;
    }

    function createHostRootFiber(tag) {
      var mode;

      if (tag === ConcurrentRoot) {
        mode = ConcurrentMode | BlockingMode | StrictMode;
      } else if (tag === BlockingRoot) {
        mode = BlockingMode | StrictMode;
      } else {
        mode = NoMode;
      }

      if (isDevToolsPresent) {
        // Always collect profile timings when DevTools are present.
        // This enables DevTools to start capturing timing at any point–
        // Without some nodes in the tree having empty base times.
        mode |= ProfileMode;
      }

      return createFiber(HostRoot, null, null, mode);
    }

    function createFiberFromTypeAndProps(type, // React$ElementType
    key, pendingProps, owner, mode, expirationTime) {
      var fiber;
      var fiberTag = IndeterminateComponent; // The resolved type is set if we know what the final type will be. I.e. it's not lazy.

      var resolvedType = type;

      if (typeof type === 'function') {
        if (shouldConstruct(type)) {
          fiberTag = ClassComponent;
          {
            resolvedType = resolveClassForHotReloading(resolvedType);
          }
        } else {
          {
            resolvedType = resolveFunctionForHotReloading(resolvedType);
          }
        }
      } else if (typeof type === 'string') {
        fiberTag = HostComponent;
      } else {
        getTag: switch (type) {
          case REACT_FRAGMENT_TYPE:
            return createFiberFromFragment(pendingProps.children, mode, expirationTime, key);

          case REACT_CONCURRENT_MODE_TYPE:
            fiberTag = Mode;
            mode |= ConcurrentMode | BlockingMode | StrictMode;
            break;

          case REACT_STRICT_MODE_TYPE:
            fiberTag = Mode;
            mode |= StrictMode;
            break;

          case REACT_PROFILER_TYPE:
            return createFiberFromProfiler(pendingProps, mode, expirationTime, key);

          case REACT_SUSPENSE_TYPE:
            return createFiberFromSuspense(pendingProps, mode, expirationTime, key);

          case REACT_SUSPENSE_LIST_TYPE:
            return createFiberFromSuspenseList(pendingProps, mode, expirationTime, key);

          default:
            {
              if (typeof type === 'object' && type !== null) {
                switch (type.$$typeof) {
                  case REACT_PROVIDER_TYPE:
                    fiberTag = ContextProvider;
                    break getTag;

                  case REACT_CONTEXT_TYPE:
                    // This is a consumer
                    fiberTag = ContextConsumer;
                    break getTag;

                  case REACT_FORWARD_REF_TYPE:
                    fiberTag = ForwardRef;
                    {
                      resolvedType = resolveForwardRefForHotReloading(resolvedType);
                    }
                    break getTag;

                  case REACT_MEMO_TYPE:
                    fiberTag = MemoComponent;
                    break getTag;

                  case REACT_LAZY_TYPE:
                    fiberTag = LazyComponent;
                    resolvedType = null;
                    break getTag;

                  case REACT_BLOCK_TYPE:
                    fiberTag = Block;
                    break getTag;
                }
              }

              var info = '';
              {
                if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
                  info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and " + 'named imports.';
                }

                var ownerName = owner ? getComponentName(owner.type) : null;

                if (ownerName) {
                  info += '\n\nCheck the render method of `' + ownerName + '`.';
                }
              }
              {
                {
                  throw Error("Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: " + (type == null ? type : typeof type) + "." + info);
                }
              }
            }
        }
      }

      fiber = createFiber(fiberTag, pendingProps, key, mode);
      fiber.elementType = type;
      fiber.type = resolvedType;
      fiber.expirationTime = expirationTime;
      return fiber;
    }

    function createFiberFromElement(element, mode, expirationTime) {
      var owner = null;
      {
        owner = element._owner;
      }
      var type = element.type;
      var key = element.key;
      var pendingProps = element.props;
      var fiber = createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, expirationTime);
      {
        fiber._debugSource = element._source;
        fiber._debugOwner = element._owner;
      }
      return fiber;
    }

    function createFiberFromFragment(elements, mode, expirationTime, key) {
      var fiber = createFiber(Fragment, elements, key, mode);
      fiber.expirationTime = expirationTime;
      return fiber;
    }

    function createFiberFromProfiler(pendingProps, mode, expirationTime, key) {
      {
        if (typeof pendingProps.id !== 'string' || typeof pendingProps.onRender !== 'function') {
          error('Profiler must specify an "id" string and "onRender" function as props');
        }
      }
      var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode); // TODO: The Profiler fiber shouldn't have a type. It has a tag.

      fiber.elementType = REACT_PROFILER_TYPE;
      fiber.type = REACT_PROFILER_TYPE;
      fiber.expirationTime = expirationTime;
      return fiber;
    }

    function createFiberFromSuspense(pendingProps, mode, expirationTime, key) {
      var fiber = createFiber(SuspenseComponent, pendingProps, key, mode); // TODO: The SuspenseComponent fiber shouldn't have a type. It has a tag.
      // This needs to be fixed in getComponentName so that it relies on the tag
      // instead.

      fiber.type = REACT_SUSPENSE_TYPE;
      fiber.elementType = REACT_SUSPENSE_TYPE;
      fiber.expirationTime = expirationTime;
      return fiber;
    }

    function createFiberFromSuspenseList(pendingProps, mode, expirationTime, key) {
      var fiber = createFiber(SuspenseListComponent, pendingProps, key, mode);
      {
        // TODO: The SuspenseListComponent fiber shouldn't have a type. It has a tag.
        // This needs to be fixed in getComponentName so that it relies on the tag
        // instead.
        fiber.type = REACT_SUSPENSE_LIST_TYPE;
      }
      fiber.elementType = REACT_SUSPENSE_LIST_TYPE;
      fiber.expirationTime = expirationTime;
      return fiber;
    }

    function createFiberFromText(content, mode, expirationTime) {
      var fiber = createFiber(HostText, content, null, mode);
      fiber.expirationTime = expirationTime;
      return fiber;
    }

    function createFiberFromHostInstanceForDeletion() {
      var fiber = createFiber(HostComponent, null, null, NoMode); // TODO: These should not need a type.

      fiber.elementType = 'DELETED';
      fiber.type = 'DELETED';
      return fiber;
    }

    function createFiberFromPortal(portal, mode, expirationTime) {
      var pendingProps = portal.children !== null ? portal.children : [];
      var fiber = createFiber(HostPortal, pendingProps, portal.key, mode);
      fiber.expirationTime = expirationTime;
      fiber.stateNode = {
        containerInfo: portal.containerInfo,
        pendingChildren: null,
        // Used by persistent updates
        implementation: portal.implementation
      };
      return fiber;
    } // Used for stashing WIP properties to replay failed work in DEV.


    function assignFiberPropertiesInDEV(target, source) {
      if (target === null) {
        // This Fiber's initial properties will always be overwritten.
        // We only use a Fiber to ensure the same hidden class so DEV isn't slow.
        target = createFiber(IndeterminateComponent, null, null, NoMode);
      } // This is intentionally written as a list of all properties.
      // We tried to use Object.assign() instead but this is called in
      // the hottest path, and Object.assign() was too slow:
      // https://github.com/facebook/react/issues/12502
      // This code is DEV-only so size is not a concern.


      target.tag = source.tag;
      target.key = source.key;
      target.elementType = source.elementType;
      target.type = source.type;
      target.stateNode = source.stateNode;
      target.return = source.return;
      target.child = source.child;
      target.sibling = source.sibling;
      target.index = source.index;
      target.ref = source.ref;
      target.pendingProps = source.pendingProps;
      target.memoizedProps = source.memoizedProps;
      target.updateQueue = source.updateQueue;
      target.memoizedState = source.memoizedState;
      target.dependencies = source.dependencies;
      target.mode = source.mode;
      target.effectTag = source.effectTag;
      target.nextEffect = source.nextEffect;
      target.firstEffect = source.firstEffect;
      target.lastEffect = source.lastEffect;
      target.expirationTime = source.expirationTime;
      target.childExpirationTime = source.childExpirationTime;
      target.alternate = source.alternate;
      {
        target.actualDuration = source.actualDuration;
        target.actualStartTime = source.actualStartTime;
        target.selfBaseDuration = source.selfBaseDuration;
        target.treeBaseDuration = source.treeBaseDuration;
      }
      {
        target._debugID = source._debugID;
      }
      target._debugSource = source._debugSource;
      target._debugOwner = source._debugOwner;
      target._debugIsCurrentlyTiming = source._debugIsCurrentlyTiming;
      target._debugNeedsRemount = source._debugNeedsRemount;
      target._debugHookTypes = source._debugHookTypes;
      return target;
    }

    function FiberRootNode(containerInfo, tag, hydrate) {
      this.tag = tag;
      this.current = null;
      this.containerInfo = containerInfo;
      this.pendingChildren = null;
      this.pingCache = null;
      this.finishedExpirationTime = NoWork;
      this.finishedWork = null;
      this.timeoutHandle = noTimeout;
      this.context = null;
      this.pendingContext = null;
      this.hydrate = hydrate;
      this.callbackNode = null;
      this.callbackPriority = NoPriority;
      this.firstPendingTime = NoWork;
      this.firstSuspendedTime = NoWork;
      this.lastSuspendedTime = NoWork;
      this.nextKnownPendingLevel = NoWork;
      this.lastPingedTime = NoWork;
      this.lastExpiredTime = NoWork;
      {
        this.interactionThreadID = tracing.unstable_getThreadID();
        this.memoizedInteractions = new Set();
        this.pendingInteractionMap = new Map();
      }
    }

    function createFiberRoot(containerInfo, tag, hydrate, hydrationCallbacks) {
      var root = new FiberRootNode(containerInfo, tag, hydrate); // stateNode is any.

      var uninitializedFiber = createHostRootFiber(tag);
      root.current = uninitializedFiber;
      uninitializedFiber.stateNode = root;
      initializeUpdateQueue(uninitializedFiber);
      return root;
    }

    function isRootSuspendedAtTime(root, expirationTime) {
      var firstSuspendedTime = root.firstSuspendedTime;
      var lastSuspendedTime = root.lastSuspendedTime;
      return firstSuspendedTime !== NoWork && firstSuspendedTime >= expirationTime && lastSuspendedTime <= expirationTime;
    }

    function markRootSuspendedAtTime(root, expirationTime) {
      var firstSuspendedTime = root.firstSuspendedTime;
      var lastSuspendedTime = root.lastSuspendedTime;

      if (firstSuspendedTime < expirationTime) {
        root.firstSuspendedTime = expirationTime;
      }

      if (lastSuspendedTime > expirationTime || firstSuspendedTime === NoWork) {
        root.lastSuspendedTime = expirationTime;
      }

      if (expirationTime <= root.lastPingedTime) {
        root.lastPingedTime = NoWork;
      }

      if (expirationTime <= root.lastExpiredTime) {
        root.lastExpiredTime = NoWork;
      }
    }

    function markRootUpdatedAtTime(root, expirationTime) {
      // Update the range of pending times
      var firstPendingTime = root.firstPendingTime;

      if (expirationTime > firstPendingTime) {
        root.firstPendingTime = expirationTime;
      } // Update the range of suspended times. Treat everything lower priority or
      // equal to this update as unsuspended.


      var firstSuspendedTime = root.firstSuspendedTime;

      if (firstSuspendedTime !== NoWork) {
        if (expirationTime >= firstSuspendedTime) {
          // The entire suspended range is now unsuspended.
          root.firstSuspendedTime = root.lastSuspendedTime = root.nextKnownPendingLevel = NoWork;
        } else if (expirationTime >= root.lastSuspendedTime) {
          root.lastSuspendedTime = expirationTime + 1;
        } // This is a pending level. Check if it's higher priority than the next
        // known pending level.


        if (expirationTime > root.nextKnownPendingLevel) {
          root.nextKnownPendingLevel = expirationTime;
        }
      }
    }

    function markRootFinishedAtTime(root, finishedExpirationTime, remainingExpirationTime) {
      // Update the range of pending times
      root.firstPendingTime = remainingExpirationTime; // Update the range of suspended times. Treat everything higher priority or
      // equal to this update as unsuspended.

      if (finishedExpirationTime <= root.lastSuspendedTime) {
        // The entire suspended range is now unsuspended.
        root.firstSuspendedTime = root.lastSuspendedTime = root.nextKnownPendingLevel = NoWork;
      } else if (finishedExpirationTime <= root.firstSuspendedTime) {
        // Part of the suspended range is now unsuspended. Narrow the range to
        // include everything between the unsuspended time (non-inclusive) and the
        // last suspended time.
        root.firstSuspendedTime = finishedExpirationTime - 1;
      }

      if (finishedExpirationTime <= root.lastPingedTime) {
        // Clear the pinged time
        root.lastPingedTime = NoWork;
      }

      if (finishedExpirationTime <= root.lastExpiredTime) {
        // Clear the expired time
        root.lastExpiredTime = NoWork;
      }
    }

    function markRootExpiredAtTime(root, expirationTime) {
      var lastExpiredTime = root.lastExpiredTime;

      if (lastExpiredTime === NoWork || lastExpiredTime > expirationTime) {
        root.lastExpiredTime = expirationTime;
      }
    }

    var didWarnAboutNestedUpdates;
    var didWarnAboutFindNodeInStrictMode;
    {
      didWarnAboutNestedUpdates = false;
      didWarnAboutFindNodeInStrictMode = {};
    }

    function getContextForSubtree(parentComponent) {
      if (!parentComponent) {
        return emptyContextObject;
      }

      var fiber = get(parentComponent);
      var parentContext = findCurrentUnmaskedContext(fiber);

      if (fiber.tag === ClassComponent) {
        var Component = fiber.type;

        if (isContextProvider(Component)) {
          return processChildContext(fiber, Component, parentContext);
        }
      }

      return parentContext;
    }

    function findHostInstanceWithWarning(component, methodName) {
      {
        var fiber = get(component);

        if (fiber === undefined) {
          if (typeof component.render === 'function') {
            {
              {
                throw Error("Unable to find node on an unmounted component.");
              }
            }
          } else {
            {
              {
                throw Error("Argument appears to not be a ReactComponent. Keys: " + Object.keys(component));
              }
            }
          }
        }

        var hostFiber = findCurrentHostFiber(fiber);

        if (hostFiber === null) {
          return null;
        }

        if (hostFiber.mode & StrictMode) {
          var componentName = getComponentName(fiber.type) || 'Component';

          if (!didWarnAboutFindNodeInStrictMode[componentName]) {
            didWarnAboutFindNodeInStrictMode[componentName] = true;

            if (fiber.mode & StrictMode) {
              error('%s is deprecated in StrictMode. ' + '%s was passed an instance of %s which is inside StrictMode. ' + 'Instead, add a ref directly to the element you want to reference. ' + 'Learn more about using refs safely here: ' + 'https://fb.me/react-strict-mode-find-node%s', methodName, methodName, componentName, getStackByFiberInDevAndProd(hostFiber));
            } else {
              error('%s is deprecated in StrictMode. ' + '%s was passed an instance of %s which renders StrictMode children. ' + 'Instead, add a ref directly to the element you want to reference. ' + 'Learn more about using refs safely here: ' + 'https://fb.me/react-strict-mode-find-node%s', methodName, methodName, componentName, getStackByFiberInDevAndProd(hostFiber));
            }
          }
        }

        return hostFiber.stateNode;
      }
    }

    function createContainer(containerInfo, tag, hydrate, hydrationCallbacks) {
      return createFiberRoot(containerInfo, tag, hydrate);
    }

    function updateContainer(element, container, parentComponent, callback) {
      {
        onScheduleRoot(container, element);
      }
      var current$1 = container.current;
      var currentTime = requestCurrentTimeForUpdate();
      {
        // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests
        if ('undefined' !== typeof jest) {
          warnIfUnmockedScheduler(current$1);
          warnIfNotScopedWithMatchingAct(current$1);
        }
      }
      var suspenseConfig = requestCurrentSuspenseConfig();
      var expirationTime = computeExpirationForFiber(currentTime, current$1, suspenseConfig);
      var context = getContextForSubtree(parentComponent);

      if (container.context === null) {
        container.context = context;
      } else {
        container.pendingContext = context;
      }

      {
        if (isRendering && current !== null && !didWarnAboutNestedUpdates) {
          didWarnAboutNestedUpdates = true;
          error('Render methods should be a pure function of props and state; ' + 'triggering nested component updates from render is not allowed. ' + 'If necessary, trigger nested updates in componentDidUpdate.\n\n' + 'Check the render method of %s.', getComponentName(current.type) || 'Unknown');
        }
      }
      var update = createUpdate(expirationTime, suspenseConfig); // Caution: React DevTools currently depends on this property
      // being called "element".

      update.payload = {
        element: element
      };
      callback = callback === undefined ? null : callback;

      if (callback !== null) {
        {
          if (typeof callback !== 'function') {
            error('render(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callback);
          }
        }
        update.callback = callback;
      }

      enqueueUpdate(current$1, update);
      scheduleWork(current$1, expirationTime);
      return expirationTime;
    }

    function getPublicRootInstance(container) {
      var containerFiber = container.current;

      if (!containerFiber.child) {
        return null;
      }

      switch (containerFiber.child.tag) {
        case HostComponent:
          return getPublicInstance(containerFiber.child.stateNode);

        default:
          return containerFiber.child.stateNode;
      }
    }

    function markRetryTimeImpl(fiber, retryTime) {
      var suspenseState = fiber.memoizedState;

      if (suspenseState !== null && suspenseState.dehydrated !== null) {
        if (suspenseState.retryTime < retryTime) {
          suspenseState.retryTime = retryTime;
        }
      }
    } // Increases the priority of thennables when they resolve within this boundary.


    function markRetryTimeIfNotHydrated(fiber, retryTime) {
      markRetryTimeImpl(fiber, retryTime);
      var alternate = fiber.alternate;

      if (alternate) {
        markRetryTimeImpl(alternate, retryTime);
      }
    }

    function attemptUserBlockingHydration$1(fiber) {
      if (fiber.tag !== SuspenseComponent) {
        // We ignore HostRoots here because we can't increase
        // their priority and they should not suspend on I/O,
        // since you have to wrap anything that might suspend in
        // Suspense.
        return;
      }

      var expTime = computeInteractiveExpiration(requestCurrentTimeForUpdate());
      scheduleWork(fiber, expTime);
      markRetryTimeIfNotHydrated(fiber, expTime);
    }

    function attemptContinuousHydration$1(fiber) {
      if (fiber.tag !== SuspenseComponent) {
        // We ignore HostRoots here because we can't increase
        // their priority and they should not suspend on I/O,
        // since you have to wrap anything that might suspend in
        // Suspense.
        return;
      }

      scheduleWork(fiber, ContinuousHydration);
      markRetryTimeIfNotHydrated(fiber, ContinuousHydration);
    }

    function attemptHydrationAtCurrentPriority$1(fiber) {
      if (fiber.tag !== SuspenseComponent) {
        // We ignore HostRoots here because we can't increase
        // their priority other than synchronously flush it.
        return;
      }

      var currentTime = requestCurrentTimeForUpdate();
      var expTime = computeExpirationForFiber(currentTime, fiber, null);
      scheduleWork(fiber, expTime);
      markRetryTimeIfNotHydrated(fiber, expTime);
    }

    function findHostInstanceWithNoPortals(fiber) {
      var hostFiber = findCurrentHostFiberWithNoPortals(fiber);

      if (hostFiber === null) {
        return null;
      }

      if (hostFiber.tag === FundamentalComponent) {
        return hostFiber.stateNode.instance;
      }

      return hostFiber.stateNode;
    }

    var shouldSuspendImpl = function (fiber) {
      return false;
    };

    function shouldSuspend(fiber) {
      return shouldSuspendImpl(fiber);
    }

    var overrideHookState = null;
    var overrideProps = null;
    var scheduleUpdate = null;
    var setSuspenseHandler = null;
    {
      var copyWithSetImpl = function (obj, path, idx, value) {
        if (idx >= path.length) {
          return value;
        }

        var key = path[idx];
        var updated = Array.isArray(obj) ? obj.slice() : _assign({}, obj); // $FlowFixMe number or string is fine here

        updated[key] = copyWithSetImpl(obj[key], path, idx + 1, value);
        return updated;
      };

      var copyWithSet = function (obj, path, value) {
        return copyWithSetImpl(obj, path, 0, value);
      }; // Support DevTools editable values for useState and useReducer.


      overrideHookState = function (fiber, id, path, value) {
        // For now, the "id" of stateful hooks is just the stateful hook index.
        // This may change in the future with e.g. nested hooks.
        var currentHook = fiber.memoizedState;

        while (currentHook !== null && id > 0) {
          currentHook = currentHook.next;
          id--;
        }

        if (currentHook !== null) {
          var newState = copyWithSet(currentHook.memoizedState, path, value);
          currentHook.memoizedState = newState;
          currentHook.baseState = newState; // We aren't actually adding an update to the queue,
          // because there is no update we can add for useReducer hooks that won't trigger an error.
          // (There's no appropriate action type for DevTools overrides.)
          // As a result though, React will see the scheduled update as a noop and bailout.
          // Shallow cloning props works as a workaround for now to bypass the bailout check.

          fiber.memoizedProps = _assign({}, fiber.memoizedProps);
          scheduleWork(fiber, Sync);
        }
      }; // Support DevTools props for function components, forwardRef, memo, host components, etc.


      overrideProps = function (fiber, path, value) {
        fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value);

        if (fiber.alternate) {
          fiber.alternate.pendingProps = fiber.pendingProps;
        }

        scheduleWork(fiber, Sync);
      };

      scheduleUpdate = function (fiber) {
        scheduleWork(fiber, Sync);
      };

      setSuspenseHandler = function (newShouldSuspendImpl) {
        shouldSuspendImpl = newShouldSuspendImpl;
      };
    }

    function injectIntoDevTools(devToolsConfig) {
      var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance;
      var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
      return injectInternals(_assign({}, devToolsConfig, {
        overrideHookState: overrideHookState,
        overrideProps: overrideProps,
        setSuspenseHandler: setSuspenseHandler,
        scheduleUpdate: scheduleUpdate,
        currentDispatcherRef: ReactCurrentDispatcher,
        findHostInstanceByFiber: function (fiber) {
          var hostFiber = findCurrentHostFiber(fiber);

          if (hostFiber === null) {
            return null;
          }

          return hostFiber.stateNode;
        },
        findFiberByHostInstance: function (instance) {
          if (!findFiberByHostInstance) {
            // Might not be implemented by the renderer.
            return null;
          }

          return findFiberByHostInstance(instance);
        },
        // React Refresh
        findHostInstancesForRefresh: findHostInstancesForRefresh,
        scheduleRefresh: scheduleRefresh,
        scheduleRoot: scheduleRoot,
        setRefreshHandler: setRefreshHandler,
        // Enables DevTools to append owner stacks to error messages in DEV mode.
        getCurrentFiber: function () {
          return current;
        }
      }));
    }

    var IsSomeRendererActing$1 = ReactSharedInternals.IsSomeRendererActing;

    function ReactDOMRoot(container, options) {
      this._internalRoot = createRootImpl(container, ConcurrentRoot, options);
    }

    function ReactDOMBlockingRoot(container, tag, options) {
      this._internalRoot = createRootImpl(container, tag, options);
    }

    ReactDOMRoot.prototype.render = ReactDOMBlockingRoot.prototype.render = function (children) {
      var root = this._internalRoot;
      {
        if (typeof arguments[1] === 'function') {
          error('render(...): does not support the second callback argument. ' + 'To execute a side effect after rendering, declare it in a component body with useEffect().');
        }

        var container = root.containerInfo;

        if (container.nodeType !== COMMENT_NODE) {
          var hostInstance = findHostInstanceWithNoPortals(root.current);

          if (hostInstance) {
            if (hostInstance.parentNode !== container) {
              error('render(...): It looks like the React-rendered content of the ' + 'root container was removed without using React. This is not ' + 'supported and will cause errors. Instead, call ' + "root.unmount() to empty a root's container.");
            }
          }
        }
      }
      updateContainer(children, root, null, null);
    };

    ReactDOMRoot.prototype.unmount = ReactDOMBlockingRoot.prototype.unmount = function () {
      {
        if (typeof arguments[0] === 'function') {
          error('unmount(...): does not support a callback argument. ' + 'To execute a side effect after rendering, declare it in a component body with useEffect().');
        }
      }
      var root = this._internalRoot;
      var container = root.containerInfo;
      updateContainer(null, root, null, function () {
        unmarkContainerAsRoot(container);
      });
    };

    function createRootImpl(container, tag, options) {
      // Tag is either LegacyRoot or Concurrent Root
      var hydrate = options != null && options.hydrate === true;
      var hydrationCallbacks = options != null && options.hydrationOptions || null;
      var root = createContainer(container, tag, hydrate);
      markContainerAsRoot(root.current, container);

      if (hydrate && tag !== LegacyRoot) {
        var doc = container.nodeType === DOCUMENT_NODE ? container : container.ownerDocument;
        eagerlyTrapReplayableEvents(container, doc);
      }

      return root;
    }

    function createLegacyRoot(container, options) {
      return new ReactDOMBlockingRoot(container, LegacyRoot, options);
    }

    function isValidContainer(node) {
      return !!(node && (node.nodeType === ELEMENT_NODE || node.nodeType === DOCUMENT_NODE || node.nodeType === DOCUMENT_FRAGMENT_NODE || node.nodeType === COMMENT_NODE && node.nodeValue === ' react-mount-point-unstable '));
    }

    var ReactCurrentOwner$3 = ReactSharedInternals.ReactCurrentOwner;
    var topLevelUpdateWarnings;
    var warnedAboutHydrateAPI = false;
    {
      topLevelUpdateWarnings = function (container) {
        if (container._reactRootContainer && container.nodeType !== COMMENT_NODE) {
          var hostInstance = findHostInstanceWithNoPortals(container._reactRootContainer._internalRoot.current);

          if (hostInstance) {
            if (hostInstance.parentNode !== container) {
              error('render(...): It looks like the React-rendered content of this ' + 'container was removed without using React. This is not ' + 'supported and will cause errors. Instead, call ' + 'ReactDOM.unmountComponentAtNode to empty a container.');
            }
          }
        }

        var isRootRenderedBySomeReact = !!container._reactRootContainer;
        var rootEl = getReactRootElementInContainer(container);
        var hasNonRootReactChild = !!(rootEl && getInstanceFromNode$1(rootEl));

        if (hasNonRootReactChild && !isRootRenderedBySomeReact) {
          error('render(...): Replacing React-rendered children with a new root ' + 'component. If you intended to update the children of this node, ' + 'you should instead have the existing children update their state ' + 'and render the new components instead of calling ReactDOM.render.');
        }

        if (container.nodeType === ELEMENT_NODE && container.tagName && container.tagName.toUpperCase() === 'BODY') {
          error('render(): Rendering components directly into document.body is ' + 'discouraged, since its children are often manipulated by third-party ' + 'scripts and browser extensions. This may lead to subtle ' + 'reconciliation issues. Try rendering into a container element created ' + 'for your app.');
        }
      };
    }

    function getReactRootElementInContainer(container) {
      if (!container) {
        return null;
      }

      if (container.nodeType === DOCUMENT_NODE) {
        return container.documentElement;
      } else {
        return container.firstChild;
      }
    }

    function shouldHydrateDueToLegacyHeuristic(container) {
      var rootElement = getReactRootElementInContainer(container);
      return !!(rootElement && rootElement.nodeType === ELEMENT_NODE && rootElement.hasAttribute(ROOT_ATTRIBUTE_NAME));
    }

    function legacyCreateRootFromDOMContainer(container, forceHydrate) {
      var shouldHydrate = forceHydrate || shouldHydrateDueToLegacyHeuristic(container); // First clear any existing content.

      if (!shouldHydrate) {
        var warned = false;
        var rootSibling;

        while (rootSibling = container.lastChild) {
          {
            if (!warned && rootSibling.nodeType === ELEMENT_NODE && rootSibling.hasAttribute(ROOT_ATTRIBUTE_NAME)) {
              warned = true;
              error('render(): Target node has markup rendered by React, but there ' + 'are unrelated nodes as well. This is most commonly caused by ' + 'white-space inserted around server-rendered markup.');
            }
          }
          container.removeChild(rootSibling);
        }
      }

      {
        if (shouldHydrate && !forceHydrate && !warnedAboutHydrateAPI) {
          warnedAboutHydrateAPI = true;
          warn('render(): Calling ReactDOM.render() to hydrate server-rendered markup ' + 'will stop working in React v17. Replace the ReactDOM.render() call ' + 'with ReactDOM.hydrate() if you want React to attach to the server HTML.');
        }
      }
      return createLegacyRoot(container, shouldHydrate ? {
        hydrate: true
      } : undefined);
    }

    function warnOnInvalidCallback$1(callback, callerName) {
      {
        if (callback !== null && typeof callback !== 'function') {
          error('%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback);
        }
      }
    }

    function legacyRenderSubtreeIntoContainer(parentComponent, children, container, forceHydrate, callback) {
      {
        topLevelUpdateWarnings(container);
        warnOnInvalidCallback$1(callback === undefined ? null : callback, 'render');
      } // TODO: Without `any` type, Flow says "Property cannot be accessed on any
      // member of intersection type." Whyyyyyy.

      var root = container._reactRootContainer;
      var fiberRoot;

      if (!root) {
        // Initial mount
        root = container._reactRootContainer = legacyCreateRootFromDOMContainer(container, forceHydrate);
        fiberRoot = root._internalRoot;

        if (typeof callback === 'function') {
          var originalCallback = callback;

          callback = function () {
            var instance = getPublicRootInstance(fiberRoot);
            originalCallback.call(instance);
          };
        } // Initial mount should not be batched.


        unbatchedUpdates(function () {
          updateContainer(children, fiberRoot, parentComponent, callback);
        });
      } else {
        fiberRoot = root._internalRoot;

        if (typeof callback === 'function') {
          var _originalCallback = callback;

          callback = function () {
            var instance = getPublicRootInstance(fiberRoot);

            _originalCallback.call(instance);
          };
        } // Update


        updateContainer(children, fiberRoot, parentComponent, callback);
      }

      return getPublicRootInstance(fiberRoot);
    }

    function findDOMNode(componentOrElement) {
      {
        var owner = ReactCurrentOwner$3.current;

        if (owner !== null && owner.stateNode !== null) {
          var warnedAboutRefsInRender = owner.stateNode._warnedAboutRefsInRender;

          if (!warnedAboutRefsInRender) {
            error('%s is accessing findDOMNode inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', getComponentName(owner.type) || 'A component');
          }

          owner.stateNode._warnedAboutRefsInRender = true;
        }
      }

      if (componentOrElement == null) {
        return null;
      }

      if (componentOrElement.nodeType === ELEMENT_NODE) {
        return componentOrElement;
      }

      {
        return findHostInstanceWithWarning(componentOrElement, 'findDOMNode');
      }
    }

    function hydrate(element, container, callback) {
      if (!isValidContainer(container)) {
        {
          throw Error("Target container is not a DOM element.");
        }
      }

      {
        var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === undefined;

        if (isModernRoot) {
          error('You are calling ReactDOM.hydrate() on a container that was previously ' + 'passed to ReactDOM.createRoot(). This is not supported. ' + 'Did you mean to call createRoot(container, {hydrate: true}).render(element)?');
        }
      } // TODO: throw or warn if we couldn't hydrate?

      return legacyRenderSubtreeIntoContainer(null, element, container, true, callback);
    }

    function render(element, container, callback) {
      if (!isValidContainer(container)) {
        {
          throw Error("Target container is not a DOM element.");
        }
      }

      {
        var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === undefined;

        if (isModernRoot) {
          error('You are calling ReactDOM.render() on a container that was previously ' + 'passed to ReactDOM.createRoot(). This is not supported. ' + 'Did you mean to call root.render(element)?');
        }
      }
      return legacyRenderSubtreeIntoContainer(null, element, container, false, callback);
    }

    function unstable_renderSubtreeIntoContainer(parentComponent, element, containerNode, callback) {
      if (!isValidContainer(containerNode)) {
        {
          throw Error("Target container is not a DOM element.");
        }
      }

      if (!(parentComponent != null && has(parentComponent))) {
        {
          throw Error("parentComponent must be a valid React Component");
        }
      }

      return legacyRenderSubtreeIntoContainer(parentComponent, element, containerNode, false, callback);
    }

    function unmountComponentAtNode(container) {
      if (!isValidContainer(container)) {
        {
          throw Error("unmountComponentAtNode(...): Target container is not a DOM element.");
        }
      }

      {
        var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === undefined;

        if (isModernRoot) {
          error('You are calling ReactDOM.unmountComponentAtNode() on a container that was previously ' + 'passed to ReactDOM.createRoot(). This is not supported. Did you mean to call root.unmount()?');
        }
      }

      if (container._reactRootContainer) {
        {
          var rootEl = getReactRootElementInContainer(container);
          var renderedByDifferentReact = rootEl && !getInstanceFromNode$1(rootEl);

          if (renderedByDifferentReact) {
            error("unmountComponentAtNode(): The node you're attempting to unmount " + 'was rendered by another copy of React.');
          }
        } // Unmount should not be batched.

        unbatchedUpdates(function () {
          legacyRenderSubtreeIntoContainer(null, null, container, false, function () {
            // $FlowFixMe This should probably use `delete container._reactRootContainer`
            container._reactRootContainer = null;
            unmarkContainerAsRoot(container);
          });
        }); // If you call unmountComponentAtNode twice in quick succession, you'll
        // get `true` twice. That's probably fine?

        return true;
      } else {
        {
          var _rootEl = getReactRootElementInContainer(container);

          var hasNonRootReactChild = !!(_rootEl && getInstanceFromNode$1(_rootEl)); // Check if the container itself is a React root node.

          var isContainerReactRoot = container.nodeType === ELEMENT_NODE && isValidContainer(container.parentNode) && !!container.parentNode._reactRootContainer;

          if (hasNonRootReactChild) {
            error("unmountComponentAtNode(): The node you're attempting to unmount " + 'was rendered by React and is not a top-level container. %s', isContainerReactRoot ? 'You may have accidentally passed in a React root node instead ' + 'of its container.' : 'Instead, have the parent component update its state and ' + 'rerender in order to remove this component.');
          }
        }
        return false;
      }
    }

    function createPortal(children, containerInfo, // TODO: figure out the API for cross-renderer implementation.
    implementation) {
      var key = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
      return {
        // This tag allow us to uniquely identify this as a React Portal
        $$typeof: REACT_PORTAL_TYPE,
        key: key == null ? null : '' + key,
        children: children,
        containerInfo: containerInfo,
        implementation: implementation
      };
    }

    var ReactVersion = '16.13.1';
    setAttemptUserBlockingHydration(attemptUserBlockingHydration$1);
    setAttemptContinuousHydration(attemptContinuousHydration$1);
    setAttemptHydrationAtCurrentPriority(attemptHydrationAtCurrentPriority$1);
    var didWarnAboutUnstableCreatePortal = false;
    {
      if (typeof Map !== 'function' || // $FlowIssue Flow incorrectly thinks Map has no prototype
      Map.prototype == null || typeof Map.prototype.forEach !== 'function' || typeof Set !== 'function' || // $FlowIssue Flow incorrectly thinks Set has no prototype
      Set.prototype == null || typeof Set.prototype.clear !== 'function' || typeof Set.prototype.forEach !== 'function') {
        error('React depends on Map and Set built-in types. Make sure that you load a ' + 'polyfill in older browsers. https://fb.me/react-polyfills');
      }
    }
    setRestoreImplementation(restoreControlledState$3);
    setBatchingImplementation(batchedUpdates$1, discreteUpdates$1, flushDiscreteUpdates, batchedEventUpdates$1);

    function createPortal$1(children, container) {
      var key = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;

      if (!isValidContainer(container)) {
        {
          throw Error("Target container is not a DOM element.");
        }
      } // TODO: pass ReactDOM portal implementation as third argument
      // $FlowFixMe The Flow type is opaque but there's no way to actually create it.


      return createPortal(children, container, null, key);
    }

    function renderSubtreeIntoContainer(parentComponent, element, containerNode, callback) {
      return unstable_renderSubtreeIntoContainer(parentComponent, element, containerNode, callback);
    }

    function unstable_createPortal(children, container) {
      var key = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
      {
        if (!didWarnAboutUnstableCreatePortal) {
          didWarnAboutUnstableCreatePortal = true;
          warn('The ReactDOM.unstable_createPortal() alias has been deprecated, ' + 'and will be removed in React 17+. Update your code to use ' + 'ReactDOM.createPortal() instead. It has the exact same API, ' + 'but without the "unstable_" prefix.');
        }
      }
      return createPortal$1(children, container, key);
    }

    var Internals = {
      // Keep in sync with ReactDOMUnstableNativeDependencies.js
      // ReactTestUtils.js, and ReactTestUtilsAct.js. This is an array for better minification.
      Events: [getInstanceFromNode$1, getNodeFromInstance$1, getFiberCurrentPropsFromNode$1, injectEventPluginsByName, eventNameDispatchConfigs, accumulateTwoPhaseDispatches, accumulateDirectDispatches, enqueueStateRestore, restoreStateIfNeeded, dispatchEvent, runEventsInBatch, flushPassiveEffects, IsThisRendererActing]
    };
    var foundDevTools = injectIntoDevTools({
      findFiberByHostInstance: getClosestInstanceFromNode,
      bundleType: 1,
      version: ReactVersion,
      rendererPackageName: 'react-dom'
    });
    {
      if (!foundDevTools && canUseDOM && window.top === window.self) {
        // If we're in Chrome or Firefox, provide a download link if not installed.
        if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) {
          var protocol = window.location.protocol; // Don't warn in exotic cases like chrome-extension://.

          if (/^(https?|file):$/.test(protocol)) {
            // eslint-disable-next-line react-internal/no-production-logging
            console.info('%cDownload the React DevTools ' + 'for a better development experience: ' + 'https://fb.me/react-devtools' + (protocol === 'file:' ? '\nYou might need to use a local HTTP server (instead of file://): ' + 'https://fb.me/react-devtools-faq' : ''), 'font-weight:bold');
          }
        }
      }
    }
    exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = Internals;
    exports.createPortal = createPortal$1;
    exports.findDOMNode = findDOMNode;
    exports.flushSync = flushSync;
    exports.hydrate = hydrate;
    exports.render = render;
    exports.unmountComponentAtNode = unmountComponentAtNode;
    exports.unstable_batchedUpdates = batchedUpdates$1;
    exports.unstable_createPortal = unstable_createPortal;
    exports.unstable_renderSubtreeIntoContainer = renderSubtreeIntoContainer;
    exports.version = ReactVersion;
  })();
}
},{"react":"../node_modules/react/index.js","object-assign":"../node_modules/object-assign/index.js","scheduler":"../node_modules/scheduler/index.js","prop-types/checkPropTypes":"../node_modules/prop-types/checkPropTypes.js","scheduler/tracing":"../node_modules/scheduler/tracing.js"}],"../node_modules/react-dom/index.js":[function(require,module,exports) {
'use strict';

function checkDCE() {
  /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
  if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined' || typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE !== 'function') {
    return;
  }

  if ("development" !== 'production') {
    // This branch is unreachable because this function is only called
    // in production, but the condition is true only in development.
    // Therefore if the branch is still here, dead code elimination wasn't
    // properly applied.
    // Don't change the message. React DevTools relies on it. Also make sure
    // this message doesn't occur elsewhere in this function, or it will cause
    // a false positive.
    throw new Error('^_^');
  }

  try {
    // Verify that the code above has been dead code eliminated (DCE'd).
    __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE);
  } catch (err) {
    // DevTools shouldn't crash React, no matter what.
    // We should still report in case we break this code.
    console.error(err);
  }
}

if ("development" === 'production') {
  // DCE check should happen before ReactDOM bundle executes so that
  // DevTools can report bad minification during injection.
  checkDCE();
  module.exports = require('./cjs/react-dom.production.min.js');
} else {
  module.exports = require('./cjs/react-dom.development.js');
}
},{"./cjs/react-dom.development.js":"../node_modules/react-dom/cjs/react-dom.development.js"}],"../node_modules/react-is/cjs/react-is.development.js":[function(require,module,exports) {
/** @license React v16.13.1
 * react-is.development.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
'use strict';

if ("development" !== "production") {
  (function () {
    'use strict'; // The Symbol used to tag the ReactElement-like types. If there is no native Symbol
    // nor polyfill, then a plain number is used for performance.

    var hasSymbol = typeof Symbol === 'function' && Symbol.for;
    var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;
    var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;
    var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;
    var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;
    var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;
    var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;
    var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; // TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary
    // (unstable) APIs that have been removed. Can we remove the symbols?

    var REACT_ASYNC_MODE_TYPE = hasSymbol ? Symbol.for('react.async_mode') : 0xeacf;
    var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;
    var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;
    var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;
    var REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for('react.suspense_list') : 0xead8;
    var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;
    var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;
    var REACT_BLOCK_TYPE = hasSymbol ? Symbol.for('react.block') : 0xead9;
    var REACT_FUNDAMENTAL_TYPE = hasSymbol ? Symbol.for('react.fundamental') : 0xead5;
    var REACT_RESPONDER_TYPE = hasSymbol ? Symbol.for('react.responder') : 0xead6;
    var REACT_SCOPE_TYPE = hasSymbol ? Symbol.for('react.scope') : 0xead7;

    function isValidElementType(type) {
      return typeof type === 'string' || typeof type === 'function' || // Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill.
      type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || typeof type === 'object' && type !== null && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_RESPONDER_TYPE || type.$$typeof === REACT_SCOPE_TYPE || type.$$typeof === REACT_BLOCK_TYPE);
    }

    function typeOf(object) {
      if (typeof object === 'object' && object !== null) {
        var $$typeof = object.$$typeof;

        switch ($$typeof) {
          case REACT_ELEMENT_TYPE:
            var type = object.type;

            switch (type) {
              case REACT_ASYNC_MODE_TYPE:
              case REACT_CONCURRENT_MODE_TYPE:
              case REACT_FRAGMENT_TYPE:
              case REACT_PROFILER_TYPE:
              case REACT_STRICT_MODE_TYPE:
              case REACT_SUSPENSE_TYPE:
                return type;

              default:
                var $$typeofType = type && type.$$typeof;

                switch ($$typeofType) {
                  case REACT_CONTEXT_TYPE:
                  case REACT_FORWARD_REF_TYPE:
                  case REACT_LAZY_TYPE:
                  case REACT_MEMO_TYPE:
                  case REACT_PROVIDER_TYPE:
                    return $$typeofType;

                  default:
                    return $$typeof;
                }

            }

          case REACT_PORTAL_TYPE:
            return $$typeof;
        }
      }

      return undefined;
    } // AsyncMode is deprecated along with isAsyncMode


    var AsyncMode = REACT_ASYNC_MODE_TYPE;
    var ConcurrentMode = REACT_CONCURRENT_MODE_TYPE;
    var ContextConsumer = REACT_CONTEXT_TYPE;
    var ContextProvider = REACT_PROVIDER_TYPE;
    var Element = REACT_ELEMENT_TYPE;
    var ForwardRef = REACT_FORWARD_REF_TYPE;
    var Fragment = REACT_FRAGMENT_TYPE;
    var Lazy = REACT_LAZY_TYPE;
    var Memo = REACT_MEMO_TYPE;
    var Portal = REACT_PORTAL_TYPE;
    var Profiler = REACT_PROFILER_TYPE;
    var StrictMode = REACT_STRICT_MODE_TYPE;
    var Suspense = REACT_SUSPENSE_TYPE;
    var hasWarnedAboutDeprecatedIsAsyncMode = false; // AsyncMode should be deprecated

    function isAsyncMode(object) {
      {
        if (!hasWarnedAboutDeprecatedIsAsyncMode) {
          hasWarnedAboutDeprecatedIsAsyncMode = true; // Using console['warn'] to evade Babel and ESLint

          console['warn']('The ReactIs.isAsyncMode() alias has been deprecated, ' + 'and will be removed in React 17+. Update your code to use ' + 'ReactIs.isConcurrentMode() instead. It has the exact same API.');
        }
      }
      return isConcurrentMode(object) || typeOf(object) === REACT_ASYNC_MODE_TYPE;
    }

    function isConcurrentMode(object) {
      return typeOf(object) === REACT_CONCURRENT_MODE_TYPE;
    }

    function isContextConsumer(object) {
      return typeOf(object) === REACT_CONTEXT_TYPE;
    }

    function isContextProvider(object) {
      return typeOf(object) === REACT_PROVIDER_TYPE;
    }

    function isElement(object) {
      return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
    }

    function isForwardRef(object) {
      return typeOf(object) === REACT_FORWARD_REF_TYPE;
    }

    function isFragment(object) {
      return typeOf(object) === REACT_FRAGMENT_TYPE;
    }

    function isLazy(object) {
      return typeOf(object) === REACT_LAZY_TYPE;
    }

    function isMemo(object) {
      return typeOf(object) === REACT_MEMO_TYPE;
    }

    function isPortal(object) {
      return typeOf(object) === REACT_PORTAL_TYPE;
    }

    function isProfiler(object) {
      return typeOf(object) === REACT_PROFILER_TYPE;
    }

    function isStrictMode(object) {
      return typeOf(object) === REACT_STRICT_MODE_TYPE;
    }

    function isSuspense(object) {
      return typeOf(object) === REACT_SUSPENSE_TYPE;
    }

    exports.AsyncMode = AsyncMode;
    exports.ConcurrentMode = ConcurrentMode;
    exports.ContextConsumer = ContextConsumer;
    exports.ContextProvider = ContextProvider;
    exports.Element = Element;
    exports.ForwardRef = ForwardRef;
    exports.Fragment = Fragment;
    exports.Lazy = Lazy;
    exports.Memo = Memo;
    exports.Portal = Portal;
    exports.Profiler = Profiler;
    exports.StrictMode = StrictMode;
    exports.Suspense = Suspense;
    exports.isAsyncMode = isAsyncMode;
    exports.isConcurrentMode = isConcurrentMode;
    exports.isContextConsumer = isContextConsumer;
    exports.isContextProvider = isContextProvider;
    exports.isElement = isElement;
    exports.isForwardRef = isForwardRef;
    exports.isFragment = isFragment;
    exports.isLazy = isLazy;
    exports.isMemo = isMemo;
    exports.isPortal = isPortal;
    exports.isProfiler = isProfiler;
    exports.isStrictMode = isStrictMode;
    exports.isSuspense = isSuspense;
    exports.isValidElementType = isValidElementType;
    exports.typeOf = typeOf;
  })();
}
},{}],"../node_modules/react-is/index.js":[function(require,module,exports) {
'use strict';

if ("development" === 'production') {
  module.exports = require('./cjs/react-is.production.min.js');
} else {
  module.exports = require('./cjs/react-is.development.js');
}
},{"./cjs/react-is.development.js":"../node_modules/react-is/cjs/react-is.development.js"}],"../node_modules/prop-types/factoryWithTypeCheckers.js":[function(require,module,exports) {
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
'use strict';

var ReactIs = require('react-is');

var assign = require('object-assign');

var ReactPropTypesSecret = require('./lib/ReactPropTypesSecret');

var checkPropTypes = require('./checkPropTypes');

var has = Function.call.bind(Object.prototype.hasOwnProperty);

var printWarning = function () {};

if ("development" !== 'production') {
  printWarning = function (text) {
    var message = 'Warning: ' + text;

    if (typeof console !== 'undefined') {
      console.error(message);
    }

    try {
      // --- Welcome to debugging React ---
      // This error was thrown as a convenience so that you can use this stack
      // to find the callsite that caused this warning to fire.
      throw new Error(message);
    } catch (x) {}
  };
}

function emptyFunctionThatReturnsNull() {
  return null;
}

module.exports = function (isValidElement, throwOnDirectAccess) {
  /* global Symbol */
  var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
  var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec.

  /**
   * Returns the iterator method function contained on the iterable object.
   *
   * Be sure to invoke the function with the iterable as context:
   *
   *     var iteratorFn = getIteratorFn(myIterable);
   *     if (iteratorFn) {
   *       var iterator = iteratorFn.call(myIterable);
   *       ...
   *     }
   *
   * @param {?object} maybeIterable
   * @return {?function}
   */

  function getIteratorFn(maybeIterable) {
    var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);

    if (typeof iteratorFn === 'function') {
      return iteratorFn;
    }
  }
  /**
   * Collection of methods that allow declaration and validation of props that are
   * supplied to React components. Example usage:
   *
   *   var Props = require('ReactPropTypes');
   *   var MyArticle = React.createClass({
   *     propTypes: {
   *       // An optional string prop named "description".
   *       description: Props.string,
   *
   *       // A required enum prop named "category".
   *       category: Props.oneOf(['News','Photos']).isRequired,
   *
   *       // A prop named "dialog" that requires an instance of Dialog.
   *       dialog: Props.instanceOf(Dialog).isRequired
   *     },
   *     render: function() { ... }
   *   });
   *
   * A more formal specification of how these methods are used:
   *
   *   type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...)
   *   decl := ReactPropTypes.{type}(.isRequired)?
   *
   * Each and every declaration produces a function with the same signature. This
   * allows the creation of custom validation functions. For example:
   *
   *  var MyLink = React.createClass({
   *    propTypes: {
   *      // An optional string or URI prop named "href".
   *      href: function(props, propName, componentName) {
   *        var propValue = props[propName];
   *        if (propValue != null && typeof propValue !== 'string' &&
   *            !(propValue instanceof URI)) {
   *          return new Error(
   *            'Expected a string or an URI for ' + propName + ' in ' +
   *            componentName
   *          );
   *        }
   *      }
   *    },
   *    render: function() {...}
   *  });
   *
   * @internal
   */


  var ANONYMOUS = '<<anonymous>>'; // Important!
  // Keep this list in sync with production version in `./factoryWithThrowingShims.js`.

  var ReactPropTypes = {
    array: createPrimitiveTypeChecker('array'),
    bool: createPrimitiveTypeChecker('boolean'),
    func: createPrimitiveTypeChecker('function'),
    number: createPrimitiveTypeChecker('number'),
    object: createPrimitiveTypeChecker('object'),
    string: createPrimitiveTypeChecker('string'),
    symbol: createPrimitiveTypeChecker('symbol'),
    any: createAnyTypeChecker(),
    arrayOf: createArrayOfTypeChecker,
    element: createElementTypeChecker(),
    elementType: createElementTypeTypeChecker(),
    instanceOf: createInstanceTypeChecker,
    node: createNodeChecker(),
    objectOf: createObjectOfTypeChecker,
    oneOf: createEnumTypeChecker,
    oneOfType: createUnionTypeChecker,
    shape: createShapeTypeChecker,
    exact: createStrictShapeTypeChecker
  };
  /**
   * inlined Object.is polyfill to avoid requiring consumers ship their own
   * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
   */

  /*eslint-disable no-self-compare*/

  function is(x, y) {
    // SameValue algorithm
    if (x === y) {
      // Steps 1-5, 7-10
      // Steps 6.b-6.e: +0 != -0
      return x !== 0 || 1 / x === 1 / y;
    } else {
      // Step 6.a: NaN == NaN
      return x !== x && y !== y;
    }
  }
  /*eslint-enable no-self-compare*/

  /**
   * We use an Error-like object for backward compatibility as people may call
   * PropTypes directly and inspect their output. However, we don't use real
   * Errors anymore. We don't inspect their stack anyway, and creating them
   * is prohibitively expensive if they are created too often, such as what
   * happens in oneOfType() for any type before the one that matched.
   */


  function PropTypeError(message) {
    this.message = message;
    this.stack = '';
  } // Make `instanceof Error` still work for returned errors.


  PropTypeError.prototype = Error.prototype;

  function createChainableTypeChecker(validate) {
    if ("development" !== 'production') {
      var manualPropTypeCallCache = {};
      var manualPropTypeWarningCount = 0;
    }

    function checkType(isRequired, props, propName, componentName, location, propFullName, secret) {
      componentName = componentName || ANONYMOUS;
      propFullName = propFullName || propName;

      if (secret !== ReactPropTypesSecret) {
        if (throwOnDirectAccess) {
          // New behavior only for users of `prop-types` package
          var err = new Error('Calling PropTypes validators directly is not supported by the `prop-types` package. ' + 'Use `PropTypes.checkPropTypes()` to call them. ' + 'Read more at http://fb.me/use-check-prop-types');
          err.name = 'Invariant Violation';
          throw err;
        } else if ("development" !== 'production' && typeof console !== 'undefined') {
          // Old behavior for people using React.PropTypes
          var cacheKey = componentName + ':' + propName;

          if (!manualPropTypeCallCache[cacheKey] && // Avoid spamming the console because they are often not actionable except for lib authors
          manualPropTypeWarningCount < 3) {
            printWarning('You are manually calling a React.PropTypes validation ' + 'function for the `' + propFullName + '` prop on `' + componentName + '`. This is deprecated ' + 'and will throw in the standalone `prop-types` package. ' + 'You may be seeing this warning due to a third-party PropTypes ' + 'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.');
            manualPropTypeCallCache[cacheKey] = true;
            manualPropTypeWarningCount++;
          }
        }
      }

      if (props[propName] == null) {
        if (isRequired) {
          if (props[propName] === null) {
            return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.'));
          }

          return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.'));
        }

        return null;
      } else {
        return validate(props, propName, componentName, location, propFullName);
      }
    }

    var chainedCheckType = checkType.bind(null, false);
    chainedCheckType.isRequired = checkType.bind(null, true);
    return chainedCheckType;
  }

  function createPrimitiveTypeChecker(expectedType) {
    function validate(props, propName, componentName, location, propFullName, secret) {
      var propValue = props[propName];
      var propType = getPropType(propValue);

      if (propType !== expectedType) {
        // `propValue` being instance of, say, date/regexp, pass the 'object'
        // check, but we can offer a more precise error message here rather than
        // 'of type `object`'.
        var preciseType = getPreciseType(propValue);
        return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.'));
      }

      return null;
    }

    return createChainableTypeChecker(validate);
  }

  function createAnyTypeChecker() {
    return createChainableTypeChecker(emptyFunctionThatReturnsNull);
  }

  function createArrayOfTypeChecker(typeChecker) {
    function validate(props, propName, componentName, location, propFullName) {
      if (typeof typeChecker !== 'function') {
        return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.');
      }

      var propValue = props[propName];

      if (!Array.isArray(propValue)) {
        var propType = getPropType(propValue);
        return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.'));
      }

      for (var i = 0; i < propValue.length; i++) {
        var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret);

        if (error instanceof Error) {
          return error;
        }
      }

      return null;
    }

    return createChainableTypeChecker(validate);
  }

  function createElementTypeChecker() {
    function validate(props, propName, componentName, location, propFullName) {
      var propValue = props[propName];

      if (!isValidElement(propValue)) {
        var propType = getPropType(propValue);
        return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.'));
      }

      return null;
    }

    return createChainableTypeChecker(validate);
  }

  function createElementTypeTypeChecker() {
    function validate(props, propName, componentName, location, propFullName) {
      var propValue = props[propName];

      if (!ReactIs.isValidElementType(propValue)) {
        var propType = getPropType(propValue);
        return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement type.'));
      }

      return null;
    }

    return createChainableTypeChecker(validate);
  }

  function createInstanceTypeChecker(expectedClass) {
    function validate(props, propName, componentName, location, propFullName) {
      if (!(props[propName] instanceof expectedClass)) {
        var expectedClassName = expectedClass.name || ANONYMOUS;
        var actualClassName = getClassName(props[propName]);
        return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.'));
      }

      return null;
    }

    return createChainableTypeChecker(validate);
  }

  function createEnumTypeChecker(expectedValues) {
    if (!Array.isArray(expectedValues)) {
      if ("development" !== 'production') {
        if (arguments.length > 1) {
          printWarning('Invalid arguments supplied to oneOf, expected an array, got ' + arguments.length + ' arguments. ' + 'A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z]).');
        } else {
          printWarning('Invalid argument supplied to oneOf, expected an array.');
        }
      }

      return emptyFunctionThatReturnsNull;
    }

    function validate(props, propName, componentName, location, propFullName) {
      var propValue = props[propName];

      for (var i = 0; i < expectedValues.length; i++) {
        if (is(propValue, expectedValues[i])) {
          return null;
        }
      }

      var valuesString = JSON.stringify(expectedValues, function replacer(key, value) {
        var type = getPreciseType(value);

        if (type === 'symbol') {
          return String(value);
        }

        return value;
      });
      return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + String(propValue) + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.'));
    }

    return createChainableTypeChecker(validate);
  }

  function createObjectOfTypeChecker(typeChecker) {
    function validate(props, propName, componentName, location, propFullName) {
      if (typeof typeChecker !== 'function') {
        return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.');
      }

      var propValue = props[propName];
      var propType = getPropType(propValue);

      if (propType !== 'object') {
        return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.'));
      }

      for (var key in propValue) {
        if (has(propValue, key)) {
          var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);

          if (error instanceof Error) {
            return error;
          }
        }
      }

      return null;
    }

    return createChainableTypeChecker(validate);
  }

  function createUnionTypeChecker(arrayOfTypeCheckers) {
    if (!Array.isArray(arrayOfTypeCheckers)) {
      "development" !== 'production' ? printWarning('Invalid argument supplied to oneOfType, expected an instance of array.') : void 0;
      return emptyFunctionThatReturnsNull;
    }

    for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
      var checker = arrayOfTypeCheckers[i];

      if (typeof checker !== 'function') {
        printWarning('Invalid argument supplied to oneOfType. Expected an array of check functions, but ' + 'received ' + getPostfixForTypeWarning(checker) + ' at index ' + i + '.');
        return emptyFunctionThatReturnsNull;
      }
    }

    function validate(props, propName, componentName, location, propFullName) {
      for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
        var checker = arrayOfTypeCheckers[i];

        if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret) == null) {
          return null;
        }
      }

      return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.'));
    }

    return createChainableTypeChecker(validate);
  }

  function createNodeChecker() {
    function validate(props, propName, componentName, location, propFullName) {
      if (!isNode(props[propName])) {
        return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.'));
      }

      return null;
    }

    return createChainableTypeChecker(validate);
  }

  function createShapeTypeChecker(shapeTypes) {
    function validate(props, propName, componentName, location, propFullName) {
      var propValue = props[propName];
      var propType = getPropType(propValue);

      if (propType !== 'object') {
        return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
      }

      for (var key in shapeTypes) {
        var checker = shapeTypes[key];

        if (!checker) {
          continue;
        }

        var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);

        if (error) {
          return error;
        }
      }

      return null;
    }

    return createChainableTypeChecker(validate);
  }

  function createStrictShapeTypeChecker(shapeTypes) {
    function validate(props, propName, componentName, location, propFullName) {
      var propValue = props[propName];
      var propType = getPropType(propValue);

      if (propType !== 'object') {
        return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
      } // We need to check all keys in case some are required but missing from
      // props.


      var allKeys = assign({}, props[propName], shapeTypes);

      for (var key in allKeys) {
        var checker = shapeTypes[key];

        if (!checker) {
          return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` key `' + key + '` supplied to `' + componentName + '`.' + '\nBad object: ' + JSON.stringify(props[propName], null, '  ') + '\nValid keys: ' + JSON.stringify(Object.keys(shapeTypes), null, '  '));
        }

        var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);

        if (error) {
          return error;
        }
      }

      return null;
    }

    return createChainableTypeChecker(validate);
  }

  function isNode(propValue) {
    switch (typeof propValue) {
      case 'number':
      case 'string':
      case 'undefined':
        return true;

      case 'boolean':
        return !propValue;

      case 'object':
        if (Array.isArray(propValue)) {
          return propValue.every(isNode);
        }

        if (propValue === null || isValidElement(propValue)) {
          return true;
        }

        var iteratorFn = getIteratorFn(propValue);

        if (iteratorFn) {
          var iterator = iteratorFn.call(propValue);
          var step;

          if (iteratorFn !== propValue.entries) {
            while (!(step = iterator.next()).done) {
              if (!isNode(step.value)) {
                return false;
              }
            }
          } else {
            // Iterator will provide entry [k,v] tuples rather than values.
            while (!(step = iterator.next()).done) {
              var entry = step.value;

              if (entry) {
                if (!isNode(entry[1])) {
                  return false;
                }
              }
            }
          }
        } else {
          return false;
        }

        return true;

      default:
        return false;
    }
  }

  function isSymbol(propType, propValue) {
    // Native Symbol.
    if (propType === 'symbol') {
      return true;
    } // falsy value can't be a Symbol


    if (!propValue) {
      return false;
    } // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol'


    if (propValue['@@toStringTag'] === 'Symbol') {
      return true;
    } // Fallback for non-spec compliant Symbols which are polyfilled.


    if (typeof Symbol === 'function' && propValue instanceof Symbol) {
      return true;
    }

    return false;
  } // Equivalent of `typeof` but with special handling for array and regexp.


  function getPropType(propValue) {
    var propType = typeof propValue;

    if (Array.isArray(propValue)) {
      return 'array';
    }

    if (propValue instanceof RegExp) {
      // Old webkits (at least until Android 4.0) return 'function' rather than
      // 'object' for typeof a RegExp. We'll normalize this here so that /bla/
      // passes PropTypes.object.
      return 'object';
    }

    if (isSymbol(propType, propValue)) {
      return 'symbol';
    }

    return propType;
  } // This handles more types than `getPropType`. Only used for error messages.
  // See `createPrimitiveTypeChecker`.


  function getPreciseType(propValue) {
    if (typeof propValue === 'undefined' || propValue === null) {
      return '' + propValue;
    }

    var propType = getPropType(propValue);

    if (propType === 'object') {
      if (propValue instanceof Date) {
        return 'date';
      } else if (propValue instanceof RegExp) {
        return 'regexp';
      }
    }

    return propType;
  } // Returns a string that is postfixed to a warning about an invalid type.
  // For example, "undefined" or "of type array"


  function getPostfixForTypeWarning(value) {
    var type = getPreciseType(value);

    switch (type) {
      case 'array':
      case 'object':
        return 'an ' + type;

      case 'boolean':
      case 'date':
      case 'regexp':
        return 'a ' + type;

      default:
        return type;
    }
  } // Returns class name of the object, if any.


  function getClassName(propValue) {
    if (!propValue.constructor || !propValue.constructor.name) {
      return ANONYMOUS;
    }

    return propValue.constructor.name;
  }

  ReactPropTypes.checkPropTypes = checkPropTypes;
  ReactPropTypes.resetWarningCache = checkPropTypes.resetWarningCache;
  ReactPropTypes.PropTypes = ReactPropTypes;
  return ReactPropTypes;
};
},{"react-is":"../node_modules/react-is/index.js","object-assign":"../node_modules/object-assign/index.js","./lib/ReactPropTypesSecret":"../node_modules/prop-types/lib/ReactPropTypesSecret.js","./checkPropTypes":"../node_modules/prop-types/checkPropTypes.js"}],"../node_modules/prop-types/index.js":[function(require,module,exports) {
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
if ("development" !== 'production') {
  var ReactIs = require('react-is'); // By explicitly using `prop-types` you are opting into new development behavior.
  // http://fb.me/prop-types-in-prod


  var throwOnDirectAccess = true;
  module.exports = require('./factoryWithTypeCheckers')(ReactIs.isElement, throwOnDirectAccess);
} else {
  // By explicitly using `prop-types` you are opting into new production behavior.
  // http://fb.me/prop-types-in-prod
  module.exports = require('./factoryWithThrowingShims')();
}
},{"react-is":"../node_modules/react-is/index.js","./factoryWithTypeCheckers":"../node_modules/prop-types/factoryWithTypeCheckers.js"}],"../node_modules/create-react-context/lib/index.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

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

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

function createEventEmitter(value) {
  var handlers = [];
  return {
    on: function on(handler) {
      handlers.push(handler);
    },
    off: function off(handler) {
      handlers = handlers.filter(function (h) {
        return h !== handler;
      });
    },
    get: function get() {
      return value;
    },
    set: function set(newValue) {
      value = newValue;
      handlers.forEach(function (handler) {
        return handler(value);
      });
    }
  };
}

function onlyChild(children) {
  return Array.isArray(children) ? children[0] : children;
}

var uniqueId = 0;

function createReactContext(defaultValue) {
  var _Provider$childContex, _Consumer$contextType;

  var contextProp = '__create-react-context-' + uniqueId++ + '__';

  var Provider = function (_Component) {
    _inherits(Provider, _Component);

    function Provider() {
      var _temp, _this, _ret;

      _classCallCheck(this, Provider);

      for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }

      return _ret = (_temp = (_this = _possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.emitter = createEventEmitter(_this.props.value), _temp), _possibleConstructorReturn(_this, _ret);
    }

    Provider.prototype.getChildContext = function getChildContext() {
      var _ref;

      return _ref = {}, _ref[contextProp] = this.emitter, _ref;
    };

    Provider.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
      if (this.props.value !== nextProps.value) {
        this.emitter.set(nextProps.value);
      }
    };

    Provider.prototype.render = function render() {
      return this.props.children;
    };

    return Provider;
  }(_react.Component);

  Provider.childContextTypes = (_Provider$childContex = {}, _Provider$childContex[contextProp] = _propTypes2.default.object.isRequired, _Provider$childContex);

  var Consumer = function (_Component2) {
    _inherits(Consumer, _Component2);

    function Consumer() {
      var _temp2, _this2, _ret2;

      _classCallCheck(this, Consumer);

      for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
        args[_key2] = arguments[_key2];
      }

      return _ret2 = (_temp2 = (_this2 = _possibleConstructorReturn(this, _Component2.call.apply(_Component2, [this].concat(args))), _this2), _this2.state = {
        value: _this2.getValue()
      }, _this2.onUpdate = function () {
        _this2.setState({
          value: _this2.getValue()
        });
      }, _temp2), _possibleConstructorReturn(_this2, _ret2);
    }

    Consumer.prototype.componentDidMount = function componentDidMount() {
      if (this.context[contextProp]) {
        this.context[contextProp].on(this.onUpdate);
      }
    };

    Consumer.prototype.componentWillUnmount = function componentWillUnmount() {
      if (this.context[contextProp]) {
        this.context[contextProp].off(this.onUpdate);
      }
    };

    Consumer.prototype.getValue = function getValue() {
      if (this.context[contextProp]) {
        return this.context[contextProp].get();
      } else {
        return defaultValue;
      }
    };

    Consumer.prototype.render = function render() {
      return onlyChild(this.props.children)(this.state.value);
    };

    return Consumer;
  }(_react.Component);

  Consumer.contextTypes = (_Consumer$contextType = {}, _Consumer$contextType[contextProp] = _propTypes2.default.object, _Consumer$contextType);


  return {
    Provider: Provider,
    Consumer: Consumer
  };
}

exports.default = createReactContext;
module.exports = exports['default'];
},{"react":"../node_modules/react/index.js","prop-types":"../node_modules/prop-types/index.js"}],"../node_modules/unstated/lib/unstated.es.js":[function(require,module,exports) {
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Provider = Provider;
exports.__SUPER_SECRET_CONTAINER_DEBUG_HOOK__ = __SUPER_SECRET_CONTAINER_DEBUG_HOOK__;
exports.Subscribe = exports.Container = void 0;

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

var _createReactContext = _interopRequireDefault(require("create-react-context"));

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

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
  return typeof obj;
} : function (obj) {
  return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};

function _possibleConstructorReturn(self, call) {
  if (!self) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }

  return call && (typeof call === "object" || typeof call === "function") ? call : self;
}

function _inherits(subClass, superClass) {
  if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
  }

  subClass.prototype = Object.create(superClass && superClass.prototype, {
    constructor: {
      value: subClass,
      enumerable: false,
      writable: true,
      configurable: true
    }
  });
  if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}

function _classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}

var StateContext = (0, _createReactContext.default)(null);

var Container = function () {
  function Container() {
    var _this = this;

    _classCallCheck(this, Container);

    this._listeners = [];
    CONTAINER_DEBUG_CALLBACKS.forEach(function (cb) {
      return cb(_this);
    });
  }

  Container.prototype.setState = function setState(updater, callback) {
    var _this2 = this;

    return Promise.resolve().then(function () {
      var nextState = void 0;

      if (typeof updater === 'function') {
        nextState = updater(_this2.state);
      } else {
        nextState = updater;
      }

      if (nextState == null) {
        if (callback) callback();
        return;
      }

      _this2.state = Object.assign({}, _this2.state, nextState);

      var promises = _this2._listeners.map(function (listener) {
        return listener();
      });

      return Promise.all(promises).then(function () {
        if (callback) {
          return callback();
        }
      });
    });
  };

  Container.prototype.subscribe = function subscribe(fn) {
    this._listeners.push(fn);
  };

  Container.prototype.unsubscribe = function unsubscribe(fn) {
    this._listeners = this._listeners.filter(function (f) {
      return f !== fn;
    });
  };

  return Container;
}();

exports.Container = Container;
var DUMMY_STATE = {};

var Subscribe = function (_React$Component) {
  _inherits(Subscribe, _React$Component);

  function Subscribe() {
    var _temp, _this3, _ret;

    _classCallCheck(this, Subscribe);

    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return _ret = (_temp = (_this3 = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this3), _this3.state = {}, _this3.instances = [], _this3.unmounted = false, _this3.onUpdate = function () {
      return new Promise(function (resolve) {
        if (!_this3.unmounted) {
          _this3.setState(DUMMY_STATE, resolve);
        } else {
          resolve();
        }
      });
    }, _temp), _possibleConstructorReturn(_this3, _ret);
  }

  Subscribe.prototype.componentWillUnmount = function componentWillUnmount() {
    this.unmounted = true;

    this._unsubscribe();
  };

  Subscribe.prototype._unsubscribe = function _unsubscribe() {
    var _this4 = this;

    this.instances.forEach(function (container) {
      container.unsubscribe(_this4.onUpdate);
    });
  };

  Subscribe.prototype._createInstances = function _createInstances(map, containers) {
    var _this5 = this;

    this._unsubscribe();

    if (map === null) {
      throw new Error('You must wrap your <Subscribe> components with a <Provider>');
    }

    var safeMap = map;
    var instances = containers.map(function (ContainerItem) {
      var instance = void 0;

      if ((typeof ContainerItem === 'undefined' ? 'undefined' : _typeof(ContainerItem)) === 'object' && ContainerItem instanceof Container) {
        instance = ContainerItem;
      } else {
        instance = safeMap.get(ContainerItem);

        if (!instance) {
          instance = new ContainerItem();
          safeMap.set(ContainerItem, instance);
        }
      }

      instance.unsubscribe(_this5.onUpdate);
      instance.subscribe(_this5.onUpdate);
      return instance;
    });
    this.instances = instances;
    return instances;
  };

  Subscribe.prototype.render = function render() {
    var _this6 = this;

    return _react.default.createElement(StateContext.Consumer, null, function (map) {
      return _this6.props.children.apply(null, _this6._createInstances(map, _this6.props.to));
    });
  };

  return Subscribe;
}(_react.default.Component);

exports.Subscribe = Subscribe;

function Provider(props) {
  return _react.default.createElement(StateContext.Consumer, null, function (parentMap) {
    var childMap = new Map(parentMap);

    if (props.inject) {
      props.inject.forEach(function (instance) {
        childMap.set(instance.constructor, instance);
      });
    }

    return _react.default.createElement(StateContext.Provider, {
      value: childMap
    }, props.children);
  });
}

var CONTAINER_DEBUG_CALLBACKS = []; // If your name isn't Sindre, this is not for you.
// I might ruin your day suddenly if you depend on this without talking to me.

function __SUPER_SECRET_CONTAINER_DEBUG_HOOK__(callback) {
  CONTAINER_DEBUG_CALLBACKS.push(callback);
}
},{"react":"../node_modules/react/index.js","create-react-context":"../node_modules/create-react-context/lib/index.js"}],"../src/state/global.js":[function(require,module,exports) {
"use strict";

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

var _unstated = require("unstated");

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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function () { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

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; }

var GlobalStateContainer = /*#__PURE__*/function (_Container) {
  _inherits(GlobalStateContainer, _Container);

  var _super = _createSuper(GlobalStateContainer);

  function GlobalStateContainer() {
    var _this;

    _classCallCheck(this, GlobalStateContainer);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _super.call.apply(_super, [this].concat(args));

    _defineProperty(_assertThisInitialized(_this), "state", {
      opened: false,
      tabIndex: "state",
      defaultSize: 0.5
    });

    _defineProperty(_assertThisInitialized(_this), "toggleDevTools", function () {
      var _this$state = _this.state,
          opened = _this$state.opened,
          defaultSize = _this$state.defaultSize;

      if (opened) {
        document.querySelector("html").style.marginBottom = "";
      } else {
        var size = defaultSize * window.innerHeight;
        document.querySelector("html").style.marginBottom = "".concat(size, "px");
      }

      _this.setState({
        opened: !opened
      });
    });

    _defineProperty(_assertThisInitialized(_this), "selectTab", function () {
      var tabIndex = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;

      _this.setState({
        tabIndex: tabIndex
      });
    });

    _defineProperty(_assertThisInitialized(_this), "updateBodyMargin", function (devToolsSize) {
      var size = devToolsSize * window.innerHeight;
      document.querySelector("html").style.marginBottom = "".concat(size, "px");
    });

    return _this;
  }

  return GlobalStateContainer;
}(_unstated.Container);

exports.default = GlobalStateContainer;
},{"unstated":"../node_modules/unstated/lib/unstated.es.js"}],"../node_modules/@babel/runtime/helpers/defineProperty.js":[function(require,module,exports) {
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;
}

module.exports = _defineProperty;
},{}],"../node_modules/@emotion/memoize/dist/memoize.browser.esm.js":[function(require,module,exports) {
"use strict";

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

function memoize(fn) {
  var cache = {};
  return function (arg) {
    if (cache[arg] === undefined) cache[arg] = fn(arg);
    return cache[arg];
  };
}

var _default = memoize;
exports.default = _default;
},{}],"../node_modules/@emotion/is-prop-valid/dist/is-prop-valid.browser.esm.js":[function(require,module,exports) {
"use strict";

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

var _memoize = _interopRequireDefault(require("@emotion/memoize"));

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

var reactPropsRegex = /^((children|dangerouslySetInnerHTML|key|ref|autoFocus|defaultValue|defaultChecked|innerHTML|suppressContentEditableWarning|suppressHydrationWarning|valueLink|accept|acceptCharset|accessKey|action|allow|allowUserMedia|allowPaymentRequest|allowFullScreen|allowTransparency|alt|async|autoComplete|autoPlay|capture|cellPadding|cellSpacing|challenge|charSet|checked|cite|classID|className|cols|colSpan|content|contentEditable|contextMenu|controls|controlsList|coords|crossOrigin|data|dateTime|decoding|default|defer|dir|disabled|disablePictureInPicture|download|draggable|encType|form|formAction|formEncType|formMethod|formNoValidate|formTarget|frameBorder|headers|height|hidden|high|href|hrefLang|htmlFor|httpEquiv|id|inputMode|integrity|is|keyParams|keyType|kind|label|lang|list|loading|loop|low|marginHeight|marginWidth|max|maxLength|media|mediaGroup|method|min|minLength|multiple|muted|name|nonce|noValidate|open|optimum|pattern|placeholder|playsInline|poster|preload|profile|radioGroup|readOnly|referrerPolicy|rel|required|reversed|role|rows|rowSpan|sandbox|scope|scoped|scrolling|seamless|selected|shape|size|sizes|slot|span|spellCheck|src|srcDoc|srcLang|srcSet|start|step|style|summary|tabIndex|target|title|type|useMap|value|width|wmode|wrap|about|datatype|inlist|prefix|property|resource|typeof|vocab|autoCapitalize|autoCorrect|autoSave|color|inert|itemProp|itemScope|itemType|itemID|itemRef|on|results|security|unselectable|accentHeight|accumulate|additive|alignmentBaseline|allowReorder|alphabetic|amplitude|arabicForm|ascent|attributeName|attributeType|autoReverse|azimuth|baseFrequency|baselineShift|baseProfile|bbox|begin|bias|by|calcMode|capHeight|clip|clipPathUnits|clipPath|clipRule|colorInterpolation|colorInterpolationFilters|colorProfile|colorRendering|contentScriptType|contentStyleType|cursor|cx|cy|d|decelerate|descent|diffuseConstant|direction|display|divisor|dominantBaseline|dur|dx|dy|edgeMode|elevation|enableBackground|end|exponent|externalResourcesRequired|fill|fillOpacity|fillRule|filter|filterRes|filterUnits|floodColor|floodOpacity|focusable|fontFamily|fontSize|fontSizeAdjust|fontStretch|fontStyle|fontVariant|fontWeight|format|from|fr|fx|fy|g1|g2|glyphName|glyphOrientationHorizontal|glyphOrientationVertical|glyphRef|gradientTransform|gradientUnits|hanging|horizAdvX|horizOriginX|ideographic|imageRendering|in|in2|intercept|k|k1|k2|k3|k4|kernelMatrix|kernelUnitLength|kerning|keyPoints|keySplines|keyTimes|lengthAdjust|letterSpacing|lightingColor|limitingConeAngle|local|markerEnd|markerMid|markerStart|markerHeight|markerUnits|markerWidth|mask|maskContentUnits|maskUnits|mathematical|mode|numOctaves|offset|opacity|operator|order|orient|orientation|origin|overflow|overlinePosition|overlineThickness|panose1|paintOrder|pathLength|patternContentUnits|patternTransform|patternUnits|pointerEvents|points|pointsAtX|pointsAtY|pointsAtZ|preserveAlpha|preserveAspectRatio|primitiveUnits|r|radius|refX|refY|renderingIntent|repeatCount|repeatDur|requiredExtensions|requiredFeatures|restart|result|rotate|rx|ry|scale|seed|shapeRendering|slope|spacing|specularConstant|specularExponent|speed|spreadMethod|startOffset|stdDeviation|stemh|stemv|stitchTiles|stopColor|stopOpacity|strikethroughPosition|strikethroughThickness|string|stroke|strokeDasharray|strokeDashoffset|strokeLinecap|strokeLinejoin|strokeMiterlimit|strokeOpacity|strokeWidth|surfaceScale|systemLanguage|tableValues|targetX|targetY|textAnchor|textDecoration|textRendering|textLength|to|transform|u1|u2|underlinePosition|underlineThickness|unicode|unicodeBidi|unicodeRange|unitsPerEm|vAlphabetic|vHanging|vIdeographic|vMathematical|values|vectorEffect|version|vertAdvY|vertOriginX|vertOriginY|viewBox|viewTarget|visibility|widths|wordSpacing|writingMode|x|xHeight|x1|x2|xChannelSelector|xlinkActuate|xlinkArcrole|xlinkHref|xlinkRole|xlinkShow|xlinkTitle|xlinkType|xmlBase|xmlns|xmlnsXlink|xmlLang|xmlSpace|y|y1|y2|yChannelSelector|z|zoomAndPan|for|class|autofocus)|(([Dd][Aa][Tt][Aa]|[Aa][Rr][Ii][Aa]|x)-.*))$/; // https://esbench.com/bench/5bfee68a4cd7e6009ef61d23

var index = (0, _memoize.default)(function (prop) {
  return reactPropsRegex.test(prop) || prop.charCodeAt(0) === 111
  /* o */
  && prop.charCodeAt(1) === 110
  /* n */
  && prop.charCodeAt(2) < 91;
}
/* Z+1 */
);
var _default = index;
exports.default = _default;
},{"@emotion/memoize":"../node_modules/@emotion/memoize/dist/memoize.browser.esm.js"}],"../node_modules/@babel/runtime/helpers/inheritsLoose.js":[function(require,module,exports) {
function _inheritsLoose(subClass, superClass) {
  subClass.prototype = Object.create(superClass.prototype);
  subClass.prototype.constructor = subClass;
  subClass.__proto__ = superClass;
}

module.exports = _inheritsLoose;
},{}],"../node_modules/@emotion/sheet/dist/sheet.browser.esm.js":[function(require,module,exports) {
"use strict";

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

/*

Based off glamor's StyleSheet, thanks Sunil ❤️

high performance StyleSheet for css-in-js systems

- uses multiple style tags behind the scenes for millions of rules
- uses `insertRule` for appending in production for *much* faster performance

// usage

import { StyleSheet } from '@emotion/sheet'

let styleSheet = new StyleSheet({ key: '', container: document.head })

styleSheet.insert('#box { border: 1px solid red; }')
- appends a css rule into the stylesheet

styleSheet.flush()
- empties the stylesheet of all its contents

*/
// $FlowFixMe
function sheetForTag(tag) {
  if (tag.sheet) {
    // $FlowFixMe
    return tag.sheet;
  } // this weirdness brought to you by firefox

  /* istanbul ignore next */


  for (var i = 0; i < document.styleSheets.length; i++) {
    if (document.styleSheets[i].ownerNode === tag) {
      // $FlowFixMe
      return document.styleSheets[i];
    }
  }
}

function createStyleElement(options) {
  var tag = document.createElement('style');
  tag.setAttribute('data-emotion', options.key);

  if (options.nonce !== undefined) {
    tag.setAttribute('nonce', options.nonce);
  }

  tag.appendChild(document.createTextNode(''));
  return tag;
}

var StyleSheet = /*#__PURE__*/function () {
  function StyleSheet(options) {
    this.isSpeedy = options.speedy === undefined ? "development" === 'production' : options.speedy;
    this.tags = [];
    this.ctr = 0;
    this.nonce = options.nonce; // key is the value of the data-emotion attribute, it's used to identify different sheets

    this.key = options.key;
    this.container = options.container;
    this.before = null;
  }

  var _proto = StyleSheet.prototype;

  _proto.insert = function insert(rule) {
    // the max length is how many rules we have per style tag, it's 65000 in speedy mode
    // it's 1 in dev because we insert source maps that map a single rule to a location
    // and you can only have one source map per style tag
    if (this.ctr % (this.isSpeedy ? 65000 : 1) === 0) {
      var _tag = createStyleElement(this);

      var before;

      if (this.tags.length === 0) {
        before = this.before;
      } else {
        before = this.tags[this.tags.length - 1].nextSibling;
      }

      this.container.insertBefore(_tag, before);
      this.tags.push(_tag);
    }

    var tag = this.tags[this.tags.length - 1];

    if (this.isSpeedy) {
      var sheet = sheetForTag(tag);

      try {
        // this is a really hot path
        // we check the second character first because having "i"
        // as the second character will happen less often than
        // having "@" as the first character
        var isImportRule = rule.charCodeAt(1) === 105 && rule.charCodeAt(0) === 64; // this is the ultrafast version, works across browsers
        // the big drawback is that the css won't be editable in devtools

        sheet.insertRule(rule, // we need to insert @import rules before anything else
        // otherwise there will be an error
        // technically this means that the @import rules will
        // _usually_(not always since there could be multiple style tags)
        // be the first ones in prod and generally later in dev
        // this shouldn't really matter in the real world though
        // @import is generally only used for font faces from google fonts and etc.
        // so while this could be technically correct then it would be slower and larger
        // for a tiny bit of correctness that won't matter in the real world
        isImportRule ? 0 : sheet.cssRules.length);
      } catch (e) {
        if ("development" !== 'production') {
          console.warn("There was a problem inserting the following rule: \"" + rule + "\"", e);
        }
      }
    } else {
      tag.appendChild(document.createTextNode(rule));
    }

    this.ctr++;
  };

  _proto.flush = function flush() {
    // $FlowFixMe
    this.tags.forEach(function (tag) {
      return tag.parentNode.removeChild(tag);
    });
    this.tags = [];
    this.ctr = 0;
  };

  return StyleSheet;
}();

exports.StyleSheet = StyleSheet;
},{}],"../node_modules/@emotion/stylis/dist/stylis.browser.esm.js":[function(require,module,exports) {
"use strict";

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

function stylis_min(W) {
  function M(d, c, e, h, a) {
    for (var m = 0, b = 0, v = 0, n = 0, q, g, x = 0, K = 0, k, u = k = q = 0, l = 0, r = 0, I = 0, t = 0, B = e.length, J = B - 1, y, f = '', p = '', F = '', G = '', C; l < B;) {
      g = e.charCodeAt(l);
      l === J && 0 !== b + n + v + m && (0 !== b && (g = 47 === b ? 10 : 47), n = v = m = 0, B++, J++);

      if (0 === b + n + v + m) {
        if (l === J && (0 < r && (f = f.replace(N, '')), 0 < f.trim().length)) {
          switch (g) {
            case 32:
            case 9:
            case 59:
            case 13:
            case 10:
              break;

            default:
              f += e.charAt(l);
          }

          g = 59;
        }

        switch (g) {
          case 123:
            f = f.trim();
            q = f.charCodeAt(0);
            k = 1;

            for (t = ++l; l < B;) {
              switch (g = e.charCodeAt(l)) {
                case 123:
                  k++;
                  break;

                case 125:
                  k--;
                  break;

                case 47:
                  switch (g = e.charCodeAt(l + 1)) {
                    case 42:
                    case 47:
                      a: {
                        for (u = l + 1; u < J; ++u) {
                          switch (e.charCodeAt(u)) {
                            case 47:
                              if (42 === g && 42 === e.charCodeAt(u - 1) && l + 2 !== u) {
                                l = u + 1;
                                break a;
                              }

                              break;

                            case 10:
                              if (47 === g) {
                                l = u + 1;
                                break a;
                              }

                          }
                        }

                        l = u;
                      }

                  }

                  break;

                case 91:
                  g++;

                case 40:
                  g++;

                case 34:
                case 39:
                  for (; l++ < J && e.charCodeAt(l) !== g;) {}

              }

              if (0 === k) break;
              l++;
            }

            k = e.substring(t, l);
            0 === q && (q = (f = f.replace(ca, '').trim()).charCodeAt(0));

            switch (q) {
              case 64:
                0 < r && (f = f.replace(N, ''));
                g = f.charCodeAt(1);

                switch (g) {
                  case 100:
                  case 109:
                  case 115:
                  case 45:
                    r = c;
                    break;

                  default:
                    r = O;
                }

                k = M(c, r, k, g, a + 1);
                t = k.length;
                0 < A && (r = X(O, f, I), C = H(3, k, r, c, D, z, t, g, a, h), f = r.join(''), void 0 !== C && 0 === (t = (k = C.trim()).length) && (g = 0, k = ''));
                if (0 < t) switch (g) {
                  case 115:
                    f = f.replace(da, ea);

                  case 100:
                  case 109:
                  case 45:
                    k = f + '{' + k + '}';
                    break;

                  case 107:
                    f = f.replace(fa, '$1 $2');
                    k = f + '{' + k + '}';
                    k = 1 === w || 2 === w && L('@' + k, 3) ? '@-webkit-' + k + '@' + k : '@' + k;
                    break;

                  default:
                    k = f + k, 112 === h && (k = (p += k, ''));
                } else k = '';
                break;

              default:
                k = M(c, X(c, f, I), k, h, a + 1);
            }

            F += k;
            k = I = r = u = q = 0;
            f = '';
            g = e.charCodeAt(++l);
            break;

          case 125:
          case 59:
            f = (0 < r ? f.replace(N, '') : f).trim();
            if (1 < (t = f.length)) switch (0 === u && (q = f.charCodeAt(0), 45 === q || 96 < q && 123 > q) && (t = (f = f.replace(' ', ':')).length), 0 < A && void 0 !== (C = H(1, f, c, d, D, z, p.length, h, a, h)) && 0 === (t = (f = C.trim()).length) && (f = '\x00\x00'), q = f.charCodeAt(0), g = f.charCodeAt(1), q) {
              case 0:
                break;

              case 64:
                if (105 === g || 99 === g) {
                  G += f + e.charAt(l);
                  break;
                }

              default:
                58 !== f.charCodeAt(t - 1) && (p += P(f, q, g, f.charCodeAt(2)));
            }
            I = r = u = q = 0;
            f = '';
            g = e.charCodeAt(++l);
        }
      }

      switch (g) {
        case 13:
        case 10:
          47 === b ? b = 0 : 0 === 1 + q && 107 !== h && 0 < f.length && (r = 1, f += '\x00');
          0 < A * Y && H(0, f, c, d, D, z, p.length, h, a, h);
          z = 1;
          D++;
          break;

        case 59:
        case 125:
          if (0 === b + n + v + m) {
            z++;
            break;
          }

        default:
          z++;
          y = e.charAt(l);

          switch (g) {
            case 9:
            case 32:
              if (0 === n + m + b) switch (x) {
                case 44:
                case 58:
                case 9:
                case 32:
                  y = '';
                  break;

                default:
                  32 !== g && (y = ' ');
              }
              break;

            case 0:
              y = '\\0';
              break;

            case 12:
              y = '\\f';
              break;

            case 11:
              y = '\\v';
              break;

            case 38:
              0 === n + b + m && (r = I = 1, y = '\f' + y);
              break;

            case 108:
              if (0 === n + b + m + E && 0 < u) switch (l - u) {
                case 2:
                  112 === x && 58 === e.charCodeAt(l - 3) && (E = x);

                case 8:
                  111 === K && (E = K);
              }
              break;

            case 58:
              0 === n + b + m && (u = l);
              break;

            case 44:
              0 === b + v + n + m && (r = 1, y += '\r');
              break;

            case 34:
            case 39:
              0 === b && (n = n === g ? 0 : 0 === n ? g : n);
              break;

            case 91:
              0 === n + b + v && m++;
              break;

            case 93:
              0 === n + b + v && m--;
              break;

            case 41:
              0 === n + b + m && v--;
              break;

            case 40:
              if (0 === n + b + m) {
                if (0 === q) switch (2 * x + 3 * K) {
                  case 533:
                    break;

                  default:
                    q = 1;
                }
                v++;
              }

              break;

            case 64:
              0 === b + v + n + m + u + k && (k = 1);
              break;

            case 42:
            case 47:
              if (!(0 < n + m + v)) switch (b) {
                case 0:
                  switch (2 * g + 3 * e.charCodeAt(l + 1)) {
                    case 235:
                      b = 47;
                      break;

                    case 220:
                      t = l, b = 42;
                  }

                  break;

                case 42:
                  47 === g && 42 === x && t + 2 !== l && (33 === e.charCodeAt(t + 2) && (p += e.substring(t, l + 1)), y = '', b = 0);
              }
          }

          0 === b && (f += y);
      }

      K = x;
      x = g;
      l++;
    }

    t = p.length;

    if (0 < t) {
      r = c;
      if (0 < A && (C = H(2, p, r, d, D, z, t, h, a, h), void 0 !== C && 0 === (p = C).length)) return G + p + F;
      p = r.join(',') + '{' + p + '}';

      if (0 !== w * E) {
        2 !== w || L(p, 2) || (E = 0);

        switch (E) {
          case 111:
            p = p.replace(ha, ':-moz-$1') + p;
            break;

          case 112:
            p = p.replace(Q, '::-webkit-input-$1') + p.replace(Q, '::-moz-$1') + p.replace(Q, ':-ms-input-$1') + p;
        }

        E = 0;
      }
    }

    return G + p + F;
  }

  function X(d, c, e) {
    var h = c.trim().split(ia);
    c = h;
    var a = h.length,
        m = d.length;

    switch (m) {
      case 0:
      case 1:
        var b = 0;

        for (d = 0 === m ? '' : d[0] + ' '; b < a; ++b) {
          c[b] = Z(d, c[b], e).trim();
        }

        break;

      default:
        var v = b = 0;

        for (c = []; b < a; ++b) {
          for (var n = 0; n < m; ++n) {
            c[v++] = Z(d[n] + ' ', h[b], e).trim();
          }
        }

    }

    return c;
  }

  function Z(d, c, e) {
    var h = c.charCodeAt(0);
    33 > h && (h = (c = c.trim()).charCodeAt(0));

    switch (h) {
      case 38:
        return c.replace(F, '$1' + d.trim());

      case 58:
        return d.trim() + c.replace(F, '$1' + d.trim());

      default:
        if (0 < 1 * e && 0 < c.indexOf('\f')) return c.replace(F, (58 === d.charCodeAt(0) ? '' : '$1') + d.trim());
    }

    return d + c;
  }

  function P(d, c, e, h) {
    var a = d + ';',
        m = 2 * c + 3 * e + 4 * h;

    if (944 === m) {
      d = a.indexOf(':', 9) + 1;
      var b = a.substring(d, a.length - 1).trim();
      b = a.substring(0, d).trim() + b + ';';
      return 1 === w || 2 === w && L(b, 1) ? '-webkit-' + b + b : b;
    }

    if (0 === w || 2 === w && !L(a, 1)) return a;

    switch (m) {
      case 1015:
        return 97 === a.charCodeAt(10) ? '-webkit-' + a + a : a;

      case 951:
        return 116 === a.charCodeAt(3) ? '-webkit-' + a + a : a;

      case 963:
        return 110 === a.charCodeAt(5) ? '-webkit-' + a + a : a;

      case 1009:
        if (100 !== a.charCodeAt(4)) break;

      case 969:
      case 942:
        return '-webkit-' + a + a;

      case 978:
        return '-webkit-' + a + '-moz-' + a + a;

      case 1019:
      case 983:
        return '-webkit-' + a + '-moz-' + a + '-ms-' + a + a;

      case 883:
        if (45 === a.charCodeAt(8)) return '-webkit-' + a + a;
        if (0 < a.indexOf('image-set(', 11)) return a.replace(ja, '$1-webkit-$2') + a;
        break;

      case 932:
        if (45 === a.charCodeAt(4)) switch (a.charCodeAt(5)) {
          case 103:
            return '-webkit-box-' + a.replace('-grow', '') + '-webkit-' + a + '-ms-' + a.replace('grow', 'positive') + a;

          case 115:
            return '-webkit-' + a + '-ms-' + a.replace('shrink', 'negative') + a;

          case 98:
            return '-webkit-' + a + '-ms-' + a.replace('basis', 'preferred-size') + a;
        }
        return '-webkit-' + a + '-ms-' + a + a;

      case 964:
        return '-webkit-' + a + '-ms-flex-' + a + a;

      case 1023:
        if (99 !== a.charCodeAt(8)) break;
        b = a.substring(a.indexOf(':', 15)).replace('flex-', '').replace('space-between', 'justify');
        return '-webkit-box-pack' + b + '-webkit-' + a + '-ms-flex-pack' + b + a;

      case 1005:
        return ka.test(a) ? a.replace(aa, ':-webkit-') + a.replace(aa, ':-moz-') + a : a;

      case 1e3:
        b = a.substring(13).trim();
        c = b.indexOf('-') + 1;

        switch (b.charCodeAt(0) + b.charCodeAt(c)) {
          case 226:
            b = a.replace(G, 'tb');
            break;

          case 232:
            b = a.replace(G, 'tb-rl');
            break;

          case 220:
            b = a.replace(G, 'lr');
            break;

          default:
            return a;
        }

        return '-webkit-' + a + '-ms-' + b + a;

      case 1017:
        if (-1 === a.indexOf('sticky', 9)) break;

      case 975:
        c = (a = d).length - 10;
        b = (33 === a.charCodeAt(c) ? a.substring(0, c) : a).substring(d.indexOf(':', 7) + 1).trim();

        switch (m = b.charCodeAt(0) + (b.charCodeAt(7) | 0)) {
          case 203:
            if (111 > b.charCodeAt(8)) break;

          case 115:
            a = a.replace(b, '-webkit-' + b) + ';' + a;
            break;

          case 207:
          case 102:
            a = a.replace(b, '-webkit-' + (102 < m ? 'inline-' : '') + 'box') + ';' + a.replace(b, '-webkit-' + b) + ';' + a.replace(b, '-ms-' + b + 'box') + ';' + a;
        }

        return a + ';';

      case 938:
        if (45 === a.charCodeAt(5)) switch (a.charCodeAt(6)) {
          case 105:
            return b = a.replace('-items', ''), '-webkit-' + a + '-webkit-box-' + b + '-ms-flex-' + b + a;

          case 115:
            return '-webkit-' + a + '-ms-flex-item-' + a.replace(ba, '') + a;

          default:
            return '-webkit-' + a + '-ms-flex-line-pack' + a.replace('align-content', '').replace(ba, '') + a;
        }
        break;

      case 973:
      case 989:
        if (45 !== a.charCodeAt(3) || 122 === a.charCodeAt(4)) break;

      case 931:
      case 953:
        if (!0 === la.test(d)) return 115 === (b = d.substring(d.indexOf(':') + 1)).charCodeAt(0) ? P(d.replace('stretch', 'fill-available'), c, e, h).replace(':fill-available', ':stretch') : a.replace(b, '-webkit-' + b) + a.replace(b, '-moz-' + b.replace('fill-', '')) + a;
        break;

      case 962:
        if (a = '-webkit-' + a + (102 === a.charCodeAt(5) ? '-ms-' + a : '') + a, 211 === e + h && 105 === a.charCodeAt(13) && 0 < a.indexOf('transform', 10)) return a.substring(0, a.indexOf(';', 27) + 1).replace(ma, '$1-webkit-$2') + a;
    }

    return a;
  }

  function L(d, c) {
    var e = d.indexOf(1 === c ? ':' : '{'),
        h = d.substring(0, 3 !== c ? e : 10);
    e = d.substring(e + 1, d.length - 1);
    return R(2 !== c ? h : h.replace(na, '$1'), e, c);
  }

  function ea(d, c) {
    var e = P(c, c.charCodeAt(0), c.charCodeAt(1), c.charCodeAt(2));
    return e !== c + ';' ? e.replace(oa, ' or ($1)').substring(4) : '(' + c + ')';
  }

  function H(d, c, e, h, a, m, b, v, n, q) {
    for (var g = 0, x = c, w; g < A; ++g) {
      switch (w = S[g].call(B, d, x, e, h, a, m, b, v, n, q)) {
        case void 0:
        case !1:
        case !0:
        case null:
          break;

        default:
          x = w;
      }
    }

    if (x !== c) return x;
  }

  function T(d) {
    switch (d) {
      case void 0:
      case null:
        A = S.length = 0;
        break;

      default:
        if ('function' === typeof d) S[A++] = d;else if ('object' === typeof d) for (var c = 0, e = d.length; c < e; ++c) {
          T(d[c]);
        } else Y = !!d | 0;
    }

    return T;
  }

  function U(d) {
    d = d.prefix;
    void 0 !== d && (R = null, d ? 'function' !== typeof d ? w = 1 : (w = 2, R = d) : w = 0);
    return U;
  }

  function B(d, c) {
    var e = d;
    33 > e.charCodeAt(0) && (e = e.trim());
    V = e;
    e = [V];

    if (0 < A) {
      var h = H(-1, c, e, e, D, z, 0, 0, 0, 0);
      void 0 !== h && 'string' === typeof h && (c = h);
    }

    var a = M(O, e, c, 0, 0);
    0 < A && (h = H(-2, a, e, e, D, z, a.length, 0, 0, 0), void 0 !== h && (a = h));
    V = '';
    E = 0;
    z = D = 1;
    return a;
  }

  var ca = /^\0+/g,
      N = /[\0\r\f]/g,
      aa = /: */g,
      ka = /zoo|gra/,
      ma = /([,: ])(transform)/g,
      ia = /,\r+?/g,
      F = /([\t\r\n ])*\f?&/g,
      fa = /@(k\w+)\s*(\S*)\s*/,
      Q = /::(place)/g,
      ha = /:(read-only)/g,
      G = /[svh]\w+-[tblr]{2}/,
      da = /\(\s*(.*)\s*\)/g,
      oa = /([\s\S]*?);/g,
      ba = /-self|flex-/g,
      na = /[^]*?(:[rp][el]a[\w-]+)[^]*/,
      la = /stretch|:\s*\w+\-(?:conte|avail)/,
      ja = /([^-])(image-set\()/,
      z = 1,
      D = 1,
      E = 0,
      w = 1,
      O = [],
      S = [],
      A = 0,
      R = null,
      Y = 0,
      V = '';
  B.use = T;
  B.set = U;
  void 0 !== W && U(W);
  return B;
}

var _default = stylis_min;
exports.default = _default;
},{}],"../node_modules/@emotion/weak-memoize/dist/weak-memoize.browser.esm.js":[function(require,module,exports) {
"use strict";

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

var weakMemoize = function weakMemoize(func) {
  // $FlowFixMe flow doesn't include all non-primitive types as allowed for weakmaps
  var cache = new WeakMap();
  return function (arg) {
    if (cache.has(arg)) {
      // $FlowFixMe
      return cache.get(arg);
    }

    var ret = func(arg);
    cache.set(arg, ret);
    return ret;
  };
};

var _default = weakMemoize;
exports.default = _default;
},{}],"../node_modules/@emotion/cache/dist/cache.browser.esm.js":[function(require,module,exports) {
"use strict";

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

var _sheet = require("@emotion/sheet");

var _stylis = _interopRequireDefault(require("@emotion/stylis"));

require("@emotion/weak-memoize");

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

// https://github.com/thysultan/stylis.js/tree/master/plugins/rule-sheet
// inlined to avoid umd wrapper and peerDep warnings/installing stylis
// since we use stylis after closure compiler
var delimiter = '/*|*/';
var needle = delimiter + '}';

function toSheet(block) {
  if (block) {
    Sheet.current.insert(block + '}');
  }
}

var Sheet = {
  current: null
};

var ruleSheet = function ruleSheet(context, content, selectors, parents, line, column, length, ns, depth, at) {
  switch (context) {
    // property
    case 1:
      {
        switch (content.charCodeAt(0)) {
          case 64:
            {
              // @import
              Sheet.current.insert(content + ';');
              return '';
            }
          // charcode for l

          case 108:
            {
              // charcode for b
              // this ignores label
              if (content.charCodeAt(2) === 98) {
                return '';
              }
            }
        }

        break;
      }
    // selector

    case 2:
      {
        if (ns === 0) return content + delimiter;
        break;
      }
    // at-rule

    case 3:
      {
        switch (ns) {
          // @font-face, @page
          case 102:
          case 112:
            {
              Sheet.current.insert(selectors[0] + content);
              return '';
            }

          default:
            {
              return content + (at === 0 ? delimiter : '');
            }
        }
      }

    case -2:
      {
        content.split(needle).forEach(toSheet);
      }
  }
};

var createCache = function createCache(options) {
  if (options === undefined) options = {};
  var key = options.key || 'css';
  var stylisOptions;

  if (options.prefix !== undefined) {
    stylisOptions = {
      prefix: options.prefix
    };
  }

  var stylis = new _stylis.default(stylisOptions);

  if ("development" !== 'production') {
    // $FlowFixMe
    if (/[^a-z-]/.test(key)) {
      throw new Error("Emotion key must only contain lower case alphabetical characters and - but \"" + key + "\" was passed");
    }
  }

  var inserted = {}; // $FlowFixMe

  var container;
  {
    container = options.container || document.head;
    var nodes = document.querySelectorAll("style[data-emotion-" + key + "]");
    Array.prototype.forEach.call(nodes, function (node) {
      var attrib = node.getAttribute("data-emotion-" + key); // $FlowFixMe

      attrib.split(' ').forEach(function (id) {
        inserted[id] = true;
      });

      if (node.parentNode !== container) {
        container.appendChild(node);
      }
    });
  }

  var _insert;

  {
    stylis.use(options.stylisPlugins)(ruleSheet);

    _insert = function insert(selector, serialized, sheet, shouldCache) {
      var name = serialized.name;
      Sheet.current = sheet;

      if ("development" !== 'production' && serialized.map !== undefined) {
        var map = serialized.map;
        Sheet.current = {
          insert: function insert(rule) {
            sheet.insert(rule + map);
          }
        };
      }

      stylis(selector, serialized.styles);

      if (shouldCache) {
        cache.inserted[name] = true;
      }
    };
  }

  if ("development" !== 'production') {
    // https://esbench.com/bench/5bf7371a4cd7e6009ef61d0a
    var commentStart = /\/\*/g;
    var commentEnd = /\*\//g;
    stylis.use(function (context, content) {
      switch (context) {
        case -1:
          {
            while (commentStart.test(content)) {
              commentEnd.lastIndex = commentStart.lastIndex;

              if (commentEnd.test(content)) {
                commentStart.lastIndex = commentEnd.lastIndex;
                continue;
              }

              throw new Error('Your styles have an unterminated comment ("/*" without corresponding "*/").');
            }

            commentStart.lastIndex = 0;
            break;
          }
      }
    });
    stylis.use(function (context, content, selectors) {
      switch (context) {
        case -1:
          {
            var flag = 'emotion-disable-server-rendering-unsafe-selector-warning-please-do-not-use-this-the-warning-exists-for-a-reason';
            var unsafePseudoClasses = content.match(/(:first|:nth|:nth-last)-child/g);

            if (unsafePseudoClasses && cache.compat !== true) {
              unsafePseudoClasses.forEach(function (unsafePseudoClass) {
                var ignoreRegExp = new RegExp(unsafePseudoClass + ".*\\/\\* " + flag + " \\*\\/");
                var ignore = ignoreRegExp.test(content);

                if (unsafePseudoClass && !ignore) {
                  console.error("The pseudo class \"" + unsafePseudoClass + "\" is potentially unsafe when doing server-side rendering. Try changing it to \"" + unsafePseudoClass.split('-child')[0] + "-of-type\".");
                }
              });
            }

            break;
          }
      }
    });
  }

  var cache = {
    key: key,
    sheet: new _sheet.StyleSheet({
      key: key,
      container: container,
      nonce: options.nonce,
      speedy: options.speedy
    }),
    nonce: options.nonce,
    inserted: inserted,
    registered: {},
    insert: _insert
  };
  return cache;
};

var _default = createCache;
exports.default = _default;
},{"@emotion/sheet":"../node_modules/@emotion/sheet/dist/sheet.browser.esm.js","@emotion/stylis":"../node_modules/@emotion/stylis/dist/stylis.browser.esm.js","@emotion/weak-memoize":"../node_modules/@emotion/weak-memoize/dist/weak-memoize.browser.esm.js"}],"../node_modules/@emotion/utils/dist/utils.browser.esm.js":[function(require,module,exports) {
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getRegisteredStyles = getRegisteredStyles;
exports.insertStyles = void 0;
var isBrowser = "object" !== 'undefined';

function getRegisteredStyles(registered, registeredStyles, classNames) {
  var rawClassName = '';
  classNames.split(' ').forEach(function (className) {
    if (registered[className] !== undefined) {
      registeredStyles.push(registered[className]);
    } else {
      rawClassName += className + " ";
    }
  });
  return rawClassName;
}

var insertStyles = function insertStyles(cache, serialized, isStringTag) {
  var className = cache.key + "-" + serialized.name;

  if ( // we only need to add the styles to the registered cache if the
  // class name could be used further down
  // the tree but if it's a string tag, we know it won't
  // so we don't have to add it to registered cache.
  // this improves memory usage since we can avoid storing the whole style string
  (isStringTag === false || // we need to always store it if we're in compat mode and
  // in node since emotion-server relies on whether a style is in
  // the registered cache to know whether a style is global or not
  // also, note that this check will be dead code eliminated in the browser
  isBrowser === false && cache.compat !== undefined) && cache.registered[className] === undefined) {
    cache.registered[className] = serialized.styles;
  }

  if (cache.inserted[serialized.name] === undefined) {
    var current = serialized;

    do {
      var maybeStyles = cache.insert("." + className, current, cache.sheet, true);
      current = current.next;
    } while (current !== undefined);
  }
};

exports.insertStyles = insertStyles;
},{}],"../node_modules/@emotion/hash/dist/hash.browser.esm.js":[function(require,module,exports) {
"use strict";

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

/* eslint-disable */
// Inspired by https://github.com/garycourt/murmurhash-js
// Ported from https://github.com/aappleby/smhasher/blob/61a0530f28277f2e850bfc39600ce61d02b518de/src/MurmurHash2.cpp#L37-L86
function murmur2(str) {
  // 'm' and 'r' are mixing constants generated offline.
  // They're not really 'magic', they just happen to work well.
  // const m = 0x5bd1e995;
  // const r = 24;
  // Initialize the hash
  var h = 0; // Mix 4 bytes at a time into the hash

  var k,
      i = 0,
      len = str.length;

  for (; len >= 4; ++i, len -= 4) {
    k = str.charCodeAt(i) & 0xff | (str.charCodeAt(++i) & 0xff) << 8 | (str.charCodeAt(++i) & 0xff) << 16 | (str.charCodeAt(++i) & 0xff) << 24;
    k =
    /* Math.imul(k, m): */
    (k & 0xffff) * 0x5bd1e995 + ((k >>> 16) * 0xe995 << 16);
    k ^=
    /* k >>> r: */
    k >>> 24;
    h =
    /* Math.imul(k, m): */
    (k & 0xffff) * 0x5bd1e995 + ((k >>> 16) * 0xe995 << 16) ^
    /* Math.imul(h, m): */
    (h & 0xffff) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16);
  } // Handle the last few bytes of the input array


  switch (len) {
    case 3:
      h ^= (str.charCodeAt(i + 2) & 0xff) << 16;

    case 2:
      h ^= (str.charCodeAt(i + 1) & 0xff) << 8;

    case 1:
      h ^= str.charCodeAt(i) & 0xff;
      h =
      /* Math.imul(h, m): */
      (h & 0xffff) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16);
  } // Do a few final mixes of the hash to ensure the last few
  // bytes are well-incorporated.


  h ^= h >>> 13;
  h =
  /* Math.imul(h, m): */
  (h & 0xffff) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16);
  return ((h ^ h >>> 15) >>> 0).toString(36);
}

var _default = murmur2;
exports.default = _default;
},{}],"../node_modules/@emotion/unitless/dist/unitless.browser.esm.js":[function(require,module,exports) {
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var unitlessKeys = {
  animationIterationCount: 1,
  borderImageOutset: 1,
  borderImageSlice: 1,
  borderImageWidth: 1,
  boxFlex: 1,
  boxFlexGroup: 1,
  boxOrdinalGroup: 1,
  columnCount: 1,
  columns: 1,
  flex: 1,
  flexGrow: 1,
  flexPositive: 1,
  flexShrink: 1,
  flexNegative: 1,
  flexOrder: 1,
  gridRow: 1,
  gridRowEnd: 1,
  gridRowSpan: 1,
  gridRowStart: 1,
  gridColumn: 1,
  gridColumnEnd: 1,
  gridColumnSpan: 1,
  gridColumnStart: 1,
  msGridRow: 1,
  msGridRowSpan: 1,
  msGridColumn: 1,
  msGridColumnSpan: 1,
  fontWeight: 1,
  lineHeight: 1,
  opacity: 1,
  order: 1,
  orphans: 1,
  tabSize: 1,
  widows: 1,
  zIndex: 1,
  zoom: 1,
  WebkitLineClamp: 1,
  // SVG-related properties
  fillOpacity: 1,
  floodOpacity: 1,
  stopOpacity: 1,
  strokeDasharray: 1,
  strokeDashoffset: 1,
  strokeMiterlimit: 1,
  strokeOpacity: 1,
  strokeWidth: 1
};
var _default = unitlessKeys;
exports.default = _default;
},{}],"../node_modules/@emotion/serialize/dist/serialize.browser.esm.js":[function(require,module,exports) {
"use strict";

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

var _hash = _interopRequireDefault(require("@emotion/hash"));

var _unitless = _interopRequireDefault(require("@emotion/unitless"));

var _memoize = _interopRequireDefault(require("@emotion/memoize"));

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

var ILLEGAL_ESCAPE_SEQUENCE_ERROR = "You have illegal escape sequence in your template literal, most likely inside content's property value.\nBecause you write your CSS inside a JavaScript string you actually have to do double escaping, so for example \"content: '\\00d7';\" should become \"content: '\\\\00d7';\".\nYou can read more about this here:\nhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#ES2018_revision_of_illegal_escape_sequences";
var UNDEFINED_AS_OBJECT_KEY_ERROR = "You have passed in falsy value as style object's key (can happen when in example you pass unexported component as computed key).";
var hyphenateRegex = /[A-Z]|^ms/g;
var animationRegex = /_EMO_([^_]+?)_([^]*?)_EMO_/g;

var isCustomProperty = function isCustomProperty(property) {
  return property.charCodeAt(1) === 45;
};

var isProcessableValue = function isProcessableValue(value) {
  return value != null && typeof value !== 'boolean';
};

var processStyleName = (0, _memoize.default)(function (styleName) {
  return isCustomProperty(styleName) ? styleName : styleName.replace(hyphenateRegex, '-$&').toLowerCase();
});

var processStyleValue = function processStyleValue(key, value) {
  switch (key) {
    case 'animation':
    case 'animationName':
      {
        if (typeof value === 'string') {
          return value.replace(animationRegex, function (match, p1, p2) {
            cursor = {
              name: p1,
              styles: p2,
              next: cursor
            };
            return p1;
          });
        }
      }
  }

  if (_unitless.default[key] !== 1 && !isCustomProperty(key) && typeof value === 'number' && value !== 0) {
    return value + 'px';
  }

  return value;
};

if ("development" !== 'production') {
  var contentValuePattern = /(attr|calc|counters?|url)\(/;
  var contentValues = ['normal', 'none', 'counter', 'open-quote', 'close-quote', 'no-open-quote', 'no-close-quote', 'initial', 'inherit', 'unset'];
  var oldProcessStyleValue = processStyleValue;
  var msPattern = /^-ms-/;
  var hyphenPattern = /-(.)/g;
  var hyphenatedCache = {};

  processStyleValue = function processStyleValue(key, value) {
    if (key === 'content') {
      if (typeof value !== 'string' || contentValues.indexOf(value) === -1 && !contentValuePattern.test(value) && (value.charAt(0) !== value.charAt(value.length - 1) || value.charAt(0) !== '"' && value.charAt(0) !== "'")) {
        console.error("You seem to be using a value for 'content' without quotes, try replacing it with `content: '\"" + value + "\"'`");
      }
    }

    var processed = oldProcessStyleValue(key, value);

    if (processed !== '' && !isCustomProperty(key) && key.indexOf('-') !== -1 && hyphenatedCache[key] === undefined) {
      hyphenatedCache[key] = true;
      console.error("Using kebab-case for css properties in objects is not supported. Did you mean " + key.replace(msPattern, 'ms-').replace(hyphenPattern, function (str, _char) {
        return _char.toUpperCase();
      }) + "?");
    }

    return processed;
  };
}

var shouldWarnAboutInterpolatingClassNameFromCss = true;

function handleInterpolation(mergedProps, registered, interpolation, couldBeSelectorInterpolation) {
  if (interpolation == null) {
    return '';
  }

  if (interpolation.__emotion_styles !== undefined) {
    if ("development" !== 'production' && interpolation.toString() === 'NO_COMPONENT_SELECTOR') {
      throw new Error('Component selectors can only be used in conjunction with babel-plugin-emotion.');
    }

    return interpolation;
  }

  switch (typeof interpolation) {
    case 'boolean':
      {
        return '';
      }

    case 'object':
      {
        if (interpolation.anim === 1) {
          cursor = {
            name: interpolation.name,
            styles: interpolation.styles,
            next: cursor
          };
          return interpolation.name;
        }

        if (interpolation.styles !== undefined) {
          var next = interpolation.next;

          if (next !== undefined) {
            // not the most efficient thing ever but this is a pretty rare case
            // and there will be very few iterations of this generally
            while (next !== undefined) {
              cursor = {
                name: next.name,
                styles: next.styles,
                next: cursor
              };
              next = next.next;
            }
          }

          var styles = interpolation.styles + ";";

          if ("development" !== 'production' && interpolation.map !== undefined) {
            styles += interpolation.map;
          }

          return styles;
        }

        return createStringFromObject(mergedProps, registered, interpolation);
      }

    case 'function':
      {
        if (mergedProps !== undefined) {
          var previousCursor = cursor;
          var result = interpolation(mergedProps);
          cursor = previousCursor;
          return handleInterpolation(mergedProps, registered, result, couldBeSelectorInterpolation);
        } else if ("development" !== 'production') {
          console.error('Functions that are interpolated in css calls will be stringified.\n' + 'If you want to have a css call based on props, create a function that returns a css call like this\n' + 'let dynamicStyle = (props) => css`color: ${props.color}`\n' + 'It can be called directly with props or interpolated in a styled call like this\n' + "let SomeComponent = styled('div')`${dynamicStyle}`");
        }

        break;
      }

    case 'string':
      if ("development" !== 'production') {
        var matched = [];
        var replaced = interpolation.replace(animationRegex, function (match, p1, p2) {
          var fakeVarName = "animation" + matched.length;
          matched.push("const " + fakeVarName + " = keyframes`" + p2.replace(/^@keyframes animation-\w+/, '') + "`");
          return "${" + fakeVarName + "}";
        });

        if (matched.length) {
          console.error('`keyframes` output got interpolated into plain string, please wrap it with `css`.\n\n' + 'Instead of doing this:\n\n' + [].concat(matched, ["`" + replaced + "`"]).join('\n') + '\n\nYou should wrap it with `css` like this:\n\n' + ("css`" + replaced + "`"));
        }
      }

      break;
  } // finalize string values (regular strings and functions interpolated into css calls)


  if (registered == null) {
    return interpolation;
  }

  var cached = registered[interpolation];

  if ("development" !== 'production' && couldBeSelectorInterpolation && shouldWarnAboutInterpolatingClassNameFromCss && cached !== undefined) {
    console.error('Interpolating a className from css`` is not recommended and will cause problems with composition.\n' + 'Interpolating a className from css`` will be completely unsupported in a future major version of Emotion');
    shouldWarnAboutInterpolatingClassNameFromCss = false;
  }

  return cached !== undefined && !couldBeSelectorInterpolation ? cached : interpolation;
}

function createStringFromObject(mergedProps, registered, obj) {
  var string = '';

  if (Array.isArray(obj)) {
    for (var i = 0; i < obj.length; i++) {
      string += handleInterpolation(mergedProps, registered, obj[i], false);
    }
  } else {
    for (var _key in obj) {
      var value = obj[_key];

      if (typeof value !== 'object') {
        if (registered != null && registered[value] !== undefined) {
          string += _key + "{" + registered[value] + "}";
        } else if (isProcessableValue(value)) {
          string += processStyleName(_key) + ":" + processStyleValue(_key, value) + ";";
        }
      } else {
        if (_key === 'NO_COMPONENT_SELECTOR' && "development" !== 'production') {
          throw new Error('Component selectors can only be used in conjunction with babel-plugin-emotion.');
        }

        if (Array.isArray(value) && typeof value[0] === 'string' && (registered == null || registered[value[0]] === undefined)) {
          for (var _i = 0; _i < value.length; _i++) {
            if (isProcessableValue(value[_i])) {
              string += processStyleName(_key) + ":" + processStyleValue(_key, value[_i]) + ";";
            }
          }
        } else {
          var interpolated = handleInterpolation(mergedProps, registered, value, false);

          switch (_key) {
            case 'animation':
            case 'animationName':
              {
                string += processStyleName(_key) + ":" + interpolated + ";";
                break;
              }

            default:
              {
                if ("development" !== 'production' && _key === 'undefined') {
                  console.error(UNDEFINED_AS_OBJECT_KEY_ERROR);
                }

                string += _key + "{" + interpolated + "}";
              }
          }
        }
      }
    }
  }

  return string;
}

var labelPattern = /label:\s*([^\s;\n{]+)\s*;/g;
var sourceMapPattern;

if ("development" !== 'production') {
  sourceMapPattern = /\/\*#\ssourceMappingURL=data:application\/json;\S+\s+\*\//;
} // this is the cursor for keyframes
// keyframes are stored on the SerializedStyles object as a linked list


var cursor;

var serializeStyles = function serializeStyles(args, registered, mergedProps) {
  if (args.length === 1 && typeof args[0] === 'object' && args[0] !== null && args[0].styles !== undefined) {
    return args[0];
  }

  var stringMode = true;
  var styles = '';
  cursor = undefined;
  var strings = args[0];

  if (strings == null || strings.raw === undefined) {
    stringMode = false;
    styles += handleInterpolation(mergedProps, registered, strings, false);
  } else {
    if ("development" !== 'production' && strings[0] === undefined) {
      console.error(ILLEGAL_ESCAPE_SEQUENCE_ERROR);
    }

    styles += strings[0];
  } // we start at 1 since we've already handled the first arg


  for (var i = 1; i < args.length; i++) {
    styles += handleInterpolation(mergedProps, registered, args[i], styles.charCodeAt(styles.length - 1) === 46);

    if (stringMode) {
      if ("development" !== 'production' && strings[i] === undefined) {
        console.error(ILLEGAL_ESCAPE_SEQUENCE_ERROR);
      }

      styles += strings[i];
    }
  }

  var sourceMap;

  if ("development" !== 'production') {
    styles = styles.replace(sourceMapPattern, function (match) {
      sourceMap = match;
      return '';
    });
  } // using a global regex with .exec is stateful so lastIndex has to be reset each time


  labelPattern.lastIndex = 0;
  var identifierName = '';
  var match; // https://esbench.com/bench/5b809c2cf2949800a0f61fb5

  while ((match = labelPattern.exec(styles)) !== null) {
    identifierName += '-' + // $FlowFixMe we know it's not null
    match[1];
  }

  var name = (0, _hash.default)(styles) + identifierName;

  if ("development" !== 'production') {
    // $FlowFixMe SerializedStyles type doesn't have toString property (and we don't want to add it)
    return {
      name: name,
      styles: styles,
      map: sourceMap,
      next: cursor,
      toString: function toString() {
        return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop).";
      }
    };
  }

  return {
    name: name,
    styles: styles,
    next: cursor
  };
};

exports.serializeStyles = serializeStyles;
},{"@emotion/hash":"../node_modules/@emotion/hash/dist/hash.browser.esm.js","@emotion/unitless":"../node_modules/@emotion/unitless/dist/unitless.browser.esm.js","@emotion/memoize":"../node_modules/@emotion/memoize/dist/memoize.browser.esm.js"}],"../node_modules/@emotion/css/dist/css.browser.esm.js":[function(require,module,exports) {
"use strict";

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

var _serialize = require("@emotion/serialize");

function css() {
  for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
    args[_key] = arguments[_key];
  }

  return (0, _serialize.serializeStyles)(args);
}

var _default = css;
exports.default = _default;
},{"@emotion/serialize":"../node_modules/@emotion/serialize/dist/serialize.browser.esm.js"}],"../node_modules/@emotion/core/dist/core.browser.esm.js":[function(require,module,exports) {
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
Object.defineProperty(exports, "css", {
  enumerable: true,
  get: function () {
    return _css.default;
  }
});
exports.withEmotionCache = exports.keyframes = exports.jsx = exports.ThemeContext = exports.Global = exports.ClassNames = exports.CacheProvider = void 0;

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

var _react = require("react");

var _cache = _interopRequireDefault(require("@emotion/cache"));

var _utils = require("@emotion/utils");

var _serialize = require("@emotion/serialize");

var _sheet = require("@emotion/sheet");

var _css = _interopRequireDefault(require("@emotion/css"));

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

var EmotionCacheContext = (0, _react.createContext)( // we're doing this to avoid preconstruct's dead code elimination in this one case
// because this module is primarily intended for the browser and node
// but it's also required in react native and similar environments sometimes
// and we could have a special build just for that
// but this is much easier and the native packages
// might use a different theme context in the future anyway
typeof HTMLElement !== 'undefined' ? (0, _cache.default)() : null);
var ThemeContext = (0, _react.createContext)({});
exports.ThemeContext = ThemeContext;
var CacheProvider = EmotionCacheContext.Provider;
exports.CacheProvider = CacheProvider;

var withEmotionCache = function withEmotionCache(func) {
  var render = function render(props, ref) {
    return (0, _react.createElement)(EmotionCacheContext.Consumer, null, function (cache) {
      return func(props, cache, ref);
    });
  }; // $FlowFixMe


  return (0, _react.forwardRef)(render);
}; // thus we only need to replace what is a valid character for JS, but not for CSS


exports.withEmotionCache = withEmotionCache;

var sanitizeIdentifier = function sanitizeIdentifier(identifier) {
  return identifier.replace(/\$/g, '-');
};

var typePropName = '__EMOTION_TYPE_PLEASE_DO_NOT_USE__';
var labelPropName = '__EMOTION_LABEL_PLEASE_DO_NOT_USE__';
var hasOwnProperty = Object.prototype.hasOwnProperty;

var render = function render(cache, props, theme, ref) {
  var cssProp = theme === null ? props.css : props.css(theme); // so that using `css` from `emotion` and passing the result to the css prop works
  // not passing the registered cache to serializeStyles because it would
  // make certain babel optimisations not possible

  if (typeof cssProp === 'string' && cache.registered[cssProp] !== undefined) {
    cssProp = cache.registered[cssProp];
  }

  var type = props[typePropName];
  var registeredStyles = [cssProp];
  var className = '';

  if (typeof props.className === 'string') {
    className = (0, _utils.getRegisteredStyles)(cache.registered, registeredStyles, props.className);
  } else if (props.className != null) {
    className = props.className + " ";
  }

  var serialized = (0, _serialize.serializeStyles)(registeredStyles);

  if ("development" !== 'production' && serialized.name.indexOf('-') === -1) {
    var labelFromStack = props[labelPropName];

    if (labelFromStack) {
      serialized = (0, _serialize.serializeStyles)([serialized, 'label:' + labelFromStack + ';']);
    }
  }

  var rules = (0, _utils.insertStyles)(cache, serialized, typeof type === 'string');
  className += cache.key + "-" + serialized.name;
  var newProps = {};

  for (var key in props) {
    if (hasOwnProperty.call(props, key) && key !== 'css' && key !== typePropName && ("development" === 'production' || key !== labelPropName)) {
      newProps[key] = props[key];
    }
  }

  newProps.ref = ref;
  newProps.className = className;
  var ele = (0, _react.createElement)(type, newProps);
  return ele;
};

var Emotion = /* #__PURE__ */withEmotionCache(function (props, cache, ref) {
  // use Context.read for the theme when it's stable
  if (typeof props.css === 'function') {
    return (0, _react.createElement)(ThemeContext.Consumer, null, function (theme) {
      return render(cache, props, theme, ref);
    });
  }

  return render(cache, props, null, ref);
});

if ("development" !== 'production') {
  Emotion.displayName = 'EmotionCssPropInternal';
} // $FlowFixMe


var jsx = function jsx(type, props) {
  var args = arguments;

  if (props == null || !hasOwnProperty.call(props, 'css')) {
    // $FlowFixMe
    return _react.createElement.apply(undefined, args);
  }

  if ("development" !== 'production' && typeof props.css === 'string' && // check if there is a css declaration
  props.css.indexOf(':') !== -1) {
    throw new Error("Strings are not allowed as css prop values, please wrap it in a css template literal from '@emotion/css' like this: css`" + props.css + "`");
  }

  var argsLength = args.length;
  var createElementArgArray = new Array(argsLength);
  createElementArgArray[0] = Emotion;
  var newProps = {};

  for (var key in props) {
    if (hasOwnProperty.call(props, key)) {
      newProps[key] = props[key];
    }
  }

  newProps[typePropName] = type;

  if ("development" !== 'production') {
    var error = new Error();

    if (error.stack) {
      // chrome
      var match = error.stack.match(/at (?:Object\.|)jsx.*\n\s+at ([A-Z][A-Za-z$]+) /);

      if (!match) {
        // safari and firefox
        match = error.stack.match(/.*\n([A-Z][A-Za-z$]+)@/);
      }

      if (match) {
        newProps[labelPropName] = sanitizeIdentifier(match[1]);
      }
    }
  }

  createElementArgArray[1] = newProps;

  for (var i = 2; i < argsLength; i++) {
    createElementArgArray[i] = args[i];
  } // $FlowFixMe


  return _react.createElement.apply(null, createElementArgArray);
};

exports.jsx = jsx;
var warnedAboutCssPropForGlobal = false;
var Global = /* #__PURE__ */withEmotionCache(function (props, cache) {
  if ("development" !== 'production' && !warnedAboutCssPropForGlobal && ( // check for className as well since the user is
  // probably using the custom createElement which
  // means it will be turned into a className prop
  // $FlowFixMe I don't really want to add it to the type since it shouldn't be used
  props.className || props.css)) {
    console.error("It looks like you're using the css prop on Global, did you mean to use the styles prop instead?");
    warnedAboutCssPropForGlobal = true;
  }

  var styles = props.styles;

  if (typeof styles === 'function') {
    return (0, _react.createElement)(ThemeContext.Consumer, null, function (theme) {
      var serialized = (0, _serialize.serializeStyles)([styles(theme)]);
      return (0, _react.createElement)(InnerGlobal, {
        serialized: serialized,
        cache: cache
      });
    });
  }

  var serialized = (0, _serialize.serializeStyles)([styles]);
  return (0, _react.createElement)(InnerGlobal, {
    serialized: serialized,
    cache: cache
  });
}); // maintain place over rerenders.
// initial render from browser, insertBefore context.sheet.tags[0] or if a style hasn't been inserted there yet, appendChild
// initial client-side render from SSR, use place of hydrating tag

exports.Global = Global;

var InnerGlobal = /*#__PURE__*/function (_React$Component) {
  (0, _inheritsLoose2.default)(InnerGlobal, _React$Component);

  function InnerGlobal(props, context, updater) {
    return _React$Component.call(this, props, context, updater) || this;
  }

  var _proto = InnerGlobal.prototype;

  _proto.componentDidMount = function componentDidMount() {
    this.sheet = new _sheet.StyleSheet({
      key: this.props.cache.key + "-global",
      nonce: this.props.cache.sheet.nonce,
      container: this.props.cache.sheet.container
    }); // $FlowFixMe

    var node = document.querySelector("style[data-emotion-" + this.props.cache.key + "=\"" + this.props.serialized.name + "\"]");

    if (node !== null) {
      this.sheet.tags.push(node);
    }

    if (this.props.cache.sheet.tags.length) {
      this.sheet.before = this.props.cache.sheet.tags[0];
    }

    this.insertStyles();
  };

  _proto.componentDidUpdate = function componentDidUpdate(prevProps) {
    if (prevProps.serialized.name !== this.props.serialized.name) {
      this.insertStyles();
    }
  };

  _proto.insertStyles = function insertStyles$1() {
    if (this.props.serialized.next !== undefined) {
      // insert keyframes
      (0, _utils.insertStyles)(this.props.cache, this.props.serialized.next, true);
    }

    if (this.sheet.tags.length) {
      // if this doesn't exist then it will be null so the style element will be appended
      var element = this.sheet.tags[this.sheet.tags.length - 1].nextElementSibling;
      this.sheet.before = element;
      this.sheet.flush();
    }

    this.props.cache.insert("", this.props.serialized, this.sheet, false);
  };

  _proto.componentWillUnmount = function componentWillUnmount() {
    this.sheet.flush();
  };

  _proto.render = function render() {
    return null;
  };

  return InnerGlobal;
}(_react.Component);

var keyframes = function keyframes() {
  var insertable = _css.default.apply(void 0, arguments);

  var name = "animation-" + insertable.name; // $FlowFixMe

  return {
    name: name,
    styles: "@keyframes " + name + "{" + insertable.styles + "}",
    anim: 1,
    toString: function toString() {
      return "_EMO_" + this.name + "_" + this.styles + "_EMO_";
    }
  };
};

exports.keyframes = keyframes;

var classnames = function classnames(args) {
  var len = args.length;
  var i = 0;
  var cls = '';

  for (; i < len; i++) {
    var arg = args[i];
    if (arg == null) continue;
    var toAdd = void 0;

    switch (typeof arg) {
      case 'boolean':
        break;

      case 'object':
        {
          if (Array.isArray(arg)) {
            toAdd = classnames(arg);
          } else {
            toAdd = '';

            for (var k in arg) {
              if (arg[k] && k) {
                toAdd && (toAdd += ' ');
                toAdd += k;
              }
            }
          }

          break;
        }

      default:
        {
          toAdd = arg;
        }
    }

    if (toAdd) {
      cls && (cls += ' ');
      cls += toAdd;
    }
  }

  return cls;
};

function merge(registered, css, className) {
  var registeredStyles = [];
  var rawClassName = (0, _utils.getRegisteredStyles)(registered, registeredStyles, className);

  if (registeredStyles.length < 2) {
    return className;
  }

  return rawClassName + css(registeredStyles);
}

var ClassNames = withEmotionCache(function (props, context) {
  return (0, _react.createElement)(ThemeContext.Consumer, null, function (theme) {
    var hasRendered = false;

    var css = function css() {
      if (hasRendered && "development" !== 'production') {
        throw new Error('css can only be used during render');
      }

      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }

      var serialized = (0, _serialize.serializeStyles)(args, context.registered);
      {
        (0, _utils.insertStyles)(context, serialized, false);
      }
      return context.key + "-" + serialized.name;
    };

    var cx = function cx() {
      if (hasRendered && "development" !== 'production') {
        throw new Error('cx can only be used during render');
      }

      for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
        args[_key2] = arguments[_key2];
      }

      return merge(context.registered, css, classnames(args));
    };

    var content = {
      css: css,
      cx: cx,
      theme: theme
    };
    var ele = props.children(content);
    hasRendered = true;
    return ele;
  });
});
exports.ClassNames = ClassNames;
},{"@babel/runtime/helpers/inheritsLoose":"../node_modules/@babel/runtime/helpers/inheritsLoose.js","react":"../node_modules/react/index.js","@emotion/cache":"../node_modules/@emotion/cache/dist/cache.browser.esm.js","@emotion/utils":"../node_modules/@emotion/utils/dist/utils.browser.esm.js","@emotion/serialize":"../node_modules/@emotion/serialize/dist/serialize.browser.esm.js","@emotion/sheet":"../node_modules/@emotion/sheet/dist/sheet.browser.esm.js","@emotion/css":"../node_modules/@emotion/css/dist/css.browser.esm.js"}],"../node_modules/@emotion/styled-base/dist/styled-base.browser.esm.js":[function(require,module,exports) {
"use strict";

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

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

var _react = require("react");

var _isPropValid = _interopRequireDefault(require("@emotion/is-prop-valid"));

var _core = require("@emotion/core");

var _utils = require("@emotion/utils");

var _serialize = require("@emotion/serialize");

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

var testOmitPropsOnStringTag = _isPropValid.default;

var testOmitPropsOnComponent = function testOmitPropsOnComponent(key) {
  return key !== 'theme' && key !== 'innerRef';
};

var getDefaultShouldForwardProp = function getDefaultShouldForwardProp(tag) {
  return typeof tag === 'string' && // 96 is one less than the char code
  // for "a" so this is checking that
  // it's a lowercase character
  tag.charCodeAt(0) > 96 ? testOmitPropsOnStringTag : testOmitPropsOnComponent;
};

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(source, true).forEach(function (key) {
        (0, _defineProperty2.default)(target, key, source[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
    } else {
      ownKeys(source).forEach(function (key) {
        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
      });
    }
  }

  return target;
}

var ILLEGAL_ESCAPE_SEQUENCE_ERROR = "You have illegal escape sequence in your template literal, most likely inside content's property value.\nBecause you write your CSS inside a JavaScript string you actually have to do double escaping, so for example \"content: '\\00d7';\" should become \"content: '\\\\00d7';\".\nYou can read more about this here:\nhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#ES2018_revision_of_illegal_escape_sequences";

var createStyled = function createStyled(tag, options) {
  if ("development" !== 'production') {
    if (tag === undefined) {
      throw new Error('You are trying to create a styled element with an undefined component.\nYou may have forgotten to import it.');
    }
  }

  var identifierName;
  var shouldForwardProp;
  var targetClassName;

  if (options !== undefined) {
    identifierName = options.label;
    targetClassName = options.target;
    shouldForwardProp = tag.__emotion_forwardProp && options.shouldForwardProp ? function (propName) {
      return tag.__emotion_forwardProp(propName) && // $FlowFixMe
      options.shouldForwardProp(propName);
    } : options.shouldForwardProp;
  }

  var isReal = tag.__emotion_real === tag;
  var baseTag = isReal && tag.__emotion_base || tag;

  if (typeof shouldForwardProp !== 'function' && isReal) {
    shouldForwardProp = tag.__emotion_forwardProp;
  }

  var defaultShouldForwardProp = shouldForwardProp || getDefaultShouldForwardProp(baseTag);
  var shouldUseAs = !defaultShouldForwardProp('as');
  return function () {
    var args = arguments;
    var styles = isReal && tag.__emotion_styles !== undefined ? tag.__emotion_styles.slice(0) : [];

    if (identifierName !== undefined) {
      styles.push("label:" + identifierName + ";");
    }

    if (args[0] == null || args[0].raw === undefined) {
      styles.push.apply(styles, args);
    } else {
      if ("development" !== 'production' && args[0][0] === undefined) {
        console.error(ILLEGAL_ESCAPE_SEQUENCE_ERROR);
      }

      styles.push(args[0][0]);
      var len = args.length;
      var i = 1;

      for (; i < len; i++) {
        if ("development" !== 'production' && args[0][i] === undefined) {
          console.error(ILLEGAL_ESCAPE_SEQUENCE_ERROR);
        }

        styles.push(args[i], args[0][i]);
      }
    } // $FlowFixMe: we need to cast StatelessFunctionalComponent to our PrivateStyledComponent class


    var Styled = (0, _core.withEmotionCache)(function (props, context, ref) {
      return (0, _react.createElement)(_core.ThemeContext.Consumer, null, function (theme) {
        var finalTag = shouldUseAs && props.as || baseTag;
        var className = '';
        var classInterpolations = [];
        var mergedProps = props;

        if (props.theme == null) {
          mergedProps = {};

          for (var key in props) {
            mergedProps[key] = props[key];
          }

          mergedProps.theme = theme;
        }

        if (typeof props.className === 'string') {
          className = (0, _utils.getRegisteredStyles)(context.registered, classInterpolations, props.className);
        } else if (props.className != null) {
          className = props.className + " ";
        }

        var serialized = (0, _serialize.serializeStyles)(styles.concat(classInterpolations), context.registered, mergedProps);
        var rules = (0, _utils.insertStyles)(context, serialized, typeof finalTag === 'string');
        className += context.key + "-" + serialized.name;

        if (targetClassName !== undefined) {
          className += " " + targetClassName;
        }

        var finalShouldForwardProp = shouldUseAs && shouldForwardProp === undefined ? getDefaultShouldForwardProp(finalTag) : defaultShouldForwardProp;
        var newProps = {};

        for (var _key in props) {
          if (shouldUseAs && _key === 'as') continue;

          if ( // $FlowFixMe
          finalShouldForwardProp(_key)) {
            newProps[_key] = props[_key];
          }
        }

        newProps.className = className;
        newProps.ref = ref || props.innerRef;

        if ("development" !== 'production' && props.innerRef) {
          console.error('`innerRef` is deprecated and will be removed in a future major version of Emotion, please use the `ref` prop instead' + (identifierName === undefined ? '' : " in the usage of `" + identifierName + "`"));
        }

        var ele = (0, _react.createElement)(finalTag, newProps);
        return ele;
      });
    });
    Styled.displayName = identifierName !== undefined ? identifierName : "Styled(" + (typeof baseTag === 'string' ? baseTag : baseTag.displayName || baseTag.name || 'Component') + ")";
    Styled.defaultProps = tag.defaultProps;
    Styled.__emotion_real = Styled;
    Styled.__emotion_base = baseTag;
    Styled.__emotion_styles = styles;
    Styled.__emotion_forwardProp = shouldForwardProp;
    Object.defineProperty(Styled, 'toString', {
      value: function value() {
        if (targetClassName === undefined && "development" !== 'production') {
          return 'NO_COMPONENT_SELECTOR';
        } // $FlowFixMe: coerce undefined to string


        return "." + targetClassName;
      }
    });

    Styled.withComponent = function (nextTag, nextOptions) {
      return createStyled(nextTag, nextOptions !== undefined ? _objectSpread({}, options || {}, {}, nextOptions) : options).apply(void 0, styles);
    };

    return Styled;
  };
};

var _default = createStyled;
exports.default = _default;
},{"@babel/runtime/helpers/defineProperty":"../node_modules/@babel/runtime/helpers/defineProperty.js","react":"../node_modules/react/index.js","@emotion/is-prop-valid":"../node_modules/@emotion/is-prop-valid/dist/is-prop-valid.browser.esm.js","@emotion/core":"../node_modules/@emotion/core/dist/core.browser.esm.js","@emotion/utils":"../node_modules/@emotion/utils/dist/utils.browser.esm.js","@emotion/serialize":"../node_modules/@emotion/serialize/dist/serialize.browser.esm.js"}],"../node_modules/@emotion/styled/dist/styled.browser.esm.js":[function(require,module,exports) {
"use strict";

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

var _styledBase = _interopRequireDefault(require("@emotion/styled-base"));

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

var tags = ['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'big', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr', // SVG
'circle', 'clipPath', 'defs', 'ellipse', 'foreignObject', 'g', 'image', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'svg', 'text', 'tspan'];

var newStyled = _styledBase.default.bind();

tags.forEach(function (tagName) {
  newStyled[tagName] = newStyled(tagName);
});
var _default = newStyled;
exports.default = _default;
},{"@emotion/styled-base":"../node_modules/@emotion/styled-base/dist/styled-base.browser.esm.js"}],"../src/theme.js":[function(require,module,exports) {
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.jsonTreeTheme = exports.default = void 0;
var jsonTreeTheme = {
  scheme: "monokai",
  base00: "#363755",
  base01: "#604D49",
  base02: "#6D5A55",
  base03: "#D1929B",
  base04: "#B79F8D",
  base05: "#F9F8F2",
  base06: "#F7F4F1",
  base07: "#FAF8F5",
  base08: "#FA3E7E",
  base09: "#FD993C",
  base0A: "#F6BF81",
  base0B: "#B8E248",
  base0C: "#B4EFE4",
  base0D: "#85D9EF",
  base0E: "#BE87FF",
  base0F: "#D6724C"
};
exports.jsonTreeTheme = jsonTreeTheme;
var mainTheme = {
  main: "#ffa2b1",
  main20: "rgba(255, 162, 177, .2)",
  main40: "rgba(255, 162, 177, .4)",
  main60: "rgba(255, 162, 177, .6)",
  main80: "rgba(255, 162, 177, .8)",
  main90: "rgba(255, 162, 177, .9)",
  mainBg: "#363755",
  softerMain: "#BB91A3",
  white: "#fff",
  white05: "rgba(255, 255, 255, .05)",
  white10: "rgba(255, 255, 255, .1)",
  white20: "rgba(255, 255, 255, .2)",
  white60: "rgba(255, 255, 255, .6)",
  white80: "rgba(255, 255, 255, .8)",
  black30: "rgba(0, 0, 0, .3)",
  // For diffs and structure
  lightYellow: "#FFF9C4",
  lightPink: "#FB4B85",
  darkGreen: "#81AF6D",
  syntax: jsonTreeTheme
};
var _default = mainTheme;
exports.default = _default;
},{}],"../src/dev-tools-collapsed.js":[function(require,module,exports) {
"use strict";

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

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

var _styled = _interopRequireDefault(require("@emotion/styled"));

var _theme = _interopRequireDefault(require("./theme"));

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

var FloattingButton = (0, _styled.default)("div")({
  position: "fixed",
  bottom: "16px",
  right: "16px",
  background: _theme.default.mainBg,
  boxShadow: "0 0 30px ".concat(_theme.default.black30),
  borderRadius: "50%",
  padding: "4px 6px",
  transition: "opacity 0.3s",
  zIndex: 99999,
  "&:hover": {
    opacity: 0.7,
    cursor: "pointer"
  },
  "& svg": {
    width: "34px",
    height: "34px",
    position: "relative",
    bottom: "-2px"
  }
});
FloattingButton.displayName = "FloattingButton";

function DevToolsCollapsed(props) {
  return /*#__PURE__*/_react.default.createElement(FloattingButton, {
    onClick: props.onClick
  }, /*#__PURE__*/_react.default.createElement("svg", {
    width: "530",
    height: "530",
    viewBox: "0 0 530 530",
    xmlns: "http://www.w3.org/2000/svg",
    xmlnsXlink: "http://www.w3.org/1999/xlink"
  }, /*#__PURE__*/_react.default.createElement("title", null, "prosemirror"), /*#__PURE__*/_react.default.createElement("desc", null, "Created using Figma"), /*#__PURE__*/_react.default.createElement("use", {
    xlinkHref: "#a",
    transform: "matrix(2 0 0 2 118 116)",
    fill: "#FFF"
  }), /*#__PURE__*/_react.default.createElement("use", {
    xlinkHref: "#b",
    transform: "rotate(16 59.054 420.192) scale(2)",
    fill: "#FFF"
  }), /*#__PURE__*/_react.default.createElement("use", {
    xlinkHref: "#c",
    transform: "matrix(2 0 0 2 154.024 141.58)",
    fill: "#363755"
  }), /*#__PURE__*/_react.default.createElement("use", {
    xlinkHref: "#d",
    transform: "matrix(2 0 0 2 220 334.8)",
    fill: "#FFF"
  }), /*#__PURE__*/_react.default.createElement("use", {
    xlinkHref: "#e",
    transform: "matrix(2 0 0 2 218.826 262.052)",
    fill: "#363755"
  }), /*#__PURE__*/_react.default.createElement("use", {
    xlinkHref: "#f",
    transform: "matrix(2 0 0 2 197.108 184.998)",
    fill: "#FFF"
  }), /*#__PURE__*/_react.default.createElement("use", {
    xlinkHref: "#g",
    transform: "matrix(2 0 0 2 221.8 216)",
    fill: "#363755"
  }), /*#__PURE__*/_react.default.createElement("defs", null, /*#__PURE__*/_react.default.createElement("path", {
    id: "a",
    d: "M73.5 0C32.859 0 0 32.859 0 73.5S32.859 147 73.5 147 147 114.141 147 73.5 114.069 0 73.5 0z"
  }), /*#__PURE__*/_react.default.createElement("path", {
    id: "b",
    d: "M193.601 107.116c0-13.376 8.238-23.91 20.619-31.153-2.244-7.447-5.19-14.6-8.824-21.32-13.886 3.633-25.12-1.799-34.568-11.26-9.449-9.437-12.344-20.672-8.709-34.571A111.362 111.362 0 0 0 140.799 0c-7.243 12.37-20.339 20.594-33.689 20.594-13.363 0-26.446-8.225-33.701-20.594A110.888 110.888 0 0 0 52.1 8.812c3.634 13.9.753 25.134-8.721 34.57-9.436 9.462-20.67 14.894-34.569 11.26A112.178 112.178 0 0 0 0 75.963c12.369 7.243 20.593 17.777 20.593 31.153 0 13.352-8.224 26.448-20.593 33.704a113.338 113.338 0 0 0 8.811 21.321c13.899-3.634 25.133-.752 34.569 8.697 9.448 9.462 12.355 20.696 8.721 34.57a112.653 112.653 0 0 0 21.32 8.837c7.243-12.407 20.338-20.619 33.702-20.619 13.35 0 26.446 8.225 33.701 20.619a114.22 114.22 0 0 0 21.32-8.837c-3.634-13.874-.752-25.108 8.709-34.57 9.449-9.437 20.683-14.869 34.569-11.26a112.343 112.343 0 0 0 8.823-21.321c-12.406-7.256-20.644-17.789-20.644-31.141zm-86.491 46.57c-25.732 0-46.58-20.849-46.58-46.57 0-25.733 20.86-46.595 46.58-46.595 25.732 0 46.567 20.875 46.567 46.595 0 25.734-20.835 46.57-46.567 46.57z"
  }), /*#__PURE__*/_react.default.createElement("path", {
    id: "c",
    d: "M98.088 49.91c-6.9 83.9 10.8 103.401 10.8 103.401s-55.1 5.499-82.7-13.401c-30.5-20.9-26-67.5-25.9-94.6.1-28.4 25.6-45.8 49.9-45.3 29.1.5 50.2 21.6 47.9 49.9z"
  }), /*#__PURE__*/_react.default.createElement("path", {
    id: "d",
    d: "M.1.1c12.2 33.3 22.5 42.7 40 55.2 25.3 18 36.6 17.5 76.3 41C78.1 60.3 30.8 45.7 0 0l.1.1z"
  }), /*#__PURE__*/_react.default.createElement("path", {
    id: "e",
    d: "M.687 36.474c3 13.3 17.9 29.9 30.4 41.6 24.8 23.2 42 22.4 86 54.7-18.2-51.8-18.8-62-43.5-106.1-24.7-44-67.6-20.3-67.6-20.3s-8.4 16.6-5.3 29.9v.2z"
  }), /*#__PURE__*/_react.default.createElement("path", {
    id: "f",
    d: "M38.346 11.5s-4-11.6-18-11.5c-30 .2-28.8 52.1 16.9 52 39.6-.1 39.2-49.4 16.1-49.6-10.2-.2-15 9.1-15 9.1z"
  }), /*#__PURE__*/_react.default.createElement("path", {
    id: "g",
    d: "M26.5 15c10.8 0 2 14.9-.6 20.9-1.8-8.4-10.2-20.9.6-20.9zM10.2.1C4.6.1 0 4.6 0 10.3c0 5.6 4.5 10.2 10.2 10.2 5.6 0 10.2-4.5 10.2-10.2C20.4 4.7 15.9.1 10.2.1zM40.7 0c-4.8 0-8.8 4.5-8.8 10.2 0 5.6 3.9 10.2 8.8 10.2 4.8 0 8.8-4.5 8.8-10.2C49.5 4.6 45.6 0 40.7 0z"
  }))));
}
},{"react":"../node_modules/react/index.js","@emotion/styled":"../node_modules/@emotion/styled/dist/styled.browser.esm.js","./theme":"../src/theme.js"}],"../node_modules/lodash._getnative/index.js":[function(require,module,exports) {
/**
 * lodash 3.9.1 (Custom Build) <https://lodash.com/>
 * Build: `lodash modern modularize exports="npm" -o ./`
 * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <https://lodash.com/license>
 */

/** `Object#toString` result references. */
var funcTag = '[object Function]';

/** Used to detect host constructors (Safari > 5). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;

/**
 * Checks if `value` is object-like.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
 */
function isObjectLike(value) {
  return !!value && typeof value == 'object';
}

/** Used for native method references. */
var objectProto = Object.prototype;

/** Used to resolve the decompiled source of functions. */
var fnToString = Function.prototype.toString;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
 * of values.
 */
var objToString = objectProto.toString;

/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
  fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&')
  .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);

/**
 * Gets the native function at `key` of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {string} key The key of the method to get.
 * @returns {*} Returns the function if it's native, else `undefined`.
 */
function getNative(object, key) {
  var value = object == null ? undefined : object[key];
  return isNative(value) ? value : undefined;
}

/**
 * Checks if `value` is classified as a `Function` object.
 *
 * @static
 * @memberOf _
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
 * @example
 *
 * _.isFunction(_);
 * // => true
 *
 * _.isFunction(/abc/);
 * // => false
 */
function isFunction(value) {
  // The use of `Object#toString` avoids issues with the `typeof` operator
  // in older versions of Chrome and Safari which return 'function' for regexes
  // and Safari 8 equivalents which return 'object' for typed array constructors.
  return isObject(value) && objToString.call(value) == funcTag;
}

/**
 * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
 * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
 *
 * @static
 * @memberOf _
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
 * @example
 *
 * _.isObject({});
 * // => true
 *
 * _.isObject([1, 2, 3]);
 * // => true
 *
 * _.isObject(1);
 * // => false
 */
function isObject(value) {
  // Avoid a V8 JIT bug in Chrome 19-20.
  // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
  var type = typeof value;
  return !!value && (type == 'object' || type == 'function');
}

/**
 * Checks if `value` is a native function.
 *
 * @static
 * @memberOf _
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a native function, else `false`.
 * @example
 *
 * _.isNative(Array.prototype.push);
 * // => true
 *
 * _.isNative(_);
 * // => false
 */
function isNative(value) {
  if (value == null) {
    return false;
  }
  if (isFunction(value)) {
    return reIsNative.test(fnToString.call(value));
  }
  return isObjectLike(value) && reIsHostCtor.test(value);
}

module.exports = getNative;

},{}],"../node_modules/lodash.debounce/index.js":[function(require,module,exports) {
/**
 * lodash 3.1.1 (Custom Build) <https://lodash.com/>
 * Build: `lodash modern modularize exports="npm" -o ./`
 * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <https://lodash.com/license>
 */
var getNative = require('lodash._getnative');

/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';

/* Native method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max,
    nativeNow = getNative(Date, 'now');

/**
 * Gets the number of milliseconds that have elapsed since the Unix epoch
 * (1 January 1970 00:00:00 UTC).
 *
 * @static
 * @memberOf _
 * @category Date
 * @example
 *
 * _.defer(function(stamp) {
 *   console.log(_.now() - stamp);
 * }, _.now());
 * // => logs the number of milliseconds it took for the deferred function to be invoked
 */
var now = nativeNow || function() {
  return new Date().getTime();
};

/**
 * Creates a debounced function that delays invoking `func` until after `wait`
 * milliseconds have elapsed since the last time the debounced function was
 * invoked. The debounced function comes with a `cancel` method to cancel
 * delayed invocations. Provide an options object to indicate that `func`
 * should be invoked on the leading and/or trailing edge of the `wait` timeout.
 * Subsequent calls to the debounced function return the result of the last
 * `func` invocation.
 *
 * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked
 * on the trailing edge of the timeout only if the the debounced function is
 * invoked more than once during the `wait` timeout.
 *
 * See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation)
 * for details over the differences between `_.debounce` and `_.throttle`.
 *
 * @static
 * @memberOf _
 * @category Function
 * @param {Function} func The function to debounce.
 * @param {number} [wait=0] The number of milliseconds to delay.
 * @param {Object} [options] The options object.
 * @param {boolean} [options.leading=false] Specify invoking on the leading
 *  edge of the timeout.
 * @param {number} [options.maxWait] The maximum time `func` is allowed to be
 *  delayed before it is invoked.
 * @param {boolean} [options.trailing=true] Specify invoking on the trailing
 *  edge of the timeout.
 * @returns {Function} Returns the new debounced function.
 * @example
 *
 * // avoid costly calculations while the window size is in flux
 * jQuery(window).on('resize', _.debounce(calculateLayout, 150));
 *
 * // invoke `sendMail` when the click event is fired, debouncing subsequent calls
 * jQuery('#postbox').on('click', _.debounce(sendMail, 300, {
 *   'leading': true,
 *   'trailing': false
 * }));
 *
 * // ensure `batchLog` is invoked once after 1 second of debounced calls
 * var source = new EventSource('/stream');
 * jQuery(source).on('message', _.debounce(batchLog, 250, {
 *   'maxWait': 1000
 * }));
 *
 * // cancel a debounced call
 * var todoChanges = _.debounce(batchLog, 1000);
 * Object.observe(models.todo, todoChanges);
 *
 * Object.observe(models, function(changes) {
 *   if (_.find(changes, { 'user': 'todo', 'type': 'delete'})) {
 *     todoChanges.cancel();
 *   }
 * }, ['delete']);
 *
 * // ...at some point `models.todo` is changed
 * models.todo.completed = true;
 *
 * // ...before 1 second has passed `models.todo` is deleted
 * // which cancels the debounced `todoChanges` call
 * delete models.todo;
 */
function debounce(func, wait, options) {
  var args,
      maxTimeoutId,
      result,
      stamp,
      thisArg,
      timeoutId,
      trailingCall,
      lastCalled = 0,
      maxWait = false,
      trailing = true;

  if (typeof func != 'function') {
    throw new TypeError(FUNC_ERROR_TEXT);
  }
  wait = wait < 0 ? 0 : (+wait || 0);
  if (options === true) {
    var leading = true;
    trailing = false;
  } else if (isObject(options)) {
    leading = !!options.leading;
    maxWait = 'maxWait' in options && nativeMax(+options.maxWait || 0, wait);
    trailing = 'trailing' in options ? !!options.trailing : trailing;
  }

  function cancel() {
    if (timeoutId) {
      clearTimeout(timeoutId);
    }
    if (maxTimeoutId) {
      clearTimeout(maxTimeoutId);
    }
    lastCalled = 0;
    maxTimeoutId = timeoutId = trailingCall = undefined;
  }

  function complete(isCalled, id) {
    if (id) {
      clearTimeout(id);
    }
    maxTimeoutId = timeoutId = trailingCall = undefined;
    if (isCalled) {
      lastCalled = now();
      result = func.apply(thisArg, args);
      if (!timeoutId && !maxTimeoutId) {
        args = thisArg = undefined;
      }
    }
  }

  function delayed() {
    var remaining = wait - (now() - stamp);
    if (remaining <= 0 || remaining > wait) {
      complete(trailingCall, maxTimeoutId);
    } else {
      timeoutId = setTimeout(delayed, remaining);
    }
  }

  function maxDelayed() {
    complete(trailing, timeoutId);
  }

  function debounced() {
    args = arguments;
    stamp = now();
    thisArg = this;
    trailingCall = trailing && (timeoutId || !leading);

    if (maxWait === false) {
      var leadingCall = leading && !timeoutId;
    } else {
      if (!maxTimeoutId && !leading) {
        lastCalled = stamp;
      }
      var remaining = maxWait - (stamp - lastCalled),
          isCalled = remaining <= 0 || remaining > maxWait;

      if (isCalled) {
        if (maxTimeoutId) {
          maxTimeoutId = clearTimeout(maxTimeoutId);
        }
        lastCalled = stamp;
        result = func.apply(thisArg, args);
      }
      else if (!maxTimeoutId) {
        maxTimeoutId = setTimeout(maxDelayed, remaining);
      }
    }
    if (isCalled && timeoutId) {
      timeoutId = clearTimeout(timeoutId);
    }
    else if (!timeoutId && wait !== maxWait) {
      timeoutId = setTimeout(delayed, wait);
    }
    if (leadingCall) {
      isCalled = true;
      result = func.apply(thisArg, args);
    }
    if (isCalled && !timeoutId && !maxTimeoutId) {
      args = thisArg = undefined;
    }
    return result;
  }
  debounced.cancel = cancel;
  return debounced;
}

/**
 * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
 * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
 *
 * @static
 * @memberOf _
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
 * @example
 *
 * _.isObject({});
 * // => true
 *
 * _.isObject([1, 2, 3]);
 * // => true
 *
 * _.isObject(1);
 * // => false
 */
function isObject(value) {
  // Avoid a V8 JIT bug in Chrome 19-20.
  // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
  var type = typeof value;
  return !!value && (type == 'object' || type == 'function');
}

module.exports = debounce;

},{"lodash._getnative":"../node_modules/lodash._getnative/index.js"}],"../node_modules/react-dock/lib/autoprefix.js":[function(require,module,exports) {
'use strict';

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

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

exports.default = autoprefix;
// Same as https://github.com/SimenB/react-vendor-prefixes/blob/master/src/index.js,
// but dumber

var vendorSpecificProperties = ['animation', 'animationDelay', 'animationDirection', 'animationDuration', 'animationFillMode', 'animationIterationCount', 'animationName', 'animationPlayState', 'animationTimingFunction', 'appearance', 'backfaceVisibility', 'backgroundClip', 'borderImage', 'borderImageSlice', 'boxSizing', 'boxShadow', 'contentColumns', 'transform', 'transformOrigin', 'transformStyle', 'transition', 'transitionDelay', 'transitionDuration', 'transitionProperty', 'transitionTimingFunction', 'perspective', 'perspectiveOrigin', 'userSelect'];

var prefixes = ['Moz', 'Webkit', 'ms', 'O'];

function prefixProp(key, value) {
  return prefixes.reduce(function (obj, pre) {
    return obj[pre + key[0].toUpperCase() + key.substr(1)] = value, obj;
  }, {});
}

function autoprefix(style) {
  return Object.keys(style).reduce(function (obj, key) {
    return vendorSpecificProperties.indexOf(key) !== -1 ? _extends({}, obj, prefixProp(key, style[key])) : obj;
  }, style);
}
},{}],"../node_modules/react-dock/lib/Dock.js":[function(require,module,exports) {
'use strict';

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

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _class, _temp;

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _lodash = require('lodash.debounce');

var _lodash2 = _interopRequireDefault(_lodash);

var _autoprefix = require('./autoprefix');

var _autoprefix2 = _interopRequireDefault(_autoprefix);

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

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

function autoprefixes(styles) {
  return Object.keys(styles).reduce(function (obj, key) {
    return obj[key] = (0, _autoprefix2.default)(styles[key]), obj;
  }, {});
}

var styles = autoprefixes({
  wrapper: {
    position: 'fixed',
    width: 0,
    height: 0,
    top: 0,
    left: 0
  },

  dim: {
    position: 'fixed',
    left: 0,
    right: 0,
    top: 0,
    bottom: 0,
    zIndex: 0,
    background: 'rgba(0, 0, 0, 0.2)',
    opacity: 1
  },

  dimAppear: {
    opacity: 0
  },

  dimTransparent: {
    pointerEvents: 'none'
  },

  dimHidden: {
    opacity: 0
  },

  dock: {
    position: 'fixed',
    zIndex: 1,
    boxShadow: '0 0 4px rgba(0, 0, 0, 0.3)',
    background: 'white',
    left: 0,
    top: 0,
    width: '100%',
    height: '100%'
  },

  dockHidden: {
    opacity: 0
  },

  dockResizing: {
    transition: 'none'
  },

  dockContent: {
    width: '100%',
    height: '100%',
    overflow: 'auto'
  },

  resizer: {
    position: 'absolute',
    zIndex: 2,
    opacity: 0
  }
});

function getTransitions(duration) {
  return ['left', 'top', 'width', 'height'].map(function (p) {
    return p + ' ' + duration / 1000 + 's ease-out';
  });
}

function getDockStyles(_ref, _ref2) {
  var fluid = _ref.fluid;
  var dockStyle = _ref.dockStyle;
  var dockHiddenStyle = _ref.dockHiddenStyle;
  var duration = _ref.duration;
  var position = _ref.position;
  var isVisible = _ref.isVisible;
  var size = _ref2.size;
  var isResizing = _ref2.isResizing;
  var fullWidth = _ref2.fullWidth;
  var fullHeight = _ref2.fullHeight;

  var posStyle = void 0;
  var absSize = fluid ? size * 100 + '%' : size + 'px';

  function getRestSize(fullSize) {
    return fluid ? 100 - size * 100 + '%' : fullSize - size + 'px';
  }

  switch (position) {
    case 'left':
      posStyle = {
        width: absSize,
        left: isVisible ? 0 : '-' + absSize
      };
      break;
    case 'right':
      posStyle = {
        left: isVisible ? getRestSize(fullWidth) : fullWidth,
        width: absSize
      };
      break;
    case 'top':
      posStyle = {
        top: isVisible ? 0 : '-' + absSize,
        height: absSize
      };
      break;
    case 'bottom':
      posStyle = {
        top: isVisible ? getRestSize(fullHeight) : fullHeight,
        height: absSize
      };
      break;
  }

  var transitions = getTransitions(duration);

  return [styles.dock, (0, _autoprefix2.default)({
    transition: [].concat(_toConsumableArray(transitions), [!isVisible && 'opacity 0.01s linear ' + duration / 1000 + 's']).filter(function (t) {
      return t;
    }).join(',')
  }), dockStyle, (0, _autoprefix2.default)(posStyle), isResizing && styles.dockResizing, !isVisible && styles.dockHidden, !isVisible && dockHiddenStyle];
}

function getDimStyles(_ref3, _ref4) {
  var dimMode = _ref3.dimMode;
  var dimStyle = _ref3.dimStyle;
  var duration = _ref3.duration;
  var isVisible = _ref3.isVisible;
  var isTransitionStarted = _ref4.isTransitionStarted;

  return [styles.dim, (0, _autoprefix2.default)({
    transition: 'opacity ' + duration / 1000 + 's ease-out'
  }), dimStyle, dimMode === 'transparent' && styles.dimTransparent, !isVisible && styles.dimHidden, isTransitionStarted && isVisible && styles.dimAppear, isTransitionStarted && !isVisible && styles.dimDisappear];
}

function getResizerStyles(position) {
  var resizerStyle = void 0;
  var size = 10;

  switch (position) {
    case 'left':
      resizerStyle = {
        right: -size / 2,
        width: size,
        top: 0,
        height: '100%',
        cursor: 'col-resize'
      };
      break;
    case 'right':
      resizerStyle = {
        left: -size / 2,
        width: size,
        top: 0,
        height: '100%',
        cursor: 'col-resize'
      };
      break;
    case 'top':
      resizerStyle = {
        bottom: -size / 2,
        height: size,
        left: 0,
        width: '100%',
        cursor: 'row-resize'
      };
      break;
    case 'bottom':
      resizerStyle = {
        top: -size / 2,
        height: size,
        left: 0,
        width: '100%',
        cursor: 'row-resize'
      };
      break;
  }

  return [styles.resizer, (0, _autoprefix2.default)(resizerStyle)];
}

function getFullSize(position, fullWidth, fullHeight) {
  return position === 'left' || position === 'right' ? fullWidth : fullHeight;
}

var Dock = (_temp = _class = function (_Component) {
  _inherits(Dock, _Component);

  function Dock(props) {
    _classCallCheck(this, Dock);

    var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(Dock).call(this, props));

    _this.transitionEnd = function () {
      _this.setState({ isTransitionStarted: false });
    };

    _this.hideDim = function () {
      if (!_this.props.isVisible) {
        _this.setState({ isDimHidden: true });
      }
    };

    _this.handleDimClick = function () {
      if (_this.props.dimMode === 'opaque') {
        _this.props.onVisibleChange && _this.props.onVisibleChange(false);
      }
    };

    _this.handleResize = function () {
      if (window.requestAnimationFrame) {
        window.requestAnimationFrame(_this.updateWindowSize.bind(_this, true));
      } else {
        _this.updateWindowSize(true);
      }
    };

    _this.updateWindowSize = function (windowResize) {
      var sizeState = {
        fullWidth: window.innerWidth,
        fullHeight: window.innerHeight
      };

      if (windowResize) {
        _this.setState(_extends({}, sizeState, {
          isResizing: true,
          isWindowResizing: windowResize
        }));

        _this.debouncedUpdateWindowSizeEnd();
      } else {
        _this.setState(sizeState);
      }
    };

    _this.updateWindowSizeEnd = function () {
      _this.setState({
        isResizing: false,
        isWindowResizing: false
      });
    };

    _this.debouncedUpdateWindowSizeEnd = (0, _lodash2.default)(_this.updateWindowSizeEnd, 30);

    _this.handleWrapperLeave = function () {
      _this.setState({ isResizing: false });
    };

    _this.handleMouseDown = function () {
      _this.setState({ isResizing: true });
    };

    _this.handleMouseUp = function () {
      _this.setState({ isResizing: false });
    };

    _this.handleMouseMove = function (e) {
      if (!_this.state.isResizing || _this.state.isWindowResizing) return;
      e.preventDefault();

      var _this$props = _this.props;
      var position = _this$props.position;
      var fluid = _this$props.fluid;
      var _this$state = _this.state;
      var fullWidth = _this$state.fullWidth;
      var fullHeight = _this$state.fullHeight;
      var isControlled = _this$state.isControlled;
      var x = e.clientX;
      var y = e.clientY;

      var size = void 0;

      switch (position) {
        case 'left':
          size = fluid ? x / fullWidth : x;
          break;
        case 'right':
          size = fluid ? (fullWidth - x) / fullWidth : fullWidth - x;
          break;
        case 'top':
          size = fluid ? y / fullHeight : y;
          break;
        case 'bottom':
          size = fluid ? (fullHeight - y) / fullHeight : fullHeight - y;
          break;
      }

      _this.props.onSizeChange && _this.props.onSizeChange(size);

      if (!isControlled) {
        _this.setState({ size: size });
      }
    };

    _this.state = {
      isControlled: typeof props.size !== 'undefined',
      size: props.size || props.defaultSize,
      isDimHidden: !props.isVisible,
      fullWidth: typeof window !== 'undefined' && window.innerWidth,
      fullHeight: typeof window !== 'undefined' && window.innerHeight,
      isTransitionStarted: false,
      isWindowResizing: false
    };
    return _this;
  }

  _createClass(Dock, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      window.addEventListener('mouseup', this.handleMouseUp);
      window.addEventListener('mousemove', this.handleMouseMove);
      window.addEventListener('resize', this.handleResize);

      if (!window.fullWidth) {
        this.updateWindowSize();
      }
    }
  }, {
    key: 'componentWillUnmount',
    value: function componentWillUnmount() {
      window.removeEventListener('mouseup', this.handleMouseUp);
      window.removeEventListener('mousemove', this.handleMouseMove);
      window.removeEventListener('resize', this.handleResize);
    }
  }, {
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps) {
      var isControlled = typeof nextProps.size !== 'undefined';

      this.setState({ isControlled: isControlled });

      if (isControlled && this.props.size !== nextProps.size) {
        this.setState({ size: nextProps.size });
      } else if (this.props.fluid !== nextProps.fluid) {
        this.updateSize(nextProps);
      }

      if (this.props.isVisible !== nextProps.isVisible) {
        this.setState({
          isTransitionStarted: true
        });
      }
    }
  }, {
    key: 'updateSize',
    value: function updateSize(props) {
      var _state = this.state;
      var fullWidth = _state.fullWidth;
      var fullHeight = _state.fullHeight;


      this.setState({
        size: props.fluid ? this.state.size / getFullSize(props.position, fullWidth, fullHeight) : getFullSize(props.position, fullWidth, fullHeight) * this.state.size
      });
    }
  }, {
    key: 'componentDidUpdate',
    value: function componentDidUpdate(prevProps) {
      var _this2 = this;

      if (this.props.isVisible !== prevProps.isVisible) {
        if (!this.props.isVisible) {
          window.setTimeout(function () {
            return _this2.hideDim();
          }, this.props.duration);
        } else {
          this.setState({ isDimHidden: false });
        }

        window.setTimeout(function () {
          return _this2.setState({ isTransitionStarted: false });
        }, 0);
      }
    }
  }, {
    key: 'render',
    value: function render() {
      var _props = this.props;
      var children = _props.children;
      var zIndex = _props.zIndex;
      var dimMode = _props.dimMode;
      var position = _props.position;
      var isVisible = _props.isVisible;
      var _state2 = this.state;
      var isResizing = _state2.isResizing;
      var size = _state2.size;
      var isDimHidden = _state2.isDimHidden;


      var dimStyles = Object.assign.apply(Object, [{}].concat(_toConsumableArray(getDimStyles(this.props, this.state))));
      var dockStyles = Object.assign.apply(Object, [{}].concat(_toConsumableArray(getDockStyles(this.props, this.state))));
      var resizerStyles = Object.assign.apply(Object, [{}].concat(_toConsumableArray(getResizerStyles(position))));

      return _react2.default.createElement(
        'div',
        { style: Object.assign({}, styles.wrapper, { zIndex: zIndex }) },
        dimMode !== 'none' && !isDimHidden && _react2.default.createElement('div', { style: dimStyles, onClick: this.handleDimClick }),
        _react2.default.createElement(
          'div',
          { style: dockStyles },
          _react2.default.createElement('div', { style: resizerStyles,
            onMouseDown: this.handleMouseDown }),
          _react2.default.createElement(
            'div',
            { style: styles.dockContent },
            typeof children === 'function' ? children({
              position: position,
              isResizing: isResizing,
              size: size,
              isVisible: isVisible
            }) : children
          )
        )
      );
    }
  }]);

  return Dock;
}(_react.Component), _class.propTypes = {
  position: _propTypes2.default.oneOf(['left', 'right', 'top', 'bottom']),
  zIndex: _propTypes2.default.number,
  fluid: _propTypes2.default.bool,
  size: _propTypes2.default.number,
  defaultSize: _propTypes2.default.number,
  dimMode: _propTypes2.default.oneOf(['none', 'transparent', 'opaque']),
  isVisible: _propTypes2.default.bool,
  onVisibleChange: _propTypes2.default.func,
  onSizeChange: _propTypes2.default.func,
  dimStyle: _propTypes2.default.object,
  dockStyle: _propTypes2.default.object,
  duration: _propTypes2.default.number
}, _class.defaultProps = {
  position: 'left',
  zIndex: 99999999,
  fluid: true,
  defaultSize: 0.3,
  dimMode: 'opaque',
  duration: 200
}, _temp);
exports.default = Dock;
},{"react":"../node_modules/react/index.js","prop-types":"../node_modules/prop-types/index.js","lodash.debounce":"../node_modules/lodash.debounce/index.js","./autoprefix":"../node_modules/react-dock/lib/autoprefix.js"}],"../node_modules/react-dock/lib/index.js":[function(require,module,exports) {
'use strict';

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

var _Dock = require('./Dock');

var _Dock2 = _interopRequireDefault(_Dock);

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

exports.default = _Dock2.default;
},{"./Dock":"../node_modules/react-dock/lib/Dock.js"}],"../src/components/tabs.js":[function(require,module,exports) {
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Tabs = exports.TabPanel = exports.TabPanelStyled = exports.Tab = exports.TabStyled = exports.TabsStled = exports.TabList = void 0;

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

var _styled = _interopRequireDefault(require("@emotion/styled"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _theme = _interopRequireDefault(require("../theme"));

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

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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function () { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

var TabList = (0, _styled.default)("div")({
  display: "flex",
  listStyle: "none",
  borderBottom: "1px solid ".concat(_theme.default.main20)
});
exports.TabList = TabList;
TabList.displayName = "TabList";
var TabsStled = (0, _styled.default)("div")({
  height: "100%",
  width: "100%"
});
exports.TabsStled = TabsStled;
TabsStled.displayName = "TabsStyled";
var TabStyled = (0, _styled.default)("div")({
  color: _theme.default.white,
  textTransform: "uppercase",
  fontSize: "13px",
  padding: "16px 24px 14px",
  boxSizing: "border-box",
  userSelect: "none",
  "&:hover": {
    cursor: "pointer",
    background: _theme.default.white05
  },
  "&:focus": {
    outline: "none"
  }
}, function (props) {
  return {
    borderBottom: props.isSelected ? "2px solid ".concat(_theme.default.main) : "none"
  };
});
exports.TabStyled = TabStyled;
TabStyled.displayName = "TabStyled";

var Tab = /*#__PURE__*/function (_React$Component) {
  _inherits(Tab, _React$Component);

  var _super = _createSuper(Tab);

  function Tab() {
    _classCallCheck(this, Tab);

    return _super.apply(this, arguments);
  }

  _createClass(Tab, [{
    key: "render",
    value: function render() {
      var _this = this;

      return /*#__PURE__*/_react.default.createElement(TabStyled, {
        isSelected: this.props.index === this.context.tabs.selectedIndex,
        onClick: function onClick() {
          (_this.context.tabs.onSelect || function () {})(_this.props.index);
        }
      }, this.props.children);
    }
  }]);

  return Tab;
}(_react.default.Component);

exports.Tab = Tab;
Tab.contextTypes = {
  tabs: _propTypes.default.object.isRequired
};
var TabPanelStyled = (0, _styled.default)("div")({
  width: "100%",
  height: "calc(100% - 48px)",
  boxSizing: "border-box"
});
exports.TabPanelStyled = TabPanelStyled;
TabPanelStyled.displayName = "TabPanelStyled";

var TabPanel = /*#__PURE__*/function (_React$Component2) {
  _inherits(TabPanel, _React$Component2);

  var _super2 = _createSuper(TabPanel);

  function TabPanel() {
    _classCallCheck(this, TabPanel);

    return _super2.apply(this, arguments);
  }

  _createClass(TabPanel, [{
    key: "render",
    value: function render() {
      return /*#__PURE__*/_react.default.createElement(TabPanelStyled, null, this.props.children({
        index: this.context.tabs.selectedIndex
      }));
    }
  }]);

  return TabPanel;
}(_react.default.Component);

exports.TabPanel = TabPanel;
TabPanel.contextTypes = {
  tabs: _propTypes.default.object.isRequired
};

var Tabs = /*#__PURE__*/function (_React$Component3) {
  _inherits(Tabs, _React$Component3);

  var _super3 = _createSuper(Tabs);

  function Tabs() {
    _classCallCheck(this, Tabs);

    return _super3.apply(this, arguments);
  }

  _createClass(Tabs, [{
    key: "getChildContext",
    value: function getChildContext() {
      return {
        tabs: {
          onSelect: this.props.onSelect,
          selectedIndex: this.props.selectedIndex
        }
      };
    }
  }, {
    key: "render",
    value: function render() {
      return /*#__PURE__*/_react.default.createElement(TabsStled, null, this.props.children);
    }
  }]);

  return Tabs;
}(_react.default.Component);

exports.Tabs = Tabs;
Tabs.childContextTypes = {
  tabs: _propTypes.default.object
};
},{"react":"../node_modules/react/index.js","@emotion/styled":"../node_modules/@emotion/styled/dist/styled.browser.esm.js","prop-types":"../node_modules/prop-types/index.js","../theme":"../src/theme.js"}],"../node_modules/regenerator-runtime/runtime.js":[function(require,module,exports) {
/**
 * Copyright (c) 2014-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

var runtime = (function (exports) {
  "use strict";

  var Op = Object.prototype;
  var hasOwn = Op.hasOwnProperty;
  var undefined; // More compressible than void 0.
  var $Symbol = typeof Symbol === "function" ? Symbol : {};
  var iteratorSymbol = $Symbol.iterator || "@@iterator";
  var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
  var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";

  function wrap(innerFn, outerFn, self, tryLocsList) {
    // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
    var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
    var generator = Object.create(protoGenerator.prototype);
    var context = new Context(tryLocsList || []);

    // The ._invoke method unifies the implementations of the .next,
    // .throw, and .return methods.
    generator._invoke = makeInvokeMethod(innerFn, self, context);

    return generator;
  }
  exports.wrap = wrap;

  // Try/catch helper to minimize deoptimizations. Returns a completion
  // record like context.tryEntries[i].completion. This interface could
  // have been (and was previously) designed to take a closure to be
  // invoked without arguments, but in all the cases we care about we
  // already have an existing method we want to call, so there's no need
  // to create a new function object. We can even get away with assuming
  // the method takes exactly one argument, since that happens to be true
  // in every case, so we don't have to touch the arguments object. The
  // only additional allocation required is the completion record, which
  // has a stable shape and so hopefully should be cheap to allocate.
  function tryCatch(fn, obj, arg) {
    try {
      return { type: "normal", arg: fn.call(obj, arg) };
    } catch (err) {
      return { type: "throw", arg: err };
    }
  }

  var GenStateSuspendedStart = "suspendedStart";
  var GenStateSuspendedYield = "suspendedYield";
  var GenStateExecuting = "executing";
  var GenStateCompleted = "completed";

  // Returning this object from the innerFn has the same effect as
  // breaking out of the dispatch switch statement.
  var ContinueSentinel = {};

  // Dummy constructor functions that we use as the .constructor and
  // .constructor.prototype properties for functions that return Generator
  // objects. For full spec compliance, you may wish to configure your
  // minifier not to mangle the names of these two functions.
  function Generator() {}
  function GeneratorFunction() {}
  function GeneratorFunctionPrototype() {}

  // This is a polyfill for %IteratorPrototype% for environments that
  // don't natively support it.
  var IteratorPrototype = {};
  IteratorPrototype[iteratorSymbol] = function () {
    return this;
  };

  var getProto = Object.getPrototypeOf;
  var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
  if (NativeIteratorPrototype &&
      NativeIteratorPrototype !== Op &&
      hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
    // This environment has a native %IteratorPrototype%; use it instead
    // of the polyfill.
    IteratorPrototype = NativeIteratorPrototype;
  }

  var Gp = GeneratorFunctionPrototype.prototype =
    Generator.prototype = Object.create(IteratorPrototype);
  GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
  GeneratorFunctionPrototype.constructor = GeneratorFunction;
  GeneratorFunctionPrototype[toStringTagSymbol] =
    GeneratorFunction.displayName = "GeneratorFunction";

  // Helper for defining the .next, .throw, and .return methods of the
  // Iterator interface in terms of a single ._invoke method.
  function defineIteratorMethods(prototype) {
    ["next", "throw", "return"].forEach(function(method) {
      prototype[method] = function(arg) {
        return this._invoke(method, arg);
      };
    });
  }

  exports.isGeneratorFunction = function(genFun) {
    var ctor = typeof genFun === "function" && genFun.constructor;
    return ctor
      ? ctor === GeneratorFunction ||
        // For the native GeneratorFunction constructor, the best we can
        // do is to check its .name property.
        (ctor.displayName || ctor.name) === "GeneratorFunction"
      : false;
  };

  exports.mark = function(genFun) {
    if (Object.setPrototypeOf) {
      Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
    } else {
      genFun.__proto__ = GeneratorFunctionPrototype;
      if (!(toStringTagSymbol in genFun)) {
        genFun[toStringTagSymbol] = "GeneratorFunction";
      }
    }
    genFun.prototype = Object.create(Gp);
    return genFun;
  };

  // Within the body of any async function, `await x` is transformed to
  // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
  // `hasOwn.call(value, "__await")` to determine if the yielded value is
  // meant to be awaited.
  exports.awrap = function(arg) {
    return { __await: arg };
  };

  function AsyncIterator(generator, PromiseImpl) {
    function invoke(method, arg, resolve, reject) {
      var record = tryCatch(generator[method], generator, arg);
      if (record.type === "throw") {
        reject(record.arg);
      } else {
        var result = record.arg;
        var value = result.value;
        if (value &&
            typeof value === "object" &&
            hasOwn.call(value, "__await")) {
          return PromiseImpl.resolve(value.__await).then(function(value) {
            invoke("next", value, resolve, reject);
          }, function(err) {
            invoke("throw", err, resolve, reject);
          });
        }

        return PromiseImpl.resolve(value).then(function(unwrapped) {
          // When a yielded Promise is resolved, its final value becomes
          // the .value of the Promise<{value,done}> result for the
          // current iteration.
          result.value = unwrapped;
          resolve(result);
        }, function(error) {
          // If a rejected Promise was yielded, throw the rejection back
          // into the async generator function so it can be handled there.
          return invoke("throw", error, resolve, reject);
        });
      }
    }

    var previousPromise;

    function enqueue(method, arg) {
      function callInvokeWithMethodAndArg() {
        return new PromiseImpl(function(resolve, reject) {
          invoke(method, arg, resolve, reject);
        });
      }

      return previousPromise =
        // If enqueue has been called before, then we want to wait until
        // all previous Promises have been resolved before calling invoke,
        // so that results are always delivered in the correct order. If
        // enqueue has not been called before, then it is important to
        // call invoke immediately, without waiting on a callback to fire,
        // so that the async generator function has the opportunity to do
        // any necessary setup in a predictable way. This predictability
        // is why the Promise constructor synchronously invokes its
        // executor callback, and why async functions synchronously
        // execute code before the first await. Since we implement simple
        // async functions in terms of async generators, it is especially
        // important to get this right, even though it requires care.
        previousPromise ? previousPromise.then(
          callInvokeWithMethodAndArg,
          // Avoid propagating failures to Promises returned by later
          // invocations of the iterator.
          callInvokeWithMethodAndArg
        ) : callInvokeWithMethodAndArg();
    }

    // Define the unified helper method that is used to implement .next,
    // .throw, and .return (see defineIteratorMethods).
    this._invoke = enqueue;
  }

  defineIteratorMethods(AsyncIterator.prototype);
  AsyncIterator.prototype[asyncIteratorSymbol] = function () {
    return this;
  };
  exports.AsyncIterator = AsyncIterator;

  // Note that simple async functions are implemented on top of
  // AsyncIterator objects; they just return a Promise for the value of
  // the final result produced by the iterator.
  exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {
    if (PromiseImpl === void 0) PromiseImpl = Promise;

    var iter = new AsyncIterator(
      wrap(innerFn, outerFn, self, tryLocsList),
      PromiseImpl
    );

    return exports.isGeneratorFunction(outerFn)
      ? iter // If outerFn is a generator, return the full iterator.
      : iter.next().then(function(result) {
          return result.done ? result.value : iter.next();
        });
  };

  function makeInvokeMethod(innerFn, self, context) {
    var state = GenStateSuspendedStart;

    return function invoke(method, arg) {
      if (state === GenStateExecuting) {
        throw new Error("Generator is already running");
      }

      if (state === GenStateCompleted) {
        if (method === "throw") {
          throw arg;
        }

        // Be forgiving, per 25.3.3.3.3 of the spec:
        // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
        return doneResult();
      }

      context.method = method;
      context.arg = arg;

      while (true) {
        var delegate = context.delegate;
        if (delegate) {
          var delegateResult = maybeInvokeDelegate(delegate, context);
          if (delegateResult) {
            if (delegateResult === ContinueSentinel) continue;
            return delegateResult;
          }
        }

        if (context.method === "next") {
          // Setting context._sent for legacy support of Babel's
          // function.sent implementation.
          context.sent = context._sent = context.arg;

        } else if (context.method === "throw") {
          if (state === GenStateSuspendedStart) {
            state = GenStateCompleted;
            throw context.arg;
          }

          context.dispatchException(context.arg);

        } else if (context.method === "return") {
          context.abrupt("return", context.arg);
        }

        state = GenStateExecuting;

        var record = tryCatch(innerFn, self, context);
        if (record.type === "normal") {
          // If an exception is thrown from innerFn, we leave state ===
          // GenStateExecuting and loop back for another invocation.
          state = context.done
            ? GenStateCompleted
            : GenStateSuspendedYield;

          if (record.arg === ContinueSentinel) {
            continue;
          }

          return {
            value: record.arg,
            done: context.done
          };

        } else if (record.type === "throw") {
          state = GenStateCompleted;
          // Dispatch the exception by looping back around to the
          // context.dispatchException(context.arg) call above.
          context.method = "throw";
          context.arg = record.arg;
        }
      }
    };
  }

  // Call delegate.iterator[context.method](context.arg) and handle the
  // result, either by returning a { value, done } result from the
  // delegate iterator, or by modifying context.method and context.arg,
  // setting context.delegate to null, and returning the ContinueSentinel.
  function maybeInvokeDelegate(delegate, context) {
    var method = delegate.iterator[context.method];
    if (method === undefined) {
      // A .throw or .return when the delegate iterator has no .throw
      // method always terminates the yield* loop.
      context.delegate = null;

      if (context.method === "throw") {
        // Note: ["return"] must be used for ES3 parsing compatibility.
        if (delegate.iterator["return"]) {
          // If the delegate iterator has a return method, give it a
          // chance to clean up.
          context.method = "return";
          context.arg = undefined;
          maybeInvokeDelegate(delegate, context);

          if (context.method === "throw") {
            // If maybeInvokeDelegate(context) changed context.method from
            // "return" to "throw", let that override the TypeError below.
            return ContinueSentinel;
          }
        }

        context.method = "throw";
        context.arg = new TypeError(
          "The iterator does not provide a 'throw' method");
      }

      return ContinueSentinel;
    }

    var record = tryCatch(method, delegate.iterator, context.arg);

    if (record.type === "throw") {
      context.method = "throw";
      context.arg = record.arg;
      context.delegate = null;
      return ContinueSentinel;
    }

    var info = record.arg;

    if (! info) {
      context.method = "throw";
      context.arg = new TypeError("iterator result is not an object");
      context.delegate = null;
      return ContinueSentinel;
    }

    if (info.done) {
      // Assign the result of the finished delegate to the temporary
      // variable specified by delegate.resultName (see delegateYield).
      context[delegate.resultName] = info.value;

      // Resume execution at the desired location (see delegateYield).
      context.next = delegate.nextLoc;

      // If context.method was "throw" but the delegate handled the
      // exception, let the outer generator proceed normally. If
      // context.method was "next", forget context.arg since it has been
      // "consumed" by the delegate iterator. If context.method was
      // "return", allow the original .return call to continue in the
      // outer generator.
      if (context.method !== "return") {
        context.method = "next";
        context.arg = undefined;
      }

    } else {
      // Re-yield the result returned by the delegate method.
      return info;
    }

    // The delegate iterator is finished, so forget it and continue with
    // the outer generator.
    context.delegate = null;
    return ContinueSentinel;
  }

  // Define Generator.prototype.{next,throw,return} in terms of the
  // unified ._invoke helper method.
  defineIteratorMethods(Gp);

  Gp[toStringTagSymbol] = "Generator";

  // A Generator should always return itself as the iterator object when the
  // @@iterator function is called on it. Some browsers' implementations of the
  // iterator prototype chain incorrectly implement this, causing the Generator
  // object to not be returned from this call. This ensures that doesn't happen.
  // See https://github.com/facebook/regenerator/issues/274 for more details.
  Gp[iteratorSymbol] = function() {
    return this;
  };

  Gp.toString = function() {
    return "[object Generator]";
  };

  function pushTryEntry(locs) {
    var entry = { tryLoc: locs[0] };

    if (1 in locs) {
      entry.catchLoc = locs[1];
    }

    if (2 in locs) {
      entry.finallyLoc = locs[2];
      entry.afterLoc = locs[3];
    }

    this.tryEntries.push(entry);
  }

  function resetTryEntry(entry) {
    var record = entry.completion || {};
    record.type = "normal";
    delete record.arg;
    entry.completion = record;
  }

  function Context(tryLocsList) {
    // The root entry object (effectively a try statement without a catch
    // or a finally block) gives us a place to store values thrown from
    // locations where there is no enclosing try statement.
    this.tryEntries = [{ tryLoc: "root" }];
    tryLocsList.forEach(pushTryEntry, this);
    this.reset(true);
  }

  exports.keys = function(object) {
    var keys = [];
    for (var key in object) {
      keys.push(key);
    }
    keys.reverse();

    // Rather than returning an object with a next method, we keep
    // things simple and return the next function itself.
    return function next() {
      while (keys.length) {
        var key = keys.pop();
        if (key in object) {
          next.value = key;
          next.done = false;
          return next;
        }
      }

      // To avoid creating an additional object, we just hang the .value
      // and .done properties off the next function object itself. This
      // also ensures that the minifier will not anonymize the function.
      next.done = true;
      return next;
    };
  };

  function values(iterable) {
    if (iterable) {
      var iteratorMethod = iterable[iteratorSymbol];
      if (iteratorMethod) {
        return iteratorMethod.call(iterable);
      }

      if (typeof iterable.next === "function") {
        return iterable;
      }

      if (!isNaN(iterable.length)) {
        var i = -1, next = function next() {
          while (++i < iterable.length) {
            if (hasOwn.call(iterable, i)) {
              next.value = iterable[i];
              next.done = false;
              return next;
            }
          }

          next.value = undefined;
          next.done = true;

          return next;
        };

        return next.next = next;
      }
    }

    // Return an iterator with no values.
    return { next: doneResult };
  }
  exports.values = values;

  function doneResult() {
    return { value: undefined, done: true };
  }

  Context.prototype = {
    constructor: Context,

    reset: function(skipTempReset) {
      this.prev = 0;
      this.next = 0;
      // Resetting context._sent for legacy support of Babel's
      // function.sent implementation.
      this.sent = this._sent = undefined;
      this.done = false;
      this.delegate = null;

      this.method = "next";
      this.arg = undefined;

      this.tryEntries.forEach(resetTryEntry);

      if (!skipTempReset) {
        for (var name in this) {
          // Not sure about the optimal order of these conditions:
          if (name.charAt(0) === "t" &&
              hasOwn.call(this, name) &&
              !isNaN(+name.slice(1))) {
            this[name] = undefined;
          }
        }
      }
    },

    stop: function() {
      this.done = true;

      var rootEntry = this.tryEntries[0];
      var rootRecord = rootEntry.completion;
      if (rootRecord.type === "throw") {
        throw rootRecord.arg;
      }

      return this.rval;
    },

    dispatchException: function(exception) {
      if (this.done) {
        throw exception;
      }

      var context = this;
      function handle(loc, caught) {
        record.type = "throw";
        record.arg = exception;
        context.next = loc;

        if (caught) {
          // If the dispatched exception was caught by a catch block,
          // then let that catch block handle the exception normally.
          context.method = "next";
          context.arg = undefined;
        }

        return !! caught;
      }

      for (var i = this.tryEntries.length - 1; i >= 0; --i) {
        var entry = this.tryEntries[i];
        var record = entry.completion;

        if (entry.tryLoc === "root") {
          // Exception thrown outside of any try block that could handle
          // it, so set the completion value of the entire function to
          // throw the exception.
          return handle("end");
        }

        if (entry.tryLoc <= this.prev) {
          var hasCatch = hasOwn.call(entry, "catchLoc");
          var hasFinally = hasOwn.call(entry, "finallyLoc");

          if (hasCatch && hasFinally) {
            if (this.prev < entry.catchLoc) {
              return handle(entry.catchLoc, true);
            } else if (this.prev < entry.finallyLoc) {
              return handle(entry.finallyLoc);
            }

          } else if (hasCatch) {
            if (this.prev < entry.catchLoc) {
              return handle(entry.catchLoc, true);
            }

          } else if (hasFinally) {
            if (this.prev < entry.finallyLoc) {
              return handle(entry.finallyLoc);
            }

          } else {
            throw new Error("try statement without catch or finally");
          }
        }
      }
    },

    abrupt: function(type, arg) {
      for (var i = this.tryEntries.length - 1; i >= 0; --i) {
        var entry = this.tryEntries[i];
        if (entry.tryLoc <= this.prev &&
            hasOwn.call(entry, "finallyLoc") &&
            this.prev < entry.finallyLoc) {
          var finallyEntry = entry;
          break;
        }
      }

      if (finallyEntry &&
          (type === "break" ||
           type === "continue") &&
          finallyEntry.tryLoc <= arg &&
          arg <= finallyEntry.finallyLoc) {
        // Ignore the finally entry if control is not jumping to a
        // location outside the try/catch block.
        finallyEntry = null;
      }

      var record = finallyEntry ? finallyEntry.completion : {};
      record.type = type;
      record.arg = arg;

      if (finallyEntry) {
        this.method = "next";
        this.next = finallyEntry.finallyLoc;
        return ContinueSentinel;
      }

      return this.complete(record);
    },

    complete: function(record, afterLoc) {
      if (record.type === "throw") {
        throw record.arg;
      }

      if (record.type === "break" ||
          record.type === "continue") {
        this.next = record.arg;
      } else if (record.type === "return") {
        this.rval = this.arg = record.arg;
        this.method = "return";
        this.next = "end";
      } else if (record.type === "normal" && afterLoc) {
        this.next = afterLoc;
      }

      return ContinueSentinel;
    },

    finish: function(finallyLoc) {
      for (var i = this.tryEntries.length - 1; i >= 0; --i) {
        var entry = this.tryEntries[i];
        if (entry.finallyLoc === finallyLoc) {
          this.complete(entry.completion, entry.afterLoc);
          resetTryEntry(entry);
          return ContinueSentinel;
        }
      }
    },

    "catch": function(tryLoc) {
      for (var i = this.tryEntries.length - 1; i >= 0; --i) {
        var entry = this.tryEntries[i];
        if (entry.tryLoc === tryLoc) {
          var record = entry.completion;
          if (record.type === "throw") {
            var thrown = record.arg;
            resetTryEntry(entry);
          }
          return thrown;
        }
      }

      // The context.catch method must only be called with a location
      // argument that corresponds to a known catch block.
      throw new Error("illegal catch attempt");
    },

    delegateYield: function(iterable, resultName, nextLoc) {
      this.delegate = {
        iterator: values(iterable),
        resultName: resultName,
        nextLoc: nextLoc
      };

      if (this.method === "next") {
        // Deliberately forget the last sent value so that we don't
        // accidentally pass it on to the delegate.
        this.arg = undefined;
      }

      return ContinueSentinel;
    }
  };

  // Regardless of whether this script is executing as a CommonJS module
  // or not, return the runtime object so that we can declare the variable
  // regeneratorRuntime in the outer scope, which allows this module to be
  // injected easily by `bin/regenerator --include-runtime script.js`.
  return exports;

}(
  // If this script is executing as a CommonJS module, use module.exports
  // as the regeneratorRuntime namespace. Otherwise create a new empty
  // object. Either way, the resulting object will be used to initialize
  // the regeneratorRuntime variable at the top of this file.
  typeof module === "object" ? module.exports : {}
));

try {
  regeneratorRuntime = runtime;
} catch (accidentalStrictMode) {
  // This module should not be running in strict mode, so the above
  // assignment should always work unless something is misconfigured. Just
  // in case runtime.js accidentally runs in strict mode, we can escape
  // strict mode using a global Function call. This could conceivably fail
  // if a Content Security Policy forbids using Function, but in that case
  // the proper solution is to fix the accidental strict mode problem. If
  // you've misconfigured your bundler to force strict mode and applied a
  // CSP to forbid Function, and you're not willing to fix either of those
  // problems, please detail your unique predicament in a GitHub issue.
  Function("r", "regeneratorRuntime = r")(runtime);
}

},{}],"../node_modules/@babel/runtime/regenerator/index.js":[function(require,module,exports) {
module.exports = require("regenerator-runtime");

},{"regenerator-runtime":"../node_modules/regenerator-runtime/runtime.js"}],"../node_modules/orderedmap/index.es.js":[function(require,module,exports) {
"use strict";

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

// ::- Persistent data structure representing an ordered mapping from
// strings to values, with some convenient update methods.
function OrderedMap(content) {
  this.content = content;
}

OrderedMap.prototype = {
  constructor: OrderedMap,
  find: function (key) {
    for (var i = 0; i < this.content.length; i += 2) if (this.content[i] === key) return i;

    return -1;
  },
  // :: (string) → ?any
  // Retrieve the value stored under `key`, or return undefined when
  // no such key exists.
  get: function (key) {
    var found = this.find(key);
    return found == -1 ? undefined : this.content[found + 1];
  },
  // :: (string, any, ?string) → OrderedMap
  // Create a new map by replacing the value of `key` with a new
  // value, or adding a binding to the end of the map. If `newKey` is
  // given, the key of the binding will be replaced with that key.
  update: function (key, value, newKey) {
    var self = newKey && newKey != key ? this.remove(newKey) : this;
    var found = self.find(key),
        content = self.content.slice();

    if (found == -1) {
      content.push(newKey || key, value);
    } else {
      content[found + 1] = value;
      if (newKey) content[found] = newKey;
    }

    return new OrderedMap(content);
  },
  // :: (string) → OrderedMap
  // Return a map with the given key removed, if it existed.
  remove: function (key) {
    var found = this.find(key);
    if (found == -1) return this;
    var content = this.content.slice();
    content.splice(found, 2);
    return new OrderedMap(content);
  },
  // :: (string, any) → OrderedMap
  // Add a new key to the start of the map.
  addToStart: function (key, value) {
    return new OrderedMap([key, value].concat(this.remove(key).content));
  },
  // :: (string, any) → OrderedMap
  // Add a new key to the end of the map.
  addToEnd: function (key, value) {
    var content = this.remove(key).content.slice();
    content.push(key, value);
    return new OrderedMap(content);
  },
  // :: (string, string, any) → OrderedMap
  // Add a key after the given key. If `place` is not found, the new
  // key is added to the end.
  addBefore: function (place, key, value) {
    var without = this.remove(key),
        content = without.content.slice();
    var found = without.find(place);
    content.splice(found == -1 ? content.length : found, 0, key, value);
    return new OrderedMap(content);
  },
  // :: ((key: string, value: any))
  // Call the given function for each key/value pair in the map, in
  // order.
  forEach: function (f) {
    for (var i = 0; i < this.content.length; i += 2) f(this.content[i], this.content[i + 1]);
  },
  // :: (union<Object, OrderedMap>) → OrderedMap
  // Create a new map by prepending the keys in this map that don't
  // appear in `map` before the keys in `map`.
  prepend: function (map) {
    map = OrderedMap.from(map);
    if (!map.size) return this;
    return new OrderedMap(map.content.concat(this.subtract(map).content));
  },
  // :: (union<Object, OrderedMap>) → OrderedMap
  // Create a new map by appending the keys in this map that don't
  // appear in `map` after the keys in `map`.
  append: function (map) {
    map = OrderedMap.from(map);
    if (!map.size) return this;
    return new OrderedMap(this.subtract(map).content.concat(map.content));
  },
  // :: (union<Object, OrderedMap>) → OrderedMap
  // Create a map containing all the keys in this map that don't
  // appear in `map`.
  subtract: function (map) {
    var result = this;
    map = OrderedMap.from(map);

    for (var i = 0; i < map.content.length; i += 2) result = result.remove(map.content[i]);

    return result;
  },

  // :: number
  // The amount of keys in this map.
  get size() {
    return this.content.length >> 1;
  }

}; // :: (?union<Object, OrderedMap>) → OrderedMap
// Return a map with the given content. If null, create an empty
// map. If given an ordered map, return that map itself. If given an
// object, create a map from the object's properties.

OrderedMap.from = function (value) {
  if (value instanceof OrderedMap) return value;
  var content = [];
  if (value) for (var prop in value) content.push(prop, value[prop]);
  return new OrderedMap(content);
};

var orderedmap = OrderedMap;
var _default = orderedmap;
exports.default = _default;
},{}],"../node_modules/prosemirror-model/dist/index.es.js":[function(require,module,exports) {
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ReplaceError = ReplaceError;
exports.Slice = exports.Schema = exports.ResolvedPos = exports.NodeType = exports.NodeRange = exports.Node = exports.MarkType = exports.Mark = exports.Fragment = exports.DOMSerializer = exports.DOMParser = exports.ContentMatch = void 0;

var _orderedmap = _interopRequireDefault(require("orderedmap"));

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

function findDiffStart(a, b, pos) {
  for (var i = 0;; i++) {
    if (i == a.childCount || i == b.childCount) {
      return a.childCount == b.childCount ? null : pos;
    }

    var childA = a.child(i),
        childB = b.child(i);

    if (childA == childB) {
      pos += childA.nodeSize;
      continue;
    }

    if (!childA.sameMarkup(childB)) {
      return pos;
    }

    if (childA.isText && childA.text != childB.text) {
      for (var j = 0; childA.text[j] == childB.text[j]; j++) {
        pos++;
      }

      return pos;
    }

    if (childA.content.size || childB.content.size) {
      var inner = findDiffStart(childA.content, childB.content, pos + 1);

      if (inner != null) {
        return inner;
      }
    }

    pos += childA.nodeSize;
  }
}

function findDiffEnd(a, b, posA, posB) {
  for (var iA = a.childCount, iB = b.childCount;;) {
    if (iA == 0 || iB == 0) {
      return iA == iB ? null : {
        a: posA,
        b: posB
      };
    }

    var childA = a.child(--iA),
        childB = b.child(--iB),
        size = childA.nodeSize;

    if (childA == childB) {
      posA -= size;
      posB -= size;
      continue;
    }

    if (!childA.sameMarkup(childB)) {
      return {
        a: posA,
        b: posB
      };
    }

    if (childA.isText && childA.text != childB.text) {
      var same = 0,
          minSize = Math.min(childA.text.length, childB.text.length);

      while (same < minSize && childA.text[childA.text.length - same - 1] == childB.text[childB.text.length - same - 1]) {
        same++;
        posA--;
        posB--;
      }

      return {
        a: posA,
        b: posB
      };
    }

    if (childA.content.size || childB.content.size) {
      var inner = findDiffEnd(childA.content, childB.content, posA - 1, posB - 1);

      if (inner) {
        return inner;
      }
    }

    posA -= size;
    posB -= size;
  }
} // ::- A fragment represents a node's collection of child nodes.
//
// Like nodes, fragments are persistent data structures, and you
// should not mutate them or their content. Rather, you create new
// instances whenever needed. The API tries to make this easy.


var Fragment = function Fragment(content, size) {
  this.content = content; // :: number
  // The size of the fragment, which is the total of the size of its
  // content nodes.

  this.size = size || 0;

  if (size == null) {
    for (var i = 0; i < content.length; i++) {
      this.size += content[i].nodeSize;
    }
  }
};

exports.Fragment = Fragment;
var prototypeAccessors = {
  firstChild: {
    configurable: true
  },
  lastChild: {
    configurable: true
  },
  childCount: {
    configurable: true
  }
}; // :: (number, number, (node: Node, start: number, parent: Node, index: number) → ?bool, ?number)
// Invoke a callback for all descendant nodes between the given two
// positions (relative to start of this fragment). Doesn't descend
// into a node when the callback returns `false`.

Fragment.prototype.nodesBetween = function nodesBetween(from, to, f, nodeStart, parent) {
  if (nodeStart === void 0) nodeStart = 0;

  for (var i = 0, pos = 0; pos < to; i++) {
    var child = this.content[i],
        end = pos + child.nodeSize;

    if (end > from && f(child, nodeStart + pos, parent, i) !== false && child.content.size) {
      var start = pos + 1;
      child.nodesBetween(Math.max(0, from - start), Math.min(child.content.size, to - start), f, nodeStart + start);
    }

    pos = end;
  }
}; // :: ((node: Node, pos: number, parent: Node) → ?bool)
// Call the given callback for every descendant node. The callback
// may return `false` to prevent traversal of a given node's children.


Fragment.prototype.descendants = function descendants(f) {
  this.nodesBetween(0, this.size, f);
}; // : (number, number, ?string, ?string) → string


Fragment.prototype.textBetween = function textBetween(from, to, blockSeparator, leafText) {
  var text = "",
      separated = true;
  this.nodesBetween(from, to, function (node, pos) {
    if (node.isText) {
      text += node.text.slice(Math.max(from, pos) - pos, to - pos);
      separated = !blockSeparator;
    } else if (node.isLeaf && leafText) {
      text += leafText;
      separated = !blockSeparator;
    } else if (!separated && node.isBlock) {
      text += blockSeparator;
      separated = true;
    }
  }, 0);
  return text;
}; // :: (Fragment) → Fragment
// Create a new fragment containing the combined content of this
// fragment and the other.


Fragment.prototype.append = function append(other) {
  if (!other.size) {
    return this;
  }

  if (!this.size) {
    return other;
  }

  var last = this.lastChild,
      first = other.firstChild,
      content = this.content.slice(),
      i = 0;

  if (last.isText && last.sameMarkup(first)) {
    content[content.length - 1] = last.withText(last.text + first.text);
    i = 1;
  }

  for (; i < other.content.length; i++) {
    content.push(other.content[i]);
  }

  return new Fragment(content, this.size + other.size);
}; // :: (number, ?number) → Fragment
// Cut out the sub-fragment between the two given positions.


Fragment.prototype.cut = function cut(from, to) {
  if (to == null) {
    to = this.size;
  }

  if (from == 0 && to == this.size) {
    return this;
  }

  var result = [],
      size = 0;

  if (to > from) {
    for (var i = 0, pos = 0; pos < to; i++) {
      var child = this.content[i],
          end = pos + child.nodeSize;

      if (end > from) {
        if (pos < from || end > to) {
          if (child.isText) {
            child = child.cut(Math.max(0, from - pos), Math.min(child.text.length, to - pos));
          } else {
            child = child.cut(Math.max(0, from - pos - 1), Math.min(child.content.size, to - pos - 1));
          }
        }

        result.push(child);
        size += child.nodeSize;
      }

      pos = end;
    }
  }

  return new Fragment(result, size);
};

Fragment.prototype.cutByIndex = function cutByIndex(from, to) {
  if (from == to) {
    return Fragment.empty;
  }

  if (from == 0 && to == this.content.length) {
    return this;
  }

  return new Fragment(this.content.slice(from, to));
}; // :: (number, Node) → Fragment
// Create a new fragment in which the node at the given index is
// replaced by the given node.


Fragment.prototype.replaceChild = function replaceChild(index, node) {
  var current = this.content[index];

  if (current == node) {
    return this;
  }

  var copy = this.content.slice();
  var size = this.size + node.nodeSize - current.nodeSize;
  copy[index] = node;
  return new Fragment(copy, size);
}; // : (Node) → Fragment
// Create a new fragment by prepending the given node to this
// fragment.


Fragment.prototype.addToStart = function addToStart(node) {
  return new Fragment([node].concat(this.content), this.size + node.nodeSize);
}; // : (Node) → Fragment
// Create a new fragment by appending the given node to this
// fragment.


Fragment.prototype.addToEnd = function addToEnd(node) {
  return new Fragment(this.content.concat(node), this.size + node.nodeSize);
}; // :: (Fragment) → bool
// Compare this fragment to another one.


Fragment.prototype.eq = function eq(other) {
  if (this.content.length != other.content.length) {
    return false;
  }

  for (var i = 0; i < this.content.length; i++) {
    if (!this.content[i].eq(other.content[i])) {
      return false;
    }
  }

  return true;
}; // :: ?Node
// The first child of the fragment, or `null` if it is empty.


prototypeAccessors.firstChild.get = function () {
  return this.content.length ? this.content[0] : null;
}; // :: ?Node
// The last child of the fragment, or `null` if it is empty.


prototypeAccessors.lastChild.get = function () {
  return this.content.length ? this.content[this.content.length - 1] : null;
}; // :: number
// The number of child nodes in this fragment.


prototypeAccessors.childCount.get = function () {
  return this.content.length;
}; // :: (number) → Node
// Get the child node at the given index. Raise an error when the
// index is out of range.


Fragment.prototype.child = function child(index) {
  var found = this.content[index];

  if (!found) {
    throw new RangeError("Index " + index + " out of range for " + this);
  }

  return found;
}; // :: (number) → ?Node
// Get the child node at the given index, if it exists.


Fragment.prototype.maybeChild = function maybeChild(index) {
  return this.content[index];
}; // :: ((node: Node, offset: number, index: number))
// Call `f` for every child node, passing the node, its offset
// into this parent node, and its index.


Fragment.prototype.forEach = function forEach(f) {
  for (var i = 0, p = 0; i < this.content.length; i++) {
    var child = this.content[i];
    f(child, p, i);
    p += child.nodeSize;
  }
}; // :: (Fragment) → ?number
// Find the first position at which this fragment and another
// fragment differ, or `null` if they are the same.


Fragment.prototype.findDiffStart = function findDiffStart$1(other, pos) {
  if (pos === void 0) pos = 0;
  return findDiffStart(this, other, pos);
}; // :: (Fragment) → ?{a: number, b: number}
// Find the first position, searching from the end, at which this
// fragment and the given fragment differ, or `null` if they are the
// same. Since this position will not be the same in both nodes, an
// object with two separate positions is returned.


Fragment.prototype.findDiffEnd = function findDiffEnd$1(other, pos, otherPos) {
  if (pos === void 0) pos = this.size;
  if (otherPos === void 0) otherPos = other.size;
  return findDiffEnd(this, other, pos, otherPos);
}; // : (number, ?number) → {index: number, offset: number}
// Find the index and inner offset corresponding to a given relative
// position in this fragment. The result object will be reused
// (overwritten) the next time the function is called. (Not public.)


Fragment.prototype.findIndex = function findIndex(pos, round) {
  if (round === void 0) round = -1;

  if (pos == 0) {
    return retIndex(0, pos);
  }

  if (pos == this.size) {
    return retIndex(this.content.length, pos);
  }

  if (pos > this.size || pos < 0) {
    throw new RangeError("Position " + pos + " outside of fragment (" + this + ")");
  }

  for (var i = 0, curPos = 0;; i++) {
    var cur = this.child(i),
        end = curPos + cur.nodeSize;

    if (end >= pos) {
      if (end == pos || round > 0) {
        return retIndex(i + 1, end);
      }

      return retIndex(i, curPos);
    }

    curPos = end;
  }
}; // :: () → string
// Return a debugging string that describes this fragment.


Fragment.prototype.toString = function toString() {
  return "<" + this.toStringInner() + ">";
};

Fragment.prototype.toStringInner = function toStringInner() {
  return this.content.join(", ");
}; // :: () → ?Object
// Create a JSON-serializeable representation of this fragment.


Fragment.prototype.toJSON = function toJSON() {
  return this.content.length ? this.content.map(function (n) {
    return n.toJSON();
  }) : null;
}; // :: (Schema, ?Object) → Fragment
// Deserialize a fragment from its JSON representation.


Fragment.fromJSON = function fromJSON(schema, value) {
  if (!value) {
    return Fragment.empty;
  }

  if (!Array.isArray(value)) {
    throw new RangeError("Invalid input for Fragment.fromJSON");
  }

  return new Fragment(value.map(schema.nodeFromJSON));
}; // :: ([Node]) → Fragment
// Build a fragment from an array of nodes. Ensures that adjacent
// text nodes with the same marks are joined together.


Fragment.fromArray = function fromArray(array) {
  if (!array.length) {
    return Fragment.empty;
  }

  var joined,
      size = 0;

  for (var i = 0; i < array.length; i++) {
    var node = array[i];
    size += node.nodeSize;

    if (i && node.isText && array[i - 1].sameMarkup(node)) {
      if (!joined) {
        joined = array.slice(0, i);
      }

      joined[joined.length - 1] = node.withText(joined[joined.length - 1].text + node.text);
    } else if (joined) {
      joined.push(node);
    }
  }

  return new Fragment(joined || array, size);
}; // :: (?union<Fragment, Node, [Node]>) → Fragment
// Create a fragment from something that can be interpreted as a set
// of nodes. For `null`, it returns the empty fragment. For a
// fragment, the fragment itself. For a node or array of nodes, a
// fragment containing those nodes.


Fragment.from = function from(nodes) {
  if (!nodes) {
    return Fragment.empty;
  }

  if (nodes instanceof Fragment) {
    return nodes;
  }

  if (Array.isArray(nodes)) {
    return this.fromArray(nodes);
  }

  if (nodes.attrs) {
    return new Fragment([nodes], nodes.nodeSize);
  }

  throw new RangeError("Can not convert " + nodes + " to a Fragment" + (nodes.nodesBetween ? " (looks like multiple versions of prosemirror-model were loaded)" : ""));
};

Object.defineProperties(Fragment.prototype, prototypeAccessors);
var found = {
  index: 0,
  offset: 0
};

function retIndex(index, offset) {
  found.index = index;
  found.offset = offset;
  return found;
} // :: Fragment
// An empty fragment. Intended to be reused whenever a node doesn't
// contain anything (rather than allocating a new empty fragment for
// each leaf node).


Fragment.empty = new Fragment([], 0);

function compareDeep(a, b) {
  if (a === b) {
    return true;
  }

  if (!(a && typeof a == "object") || !(b && typeof b == "object")) {
    return false;
  }

  var array = Array.isArray(a);

  if (Array.isArray(b) != array) {
    return false;
  }

  if (array) {
    if (a.length != b.length) {
      return false;
    }

    for (var i = 0; i < a.length; i++) {
      if (!compareDeep(a[i], b[i])) {
        return false;
      }
    }
  } else {
    for (var p in a) {
      if (!(p in b) || !compareDeep(a[p], b[p])) {
        return false;
      }
    }

    for (var p$1 in b) {
      if (!(p$1 in a)) {
        return false;
      }
    }
  }

  return true;
} // ::- A mark is a piece of information that can be attached to a node,
// such as it being emphasized, in code font, or a link. It has a type
// and optionally a set of attributes that provide further information
// (such as the target of the link). Marks are created through a
// `Schema`, which controls which types exist and which
// attributes they have.


var Mark = function Mark(type, attrs) {
  // :: MarkType
  // The type of this mark.
  this.type = type; // :: Object
  // The attributes associated with this mark.

  this.attrs = attrs;
}; // :: ([Mark]) → [Mark]
// Given a set of marks, create a new set which contains this one as
// well, in the right position. If this mark is already in the set,
// the set itself is returned. If any marks that are set to be
// [exclusive](#model.MarkSpec.excludes) with this mark are present,
// those are replaced by this one.


exports.Mark = Mark;

Mark.prototype.addToSet = function addToSet(set) {
  var copy,
      placed = false;

  for (var i = 0; i < set.length; i++) {
    var other = set[i];

    if (this.eq(other)) {
      return set;
    }

    if (this.type.excludes(other.type)) {
      if (!copy) {
        copy = set.slice(0, i);
      }
    } else if (other.type.excludes(this.type)) {
      return set;
    } else {
      if (!placed && other.type.rank > this.type.rank) {
        if (!copy) {
          copy = set.slice(0, i);
        }

        copy.push(this);
        placed = true;
      }

      if (copy) {
        copy.push(other);
      }
    }
  }

  if (!copy) {
    copy = set.slice();
  }

  if (!placed) {
    copy.push(this);
  }

  return copy;
}; // :: ([Mark]) → [Mark]
// Remove this mark from the given set, returning a new set. If this
// mark is not in the set, the set itself is returned.


Mark.prototype.removeFromSet = function removeFromSet(set) {
  for (var i = 0; i < set.length; i++) {
    if (this.eq(set[i])) {
      return set.slice(0, i).concat(set.slice(i + 1));
    }
  }

  return set;
}; // :: ([Mark]) → bool
// Test whether this mark is in the given set of marks.


Mark.prototype.isInSet = function isInSet(set) {
  for (var i = 0; i < set.length; i++) {
    if (this.eq(set[i])) {
      return true;
    }
  }

  return false;
}; // :: (Mark) → bool
// Test whether this mark has the same type and attributes as
// another mark.


Mark.prototype.eq = function eq(other) {
  return this == other || this.type == other.type && compareDeep(this.attrs, other.attrs);
}; // :: () → Object
// Convert this mark to a JSON-serializeable representation.


Mark.prototype.toJSON = function toJSON() {
  var obj = {
    type: this.type.name
  };

  for (var _ in this.attrs) {
    obj.attrs = this.attrs;
    break;
  }

  return obj;
}; // :: (Schema, Object) → Mark


Mark.fromJSON = function fromJSON(schema, json) {
  if (!json) {
    throw new RangeError("Invalid input for Mark.fromJSON");
  }

  var type = schema.marks[json.type];

  if (!type) {
    throw new RangeError("There is no mark type " + json.type + " in this schema");
  }

  return type.create(json.attrs);
}; // :: ([Mark], [Mark]) → bool
// Test whether two sets of marks are identical.


Mark.sameSet = function sameSet(a, b) {
  if (a == b) {
    return true;
  }

  if (a.length != b.length) {
    return false;
  }

  for (var i = 0; i < a.length; i++) {
    if (!a[i].eq(b[i])) {
      return false;
    }
  }

  return true;
}; // :: (?union<Mark, [Mark]>) → [Mark]
// Create a properly sorted mark set from null, a single mark, or an
// unsorted array of marks.


Mark.setFrom = function setFrom(marks) {
  if (!marks || marks.length == 0) {
    return Mark.none;
  }

  if (marks instanceof Mark) {
    return [marks];
  }

  var copy = marks.slice();
  copy.sort(function (a, b) {
    return a.type.rank - b.type.rank;
  });
  return copy;
}; // :: [Mark] The empty set of marks.


Mark.none = []; // ReplaceError:: class extends Error
// Error type raised by [`Node.replace`](#model.Node.replace) when
// given an invalid replacement.

function ReplaceError(message) {
  var err = Error.call(this, message);
  err.__proto__ = ReplaceError.prototype;
  return err;
}

ReplaceError.prototype = Object.create(Error.prototype);
ReplaceError.prototype.constructor = ReplaceError;
ReplaceError.prototype.name = "ReplaceError"; // ::- A slice represents a piece cut out of a larger document. It
// stores not only a fragment, but also the depth up to which nodes on
// both side are ‘open’ (cut through).

var Slice = function Slice(content, openStart, openEnd) {
  // :: Fragment The slice's content.
  this.content = content; // :: number The open depth at the start.

  this.openStart = openStart; // :: number The open depth at the end.

  this.openEnd = openEnd;
};

exports.Slice = Slice;
var prototypeAccessors$1 = {
  size: {
    configurable: true
  }
}; // :: number
// The size this slice would add when inserted into a document.

prototypeAccessors$1.size.get = function () {
  return this.content.size - this.openStart - this.openEnd;
};

Slice.prototype.insertAt = function insertAt(pos, fragment) {
  var content = insertInto(this.content, pos + this.openStart, fragment, null);
  return content && new Slice(content, this.openStart, this.openEnd);
};

Slice.prototype.removeBetween = function removeBetween(from, to) {
  return new Slice(removeRange(this.content, from + this.openStart, to + this.openStart), this.openStart, this.openEnd);
}; // :: (Slice) → bool
// Tests whether this slice is equal to another slice.


Slice.prototype.eq = function eq(other) {
  return this.content.eq(other.content) && this.openStart == other.openStart && this.openEnd == other.openEnd;
};

Slice.prototype.toString = function toString() {
  return this.content + "(" + this.openStart + "," + this.openEnd + ")";
}; // :: () → ?Object
// Convert a slice to a JSON-serializable representation.


Slice.prototype.toJSON = function toJSON() {
  if (!this.content.size) {
    return null;
  }

  var json = {
    content: this.content.toJSON()
  };

  if (this.openStart > 0) {
    json.openStart = this.openStart;
  }

  if (this.openEnd > 0) {
    json.openEnd = this.openEnd;
  }

  return json;
}; // :: (Schema, ?Object) → Slice
// Deserialize a slice from its JSON representation.


Slice.fromJSON = function fromJSON(schema, json) {
  if (!json) {
    return Slice.empty;
  }

  var openStart = json.openStart || 0,
      openEnd = json.openEnd || 0;

  if (typeof openStart != "number" || typeof openEnd != "number") {
    throw new RangeError("Invalid input for Slice.fromJSON");
  }

  return new Slice(Fragment.fromJSON(schema, json.content), json.openStart || 0, json.openEnd || 0);
}; // :: (Fragment, ?bool) → Slice
// Create a slice from a fragment by taking the maximum possible
// open value on both side of the fragment.


Slice.maxOpen = function maxOpen(fragment, openIsolating) {
  if (openIsolating === void 0) openIsolating = true;
  var openStart = 0,
      openEnd = 0;

  for (var n = fragment.firstChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.firstChild) {
    openStart++;
  }

  for (var n$1 = fragment.lastChild; n$1 && !n$1.isLeaf && (openIsolating || !n$1.type.spec.isolating); n$1 = n$1.lastChild) {
    openEnd++;
  }

  return new Slice(fragment, openStart, openEnd);
};

Object.defineProperties(Slice.prototype, prototypeAccessors$1);

function removeRange(content, from, to) {
  var ref = content.findIndex(from);
  var index = ref.index;
  var offset = ref.offset;
  var child = content.maybeChild(index);
  var ref$1 = content.findIndex(to);
  var indexTo = ref$1.index;
  var offsetTo = ref$1.offset;

  if (offset == from || child.isText) {
    if (offsetTo != to && !content.child(indexTo).isText) {
      throw new RangeError("Removing non-flat range");
    }

    return content.cut(0, from).append(content.cut(to));
  }

  if (index != indexTo) {
    throw new RangeError("Removing non-flat range");
  }

  return content.replaceChild(index, child.copy(removeRange(child.content, from - offset - 1, to - offset - 1)));
}

function insertInto(content, dist, insert, parent) {
  var ref = content.findIndex(dist);
  var index = ref.index;
  var offset = ref.offset;
  var child = content.maybeChild(index);

  if (offset == dist || child.isText) {
    if (parent && !parent.canReplace(index, index, insert)) {
      return null;
    }

    return content.cut(0, dist).append(insert).append(content.cut(dist));
  }

  var inner = insertInto(child.content, dist - offset - 1, insert);
  return inner && content.replaceChild(index, child.copy(inner));
} // :: Slice
// The empty slice.


Slice.empty = new Slice(Fragment.empty, 0, 0);

function replace($from, $to, slice) {
  if (slice.openStart > $from.depth) {
    throw new ReplaceError("Inserted content deeper than insertion position");
  }

  if ($from.depth - slice.openStart != $to.depth - slice.openEnd) {
    throw new ReplaceError("Inconsistent open depths");
  }

  return replaceOuter($from, $to, slice, 0);
}

function replaceOuter($from, $to, slice, depth) {
  var index = $from.index(depth),
      node = $from.node(depth);

  if (index == $to.index(depth) && depth < $from.depth - slice.openStart) {
    var inner = replaceOuter($from, $to, slice, depth + 1);
    return node.copy(node.content.replaceChild(index, inner));
  } else if (!slice.content.size) {
    return close(node, replaceTwoWay($from, $to, depth));
  } else if (!slice.openStart && !slice.openEnd && $from.depth == depth && $to.depth == depth) {
    // Simple, flat case
    var parent = $from.parent,
        content = parent.content;
    return close(parent, content.cut(0, $from.parentOffset).append(slice.content).append(content.cut($to.parentOffset)));
  } else {
    var ref = prepareSliceForReplace(slice, $from);
    var start = ref.start;
    var end = ref.end;
    return close(node, replaceThreeWay($from, start, end, $to, depth));
  }
}

function checkJoin(main, sub) {
  if (!sub.type.compatibleContent(main.type)) {
    throw new ReplaceError("Cannot join " + sub.type.name + " onto " + main.type.name);
  }
}

function joinable($before, $after, depth) {
  var node = $before.node(depth);
  checkJoin(node, $after.node(depth));
  return node;
}

function addNode(child, target) {
  var last = target.length - 1;

  if (last >= 0 && child.isText && child.sameMarkup(target[last])) {
    target[last] = child.withText(target[last].text + child.text);
  } else {
    target.push(child);
  }
}

function addRange($start, $end, depth, target) {
  var node = ($end || $start).node(depth);
  var startIndex = 0,
      endIndex = $end ? $end.index(depth) : node.childCount;

  if ($start) {
    startIndex = $start.index(depth);

    if ($start.depth > depth) {
      startIndex++;
    } else if ($start.textOffset) {
      addNode($start.nodeAfter, target);
      startIndex++;
    }
  }

  for (var i = startIndex; i < endIndex; i++) {
    addNode(node.child(i), target);
  }

  if ($end && $end.depth == depth && $end.textOffset) {
    addNode($end.nodeBefore, target);
  }
}

function close(node, content) {
  if (!node.type.validContent(content)) {
    throw new ReplaceError("Invalid content for node " + node.type.name);
  }

  return node.copy(content);
}

function replaceThreeWay($from, $start, $end, $to, depth) {
  var openStart = $from.depth > depth && joinable($from, $start, depth + 1);
  var openEnd = $to.depth > depth && joinable($end, $to, depth + 1);
  var content = [];
  addRange(null, $from, depth, content);

  if (openStart && openEnd && $start.index(depth) == $end.index(depth)) {
    checkJoin(openStart, openEnd);
    addNode(close(openStart, replaceThreeWay($from, $start, $end, $to, depth + 1)), content);
  } else {
    if (openStart) {
      addNode(close(openStart, replaceTwoWay($from, $start, depth + 1)), content);
    }

    addRange($start, $end, depth, content);

    if (openEnd) {
      addNode(close(openEnd, replaceTwoWay($end, $to, depth + 1)), content);
    }
  }

  addRange($to, null, depth, content);
  return new Fragment(content);
}

function replaceTwoWay($from, $to, depth) {
  var content = [];
  addRange(null, $from, depth, content);

  if ($from.depth > depth) {
    var type = joinable($from, $to, depth + 1);
    addNode(close(type, replaceTwoWay($from, $to, depth + 1)), content);
  }

  addRange($to, null, depth, content);
  return new Fragment(content);
}

function prepareSliceForReplace(slice, $along) {
  var extra = $along.depth - slice.openStart,
      parent = $along.node(extra);
  var node = parent.copy(slice.content);

  for (var i = extra - 1; i >= 0; i--) {
    node = $along.node(i).copy(Fragment.from(node));
  }

  return {
    start: node.resolveNoCache(slice.openStart + extra),
    end: node.resolveNoCache(node.content.size - slice.openEnd - extra)
  };
} // ::- You can [_resolve_](#model.Node.resolve) a position to get more
// information about it. Objects of this class represent such a
// resolved position, providing various pieces of context information,
// and some helper methods.
//
// Throughout this interface, methods that take an optional `depth`
// parameter will interpret undefined as `this.depth` and negative
// numbers as `this.depth + value`.


var ResolvedPos = function ResolvedPos(pos, path, parentOffset) {
  // :: number The position that was resolved.
  this.pos = pos;
  this.path = path; // :: number
  // The number of levels the parent node is from the root. If this
  // position points directly into the root node, it is 0. If it
  // points into a top-level paragraph, 1, and so on.

  this.depth = path.length / 3 - 1; // :: number The offset this position has into its parent node.

  this.parentOffset = parentOffset;
};

exports.ResolvedPos = ResolvedPos;
var prototypeAccessors$2 = {
  parent: {
    configurable: true
  },
  doc: {
    configurable: true
  },
  textOffset: {
    configurable: true
  },
  nodeAfter: {
    configurable: true
  },
  nodeBefore: {
    configurable: true
  }
};

ResolvedPos.prototype.resolveDepth = function resolveDepth(val) {
  if (val == null) {
    return this.depth;
  }

  if (val < 0) {
    return this.depth + val;
  }

  return val;
}; // :: Node
// The parent node that the position points into. Note that even if
// a position points into a text node, that node is not considered
// the parent—text nodes are ‘flat’ in this model, and have no content.


prototypeAccessors$2.parent.get = function () {
  return this.node(this.depth);
}; // :: Node
// The root node in which the position was resolved.


prototypeAccessors$2.doc.get = function () {
  return this.node(0);
}; // :: (?number) → Node
// The ancestor node at the given level. `p.node(p.depth)` is the
// same as `p.parent`.


ResolvedPos.prototype.node = function node(depth) {
  return this.path[this.resolveDepth(depth) * 3];
}; // :: (?number) → number
// The index into the ancestor at the given level. If this points at
// the 3rd node in the 2nd paragraph on the top level, for example,
// `p.index(0)` is 1 and `p.index(1)` is 2.


ResolvedPos.prototype.index = function index(depth) {
  return this.path[this.resolveDepth(depth) * 3 + 1];
}; // :: (?number) → number
// The index pointing after this position into the ancestor at the
// given level.


ResolvedPos.prototype.indexAfter = function indexAfter(depth) {
  depth = this.resolveDepth(depth);
  return this.index(depth) + (depth == this.depth && !this.textOffset ? 0 : 1);
}; // :: (?number) → number
// The (absolute) position at the start of the node at the given
// level.


ResolvedPos.prototype.start = function start(depth) {
  depth = this.resolveDepth(depth);
  return depth == 0 ? 0 : this.path[depth * 3 - 1] + 1;
}; // :: (?number) → number
// The (absolute) position at the end of the node at the given
// level.


ResolvedPos.prototype.end = function end(depth) {
  depth = this.resolveDepth(depth);
  return this.start(depth) + this.node(depth).content.size;
}; // :: (?number) → number
// The (absolute) position directly before the wrapping node at the
// given level, or, when `depth` is `this.depth + 1`, the original
// position.


ResolvedPos.prototype.before = function before(depth) {
  depth = this.resolveDepth(depth);

  if (!depth) {
    throw new RangeError("There is no position before the top-level node");
  }

  return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1];
}; // :: (?number) → number
// The (absolute) position directly after the wrapping node at the
// given level, or the original position when `depth` is `this.depth + 1`.


ResolvedPos.prototype.after = function after(depth) {
  depth = this.resolveDepth(depth);

  if (!depth) {
    throw new RangeError("There is no position after the top-level node");
  }

  return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1] + this.path[depth * 3].nodeSize;
}; // :: number
// When this position points into a text node, this returns the
// distance between the position and the start of the text node.
// Will be zero for positions that point between nodes.


prototypeAccessors$2.textOffset.get = function () {
  return this.pos - this.path[this.path.length - 1];
}; // :: ?Node
// Get the node directly after the position, if any. If the position
// points into a text node, only the part of that node after the
// position is returned.


prototypeAccessors$2.nodeAfter.get = function () {
  var parent = this.parent,
      index = this.index(this.depth);

  if (index == parent.childCount) {
    return null;
  }

  var dOff = this.pos - this.path[this.path.length - 1],
      child = parent.child(index);
  return dOff ? parent.child(index).cut(dOff) : child;
}; // :: ?Node
// Get the node directly before the position, if any. If the
// position points into a text node, only the part of that node
// before the position is returned.


prototypeAccessors$2.nodeBefore.get = function () {
  var index = this.index(this.depth);
  var dOff = this.pos - this.path[this.path.length - 1];

  if (dOff) {
    return this.parent.child(index).cut(0, dOff);
  }

  return index == 0 ? null : this.parent.child(index - 1);
}; // :: () → [Mark]
// Get the marks at this position, factoring in the surrounding
// marks' [`inclusive`](#model.MarkSpec.inclusive) property. If the
// position is at the start of a non-empty node, the marks of the
// node after it (if any) are returned.


ResolvedPos.prototype.marks = function marks() {
  var parent = this.parent,
      index = this.index(); // In an empty parent, return the empty array

  if (parent.content.size == 0) {
    return Mark.none;
  } // When inside a text node, just return the text node's marks


  if (this.textOffset) {
    return parent.child(index).marks;
  }

  var main = parent.maybeChild(index - 1),
      other = parent.maybeChild(index); // If the `after` flag is true of there is no node before, make
  // the node after this position the main reference.

  if (!main) {
    var tmp = main;
    main = other;
    other = tmp;
  } // Use all marks in the main node, except those that have
  // `inclusive` set to false and are not present in the other node.


  var marks = main.marks;

  for (var i = 0; i < marks.length; i++) {
    if (marks[i].type.spec.inclusive === false && (!other || !marks[i].isInSet(other.marks))) {
      marks = marks[i--].removeFromSet(marks);
    }
  }

  return marks;
}; // :: (ResolvedPos) → ?[Mark]
// Get the marks after the current position, if any, except those
// that are non-inclusive and not present at position `$end`. This
// is mostly useful for getting the set of marks to preserve after a
// deletion. Will return `null` if this position is at the end of
// its parent node or its parent node isn't a textblock (in which
// case no marks should be preserved).


ResolvedPos.prototype.marksAcross = function marksAcross($end) {
  var after = this.parent.maybeChild(this.index());

  if (!after || !after.isInline) {
    return null;
  }

  var marks = after.marks,
      next = $end.parent.maybeChild($end.index());

  for (var i = 0; i < marks.length; i++) {
    if (marks[i].type.spec.inclusive === false && (!next || !marks[i].isInSet(next.marks))) {
      marks = marks[i--].removeFromSet(marks);
    }
  }

  return marks;
}; // :: (number) → number
// The depth up to which this position and the given (non-resolved)
// position share the same parent nodes.


ResolvedPos.prototype.sharedDepth = function sharedDepth(pos) {
  for (var depth = this.depth; depth > 0; depth--) {
    if (this.start(depth) <= pos && this.end(depth) >= pos) {
      return depth;
    }
  }

  return 0;
}; // :: (?ResolvedPos, ?(Node) → bool) → ?NodeRange
// Returns a range based on the place where this position and the
// given position diverge around block content. If both point into
// the same textblock, for example, a range around that textblock
// will be returned. If they point into different blocks, the range
// around those blocks in their shared ancestor is returned. You can
// pass in an optional predicate that will be called with a parent
// node to see if a range into that parent is acceptable.


ResolvedPos.prototype.blockRange = function blockRange(other, pred) {
  if (other === void 0) other = this;

  if (other.pos < this.pos) {
    return other.blockRange(this);
  }

  for (var d = this.depth - (this.parent.inlineContent || this.pos == other.pos ? 1 : 0); d >= 0; d--) {
    if (other.pos <= this.end(d) && (!pred || pred(this.node(d)))) {
      return new NodeRange(this, other, d);
    }
  }
}; // :: (ResolvedPos) → bool
// Query whether the given position shares the same parent node.


ResolvedPos.prototype.sameParent = function sameParent(other) {
  return this.pos - this.parentOffset == other.pos - other.parentOffset;
}; // :: (ResolvedPos) → ResolvedPos
// Return the greater of this and the given position.


ResolvedPos.prototype.max = function max(other) {
  return other.pos > this.pos ? other : this;
}; // :: (ResolvedPos) → ResolvedPos
// Return the smaller of this and the given position.


ResolvedPos.prototype.min = function min(other) {
  return other.pos < this.pos ? other : this;
};

ResolvedPos.prototype.toString = function toString() {
  var str = "";

  for (var i = 1; i <= this.depth; i++) {
    str += (str ? "/" : "") + this.node(i).type.name + "_" + this.index(i - 1);
  }

  return str + ":" + this.parentOffset;
};

ResolvedPos.resolve = function resolve(doc, pos) {
  if (!(pos >= 0 && pos <= doc.content.size)) {
    throw new RangeError("Position " + pos + " out of range");
  }

  var path = [];
  var start = 0,
      parentOffset = pos;

  for (var node = doc;;) {
    var ref = node.content.findIndex(parentOffset);
    var index = ref.index;
    var offset = ref.offset;
    var rem = parentOffset - offset;
    path.push(node, index, start + offset);

    if (!rem) {
      break;
    }

    node = node.child(index);

    if (node.isText) {
      break;
    }

    parentOffset = rem - 1;
    start += offset + 1;
  }

  return new ResolvedPos(pos, path, parentOffset);
};

ResolvedPos.resolveCached = function resolveCached(doc, pos) {
  for (var i = 0; i < resolveCache.length; i++) {
    var cached = resolveCache[i];

    if (cached.pos == pos && cached.doc == doc) {
      return cached;
    }
  }

  var result = resolveCache[resolveCachePos] = ResolvedPos.resolve(doc, pos);
  resolveCachePos = (resolveCachePos + 1) % resolveCacheSize;
  return result;
};

Object.defineProperties(ResolvedPos.prototype, prototypeAccessors$2);
var resolveCache = [],
    resolveCachePos = 0,
    resolveCacheSize = 12; // ::- Represents a flat range of content, i.e. one that starts and
// ends in the same node.

var NodeRange = function NodeRange($from, $to, depth) {
  // :: ResolvedPos A resolved position along the start of the
  // content. May have a `depth` greater than this object's `depth`
  // property, since these are the positions that were used to
  // compute the range, not re-resolved positions directly at its
  // boundaries.
  this.$from = $from; // :: ResolvedPos A position along the end of the content. See
  // caveat for [`$from`](#model.NodeRange.$from).

  this.$to = $to; // :: number The depth of the node that this range points into.

  this.depth = depth;
};

exports.NodeRange = NodeRange;
var prototypeAccessors$1$1 = {
  start: {
    configurable: true
  },
  end: {
    configurable: true
  },
  parent: {
    configurable: true
  },
  startIndex: {
    configurable: true
  },
  endIndex: {
    configurable: true
  }
}; // :: number The position at the start of the range.

prototypeAccessors$1$1.start.get = function () {
  return this.$from.before(this.depth + 1);
}; // :: number The position at the end of the range.


prototypeAccessors$1$1.end.get = function () {
  return this.$to.after(this.depth + 1);
}; // :: Node The parent node that the range points into.


prototypeAccessors$1$1.parent.get = function () {
  return this.$from.node(this.depth);
}; // :: number The start index of the range in the parent node.


prototypeAccessors$1$1.startIndex.get = function () {
  return this.$from.index(this.depth);
}; // :: number The end index of the range in the parent node.


prototypeAccessors$1$1.endIndex.get = function () {
  return this.$to.indexAfter(this.depth);
};

Object.defineProperties(NodeRange.prototype, prototypeAccessors$1$1);
var emptyAttrs = Object.create(null); // ::- This class represents a node in the tree that makes up a
// ProseMirror document. So a document is an instance of `Node`, with
// children that are also instances of `Node`.
//
// Nodes are persistent data structures. Instead of changing them, you
// create new ones with the content you want. Old ones keep pointing
// at the old document shape. This is made cheaper by sharing
// structure between the old and new data as much as possible, which a
// tree shape like this (without back pointers) makes easy.
//
// **Do not** directly mutate the properties of a `Node` object. See
// [the guide](/docs/guide/#doc) for more information.

var Node = function Node(type, attrs, content, marks) {
  // :: NodeType
  // The type of node that this is.
  this.type = type; // :: Object
  // An object mapping attribute names to values. The kind of
  // attributes allowed and required are
  // [determined](#model.NodeSpec.attrs) by the node type.

  this.attrs = attrs; // :: Fragment
  // A container holding the node's children.

  this.content = content || Fragment.empty; // :: [Mark]
  // The marks (things like whether it is emphasized or part of a
  // link) applied to this node.

  this.marks = marks || Mark.none;
};

exports.Node = Node;
var prototypeAccessors$3 = {
  nodeSize: {
    configurable: true
  },
  childCount: {
    configurable: true
  },
  textContent: {
    configurable: true
  },
  firstChild: {
    configurable: true
  },
  lastChild: {
    configurable: true
  },
  isBlock: {
    configurable: true
  },
  isTextblock: {
    configurable: true
  },
  inlineContent: {
    configurable: true
  },
  isInline: {
    configurable: true
  },
  isText: {
    configurable: true
  },
  isLeaf: {
    configurable: true
  },
  isAtom: {
    configurable: true
  }
}; // text:: ?string
// For text nodes, this contains the node's text content.
// :: number
// The size of this node, as defined by the integer-based [indexing
// scheme](/docs/guide/#doc.indexing). For text nodes, this is the
// amount of characters. For other leaf nodes, it is one. For
// non-leaf nodes, it is the size of the content plus two (the start
// and end token).

prototypeAccessors$3.nodeSize.get = function () {
  return this.isLeaf ? 1 : 2 + this.content.size;
}; // :: number
// The number of children that the node has.


prototypeAccessors$3.childCount.get = function () {
  return this.content.childCount;
}; // :: (number) → Node
// Get the child node at the given index. Raises an error when the
// index is out of range.


Node.prototype.child = function child(index) {
  return this.content.child(index);
}; // :: (number) → ?Node
// Get the child node at the given index, if it exists.


Node.prototype.maybeChild = function maybeChild(index) {
  return this.content.maybeChild(index);
}; // :: ((node: Node, offset: number, index: number))
// Call `f` for every child node, passing the node, its offset
// into this parent node, and its index.


Node.prototype.forEach = function forEach(f) {
  this.content.forEach(f);
}; // :: (number, number, (node: Node, pos: number, parent: Node, index: number) → ?bool, ?number)
// Invoke a callback for all descendant nodes recursively between
// the given two positions that are relative to start of this node's
// content. The callback is invoked with the node, its
// parent-relative position, its parent node, and its child index.
// When the callback returns false for a given node, that node's
// children will not be recursed over. The last parameter can be
// used to specify a starting position to count from.


Node.prototype.nodesBetween = function nodesBetween(from, to, f, startPos) {
  if (startPos === void 0) startPos = 0;
  this.content.nodesBetween(from, to, f, startPos, this);
}; // :: ((node: Node, pos: number, parent: Node) → ?bool)
// Call the given callback for every descendant node. Doesn't
// descend into a node when the callback returns `false`.


Node.prototype.descendants = function descendants(f) {
  this.nodesBetween(0, this.content.size, f);
}; // :: string
// Concatenates all the text nodes found in this fragment and its
// children.


prototypeAccessors$3.textContent.get = function () {
  return this.textBetween(0, this.content.size, "");
}; // :: (number, number, ?string, ?string) → string
// Get all text between positions `from` and `to`. When
// `blockSeparator` is given, it will be inserted whenever a new
// block node is started. When `leafText` is given, it'll be
// inserted for every non-text leaf node encountered.


Node.prototype.textBetween = function textBetween(from, to, blockSeparator, leafText) {
  return this.content.textBetween(from, to, blockSeparator, leafText);
}; // :: ?Node
// Returns this node's first child, or `null` if there are no
// children.


prototypeAccessors$3.firstChild.get = function () {
  return this.content.firstChild;
}; // :: ?Node
// Returns this node's last child, or `null` if there are no
// children.


prototypeAccessors$3.lastChild.get = function () {
  return this.content.lastChild;
}; // :: (Node) → bool
// Test whether two nodes represent the same piece of document.


Node.prototype.eq = function eq(other) {
  return this == other || this.sameMarkup(other) && this.content.eq(other.content);
}; // :: (Node) → bool
// Compare the markup (type, attributes, and marks) of this node to
// those of another. Returns `true` if both have the same markup.


Node.prototype.sameMarkup = function sameMarkup(other) {
  return this.hasMarkup(other.type, other.attrs, other.marks);
}; // :: (NodeType, ?Object, ?[Mark]) → bool
// Check whether this node's markup correspond to the given type,
// attributes, and marks.


Node.prototype.hasMarkup = function hasMarkup(type, attrs, marks) {
  return this.type == type && compareDeep(this.attrs, attrs || type.defaultAttrs || emptyAttrs) && Mark.sameSet(this.marks, marks || Mark.none);
}; // :: (?Fragment) → Node
// Create a new node with the same markup as this node, containing
// the given content (or empty, if no content is given).


Node.prototype.copy = function copy(content) {
  if (content === void 0) content = null;

  if (content == this.content) {
    return this;
  }

  return new this.constructor(this.type, this.attrs, content, this.marks);
}; // :: ([Mark]) → Node
// Create a copy of this node, with the given set of marks instead
// of the node's own marks.


Node.prototype.mark = function mark(marks) {
  return marks == this.marks ? this : new this.constructor(this.type, this.attrs, this.content, marks);
}; // :: (number, ?number) → Node
// Create a copy of this node with only the content between the
// given positions. If `to` is not given, it defaults to the end of
// the node.


Node.prototype.cut = function cut(from, to) {
  if (from == 0 && to == this.content.size) {
    return this;
  }

  return this.copy(this.content.cut(from, to));
}; // :: (number, ?number) → Slice
// Cut out the part of the document between the given positions, and
// return it as a `Slice` object.


Node.prototype.slice = function slice(from, to, includeParents) {
  if (to === void 0) to = this.content.size;
  if (includeParents === void 0) includeParents = false;

  if (from == to) {
    return Slice.empty;
  }

  var $from = this.resolve(from),
      $to = this.resolve(to);
  var depth = includeParents ? 0 : $from.sharedDepth(to);
  var start = $from.start(depth),
      node = $from.node(depth);
  var content = node.content.cut($from.pos - start, $to.pos - start);
  return new Slice(content, $from.depth - depth, $to.depth - depth);
}; // :: (number, number, Slice) → Node
// Replace the part of the document between the given positions with
// the given slice. The slice must 'fit', meaning its open sides
// must be able to connect to the surrounding content, and its
// content nodes must be valid children for the node they are placed
// into. If any of this is violated, an error of type
// [`ReplaceError`](#model.ReplaceError) is thrown.


Node.prototype.replace = function replace$1(from, to, slice) {
  return replace(this.resolve(from), this.resolve(to), slice);
}; // :: (number) → ?Node
// Find the node directly after the given position.


Node.prototype.nodeAt = function nodeAt(pos) {
  for (var node = this;;) {
    var ref = node.content.findIndex(pos);
    var index = ref.index;
    var offset = ref.offset;
    node = node.maybeChild(index);

    if (!node) {
      return null;
    }

    if (offset == pos || node.isText) {
      return node;
    }

    pos -= offset + 1;
  }
}; // :: (number) → {node: ?Node, index: number, offset: number}
// Find the (direct) child node after the given offset, if any,
// and return it along with its index and offset relative to this
// node.


Node.prototype.childAfter = function childAfter(pos) {
  var ref = this.content.findIndex(pos);
  var index = ref.index;
  var offset = ref.offset;
  return {
    node: this.content.maybeChild(index),
    index: index,
    offset: offset
  };
}; // :: (number) → {node: ?Node, index: number, offset: number}
// Find the (direct) child node before the given offset, if any,
// and return it along with its index and offset relative to this
// node.


Node.prototype.childBefore = function childBefore(pos) {
  if (pos == 0) {
    return {
      node: null,
      index: 0,
      offset: 0
    };
  }

  var ref = this.content.findIndex(pos);
  var index = ref.index;
  var offset = ref.offset;

  if (offset < pos) {
    return {
      node: this.content.child(index),
      index: index,
      offset: offset
    };
  }

  var node = this.content.child(index - 1);
  return {
    node: node,
    index: index - 1,
    offset: offset - node.nodeSize
  };
}; // :: (number) → ResolvedPos
// Resolve the given position in the document, returning an
// [object](#model.ResolvedPos) with information about its context.


Node.prototype.resolve = function resolve(pos) {
  return ResolvedPos.resolveCached(this, pos);
};

Node.prototype.resolveNoCache = function resolveNoCache(pos) {
  return ResolvedPos.resolve(this, pos);
}; // :: (number, number, MarkType) → bool
// Test whether a mark of the given type occurs in this document
// between the two given positions.


Node.prototype.rangeHasMark = function rangeHasMark(from, to, type) {
  var found = false;

  if (to > from) {
    this.nodesBetween(from, to, function (node) {
      if (type.isInSet(node.marks)) {
        found = true;
      }

      return !found;
    });
  }

  return found;
}; // :: bool
// True when this is a block (non-inline node)


prototypeAccessors$3.isBlock.get = function () {
  return this.type.isBlock;
}; // :: bool
// True when this is a textblock node, a block node with inline
// content.


prototypeAccessors$3.isTextblock.get = function () {
  return this.type.isTextblock;
}; // :: bool
// True when this node allows inline content.


prototypeAccessors$3.inlineContent.get = function () {
  return this.type.inlineContent;
}; // :: bool
// True when this is an inline node (a text node or a node that can
// appear among text).


prototypeAccessors$3.isInline.get = function () {
  return this.type.isInline;
}; // :: bool
// True when this is a text node.


prototypeAccessors$3.isText.get = function () {
  return this.type.isText;
}; // :: bool
// True when this is a leaf node.


prototypeAccessors$3.isLeaf.get = function () {
  return this.type.isLeaf;
}; // :: bool
// True when this is an atom, i.e. when it does not have directly
// editable content. This is usually the same as `isLeaf`, but can
// be configured with the [`atom` property](#model.NodeSpec.atom) on
// a node's spec (typically used when the node is displayed as an
// uneditable [node view](#view.NodeView)).


prototypeAccessors$3.isAtom.get = function () {
  return this.type.isAtom;
}; // :: () → string
// Return a string representation of this node for debugging
// purposes.


Node.prototype.toString = function toString() {
  if (this.type.spec.toDebugString) {
    return this.type.spec.toDebugString(this);
  }

  var name = this.type.name;

  if (this.content.size) {
    name += "(" + this.content.toStringInner() + ")";
  }

  return wrapMarks(this.marks, name);
}; // :: (number) → ContentMatch
// Get the content match in this node at the given index.


Node.prototype.contentMatchAt = function contentMatchAt(index) {
  var match = this.type.contentMatch.matchFragment(this.content, 0, index);

  if (!match) {
    throw new Error("Called contentMatchAt on a node with invalid content");
  }

  return match;
}; // :: (number, number, ?Fragment, ?number, ?number) → bool
// Test whether replacing the range between `from` and `to` (by
// child index) with the given replacement fragment (which defaults
// to the empty fragment) would leave the node's content valid. You
// can optionally pass `start` and `end` indices into the
// replacement fragment.


Node.prototype.canReplace = function canReplace(from, to, replacement, start, end) {
  if (replacement === void 0) replacement = Fragment.empty;
  if (start === void 0) start = 0;
  if (end === void 0) end = replacement.childCount;
  var one = this.contentMatchAt(from).matchFragment(replacement, start, end);
  var two = one && one.matchFragment(this.content, to);

  if (!two || !two.validEnd) {
    return false;
  }

  for (var i = start; i < end; i++) {
    if (!this.type.allowsMarks(replacement.child(i).marks)) {
      return false;
    }
  }

  return true;
}; // :: (number, number, NodeType, ?[Mark]) → bool
// Test whether replacing the range `from` to `to` (by index) with a
// node of the given type would leave the node's content valid.


Node.prototype.canReplaceWith = function canReplaceWith(from, to, type, marks) {
  if (marks && !this.type.allowsMarks(marks)) {
    return false;
  }

  var start = this.contentMatchAt(from).matchType(type);
  var end = start && start.matchFragment(this.content, to);
  return end ? end.validEnd : false;
}; // :: (Node) → bool
// Test whether the given node's content could be appended to this
// node. If that node is empty, this will only return true if there
// is at least one node type that can appear in both nodes (to avoid
// merging completely incompatible nodes).


Node.prototype.canAppend = function canAppend(other) {
  if (other.content.size) {
    return this.canReplace(this.childCount, this.childCount, other.content);
  } else {
    return this.type.compatibleContent(other.type);
  }
}; // :: ()
// Check whether this node and its descendants conform to the
// schema, and raise error when they do not.


Node.prototype.check = function check() {
  if (!this.type.validContent(this.content)) {
    throw new RangeError("Invalid content for node " + this.type.name + ": " + this.content.toString().slice(0, 50));
  }

  this.content.forEach(function (node) {
    return node.check();
  });
}; // :: () → Object
// Return a JSON-serializeable representation of this node.


Node.prototype.toJSON = function toJSON() {
  var obj = {
    type: this.type.name
  };

  for (var _ in this.attrs) {
    obj.attrs = this.attrs;
    break;
  }

  if (this.content.size) {
    obj.content = this.content.toJSON();
  }

  if (this.marks.length) {
    obj.marks = this.marks.map(function (n) {
      return n.toJSON();
    });
  }

  return obj;
}; // :: (Schema, Object) → Node
// Deserialize a node from its JSON representation.


Node.fromJSON = function fromJSON(schema, json) {
  if (!json) {
    throw new RangeError("Invalid input for Node.fromJSON");
  }

  var marks = null;

  if (json.marks) {
    if (!Array.isArray(json.marks)) {
      throw new RangeError("Invalid mark data for Node.fromJSON");
    }

    marks = json.marks.map(schema.markFromJSON);
  }

  if (json.type == "text") {
    if (typeof json.text != "string") {
      throw new RangeError("Invalid text node in JSON");
    }

    return schema.text(json.text, marks);
  }

  var content = Fragment.fromJSON(schema, json.content);
  return schema.nodeType(json.type).create(json.attrs, content, marks);
};

Object.defineProperties(Node.prototype, prototypeAccessors$3);

var TextNode = /*@__PURE__*/function (Node) {
  function TextNode(type, attrs, content, marks) {
    Node.call(this, type, attrs, null, marks);

    if (!content) {
      throw new RangeError("Empty text nodes are not allowed");
    }

    this.text = content;
  }

  if (Node) TextNode.__proto__ = Node;
  TextNode.prototype = Object.create(Node && Node.prototype);
  TextNode.prototype.constructor = TextNode;
  var prototypeAccessors$1 = {
    textContent: {
      configurable: true
    },
    nodeSize: {
      configurable: true
    }
  };

  TextNode.prototype.toString = function toString() {
    if (this.type.spec.toDebugString) {
      return this.type.spec.toDebugString(this);
    }

    return wrapMarks(this.marks, JSON.stringify(this.text));
  };

  prototypeAccessors$1.textContent.get = function () {
    return this.text;
  };

  TextNode.prototype.textBetween = function textBetween(from, to) {
    return this.text.slice(from, to);
  };

  prototypeAccessors$1.nodeSize.get = function () {
    return this.text.length;
  };

  TextNode.prototype.mark = function mark(marks) {
    return marks == this.marks ? this : new TextNode(this.type, this.attrs, this.text, marks);
  };

  TextNode.prototype.withText = function withText(text) {
    if (text == this.text) {
      return this;
    }

    return new TextNode(this.type, this.attrs, text, this.marks);
  };

  TextNode.prototype.cut = function cut(from, to) {
    if (from === void 0) from = 0;
    if (to === void 0) to = this.text.length;

    if (from == 0 && to == this.text.length) {
      return this;
    }

    return this.withText(this.text.slice(from, to));
  };

  TextNode.prototype.eq = function eq(other) {
    return this.sameMarkup(other) && this.text == other.text;
  };

  TextNode.prototype.toJSON = function toJSON() {
    var base = Node.prototype.toJSON.call(this);
    base.text = this.text;
    return base;
  };

  Object.defineProperties(TextNode.prototype, prototypeAccessors$1);
  return TextNode;
}(Node);

function wrapMarks(marks, str) {
  for (var i = marks.length - 1; i >= 0; i--) {
    str = marks[i].type.name + "(" + str + ")";
  }

  return str;
} // ::- Instances of this class represent a match state of a node
// type's [content expression](#model.NodeSpec.content), and can be
// used to find out whether further content matches here, and whether
// a given position is a valid end of the node.


var ContentMatch = function ContentMatch(validEnd) {
  // :: bool
  // True when this match state represents a valid end of the node.
  this.validEnd = validEnd;
  this.next = [];
  this.wrapCache = [];
};

exports.ContentMatch = ContentMatch;
var prototypeAccessors$4 = {
  inlineContent: {
    configurable: true
  },
  defaultType: {
    configurable: true
  },
  edgeCount: {
    configurable: true
  }
};

ContentMatch.parse = function parse(string, nodeTypes) {
  var stream = new TokenStream(string, nodeTypes);

  if (stream.next == null) {
    return ContentMatch.empty;
  }

  var expr = parseExpr(stream);

  if (stream.next) {
    stream.err("Unexpected trailing text");
  }

  var match = dfa(nfa(expr));
  checkForDeadEnds(match, stream);
  return match;
}; // :: (NodeType) → ?ContentMatch
// Match a node type, returning a match after that node if
// successful.


ContentMatch.prototype.matchType = function matchType(type) {
  for (var i = 0; i < this.next.length; i += 2) {
    if (this.next[i] == type) {
      return this.next[i + 1];
    }
  }

  return null;
}; // :: (Fragment, ?number, ?number) → ?ContentMatch
// Try to match a fragment. Returns the resulting match when
// successful.


ContentMatch.prototype.matchFragment = function matchFragment(frag, start, end) {
  if (start === void 0) start = 0;
  if (end === void 0) end = frag.childCount;
  var cur = this;

  for (var i = start; cur && i < end; i++) {
    cur = cur.matchType(frag.child(i).type);
  }

  return cur;
};

prototypeAccessors$4.inlineContent.get = function () {
  var first = this.next[0];
  return first ? first.isInline : false;
}; // :: ?NodeType
// Get the first matching node type at this match position that can
// be generated.


prototypeAccessors$4.defaultType.get = function () {
  for (var i = 0; i < this.next.length; i += 2) {
    var type = this.next[i];

    if (!(type.isText || type.hasRequiredAttrs())) {
      return type;
    }
  }
};

ContentMatch.prototype.compatible = function compatible(other) {
  for (var i = 0; i < this.next.length; i += 2) {
    for (var j = 0; j < other.next.length; j += 2) {
      if (this.next[i] == other.next[j]) {
        return true;
      }
    }
  }

  return false;
}; // :: (Fragment, bool, ?number) → ?Fragment
// Try to match the given fragment, and if that fails, see if it can
// be made to match by inserting nodes in front of it. When
// successful, return a fragment of inserted nodes (which may be
// empty if nothing had to be inserted). When `toEnd` is true, only
// return a fragment if the resulting match goes to the end of the
// content expression.


ContentMatch.prototype.fillBefore = function fillBefore(after, toEnd, startIndex) {
  if (toEnd === void 0) toEnd = false;
  if (startIndex === void 0) startIndex = 0;
  var seen = [this];

  function search(match, types) {
    var finished = match.matchFragment(after, startIndex);

    if (finished && (!toEnd || finished.validEnd)) {
      return Fragment.from(types.map(function (tp) {
        return tp.createAndFill();
      }));
    }

    for (var i = 0; i < match.next.length; i += 2) {
      var type = match.next[i],
          next = match.next[i + 1];

      if (!(type.isText || type.hasRequiredAttrs()) && seen.indexOf(next) == -1) {
        seen.push(next);
        var found = search(next, types.concat(type));

        if (found) {
          return found;
        }
      }
    }
  }

  return search(this, []);
}; // :: (NodeType) → ?[NodeType]
// Find a set of wrapping node types that would allow a node of the
// given type to appear at this position. The result may be empty
// (when it fits directly) and will be null when no such wrapping
// exists.


ContentMatch.prototype.findWrapping = function findWrapping(target) {
  for (var i = 0; i < this.wrapCache.length; i += 2) {
    if (this.wrapCache[i] == target) {
      return this.wrapCache[i + 1];
    }
  }

  var computed = this.computeWrapping(target);
  this.wrapCache.push(target, computed);
  return computed;
};

ContentMatch.prototype.computeWrapping = function computeWrapping(target) {
  var seen = Object.create(null),
      active = [{
    match: this,
    type: null,
    via: null
  }];

  while (active.length) {
    var current = active.shift(),
        match = current.match;

    if (match.matchType(target)) {
      var result = [];

      for (var obj = current; obj.type; obj = obj.via) {
        result.push(obj.type);
      }

      return result.reverse();
    }

    for (var i = 0; i < match.next.length; i += 2) {
      var type = match.next[i];

      if (!type.isLeaf && !type.hasRequiredAttrs() && !(type.name in seen) && (!current.type || match.next[i + 1].validEnd)) {
        active.push({
          match: type.contentMatch,
          type: type,
          via: current
        });
        seen[type.name] = true;
      }
    }
  }
}; // :: number
// The number of outgoing edges this node has in the finite
// automaton that describes the content expression.


prototypeAccessors$4.edgeCount.get = function () {
  return this.next.length >> 1;
}; // :: (number) → {type: NodeType, next: ContentMatch}
// Get the _n_​th outgoing edge from this node in the finite
// automaton that describes the content expression.


ContentMatch.prototype.edge = function edge(n) {
  var i = n << 1;

  if (i >= this.next.length) {
    throw new RangeError("There's no " + n + "th edge in this content match");
  }

  return {
    type: this.next[i],
    next: this.next[i + 1]
  };
};

ContentMatch.prototype.toString = function toString() {
  var seen = [];

  function scan(m) {
    seen.push(m);

    for (var i = 1; i < m.next.length; i += 2) {
      if (seen.indexOf(m.next[i]) == -1) {
        scan(m.next[i]);
      }
    }
  }

  scan(this);
  return seen.map(function (m, i) {
    var out = i + (m.validEnd ? "*" : " ") + " ";

    for (var i$1 = 0; i$1 < m.next.length; i$1 += 2) {
      out += (i$1 ? ", " : "") + m.next[i$1].name + "->" + seen.indexOf(m.next[i$1 + 1]);
    }

    return out;
  }).join("\n");
};

Object.defineProperties(ContentMatch.prototype, prototypeAccessors$4);
ContentMatch.empty = new ContentMatch(true);

var TokenStream = function TokenStream(string, nodeTypes) {
  this.string = string;
  this.nodeTypes = nodeTypes;
  this.inline = null;
  this.pos = 0;
  this.tokens = string.split(/\s*(?=\b|\W|$)/);

  if (this.tokens[this.tokens.length - 1] == "") {
    this.tokens.pop();
  }

  if (this.tokens[0] == "") {
    this.tokens.unshift();
  }
};

var prototypeAccessors$1$2 = {
  next: {
    configurable: true
  }
};

prototypeAccessors$1$2.next.get = function () {
  return this.tokens[this.pos];
};

TokenStream.prototype.eat = function eat(tok) {
  return this.next == tok && (this.pos++ || true);
};

TokenStream.prototype.err = function err(str) {
  throw new SyntaxError(str + " (in content expression '" + this.string + "')");
};

Object.defineProperties(TokenStream.prototype, prototypeAccessors$1$2);

function parseExpr(stream) {
  var exprs = [];

  do {
    exprs.push(parseExprSeq(stream));
  } while (stream.eat("|"));

  return exprs.length == 1 ? exprs[0] : {
    type: "choice",
    exprs: exprs
  };
}

function parseExprSeq(stream) {
  var exprs = [];

  do {
    exprs.push(parseExprSubscript(stream));
  } while (stream.next && stream.next != ")" && stream.next != "|");

  return exprs.length == 1 ? exprs[0] : {
    type: "seq",
    exprs: exprs
  };
}

function parseExprSubscript(stream) {
  var expr = parseExprAtom(stream);

  for (;;) {
    if (stream.eat("+")) {
      expr = {
        type: "plus",
        expr: expr
      };
    } else if (stream.eat("*")) {
      expr = {
        type: "star",
        expr: expr
      };
    } else if (stream.eat("?")) {
      expr = {
        type: "opt",
        expr: expr
      };
    } else if (stream.eat("{")) {
      expr = parseExprRange(stream, expr);
    } else {
      break;
    }
  }

  return expr;
}

function parseNum(stream) {
  if (/\D/.test(stream.next)) {
    stream.err("Expected number, got '" + stream.next + "'");
  }

  var result = Number(stream.next);
  stream.pos++;
  return result;
}

function parseExprRange(stream, expr) {
  var min = parseNum(stream),
      max = min;

  if (stream.eat(",")) {
    if (stream.next != "}") {
      max = parseNum(stream);
    } else {
      max = -1;
    }
  }

  if (!stream.eat("}")) {
    stream.err("Unclosed braced range");
  }

  return {
    type: "range",
    min: min,
    max: max,
    expr: expr
  };
}

function resolveName(stream, name) {
  var types = stream.nodeTypes,
      type = types[name];

  if (type) {
    return [type];
  }

  var result = [];

  for (var typeName in types) {
    var type$1 = types[typeName];

    if (type$1.groups.indexOf(name) > -1) {
      result.push(type$1);
    }
  }

  if (result.length == 0) {
    stream.err("No node type or group '" + name + "' found");
  }

  return result;
}

function parseExprAtom(stream) {
  if (stream.eat("(")) {
    var expr = parseExpr(stream);

    if (!stream.eat(")")) {
      stream.err("Missing closing paren");
    }

    return expr;
  } else if (!/\W/.test(stream.next)) {
    var exprs = resolveName(stream, stream.next).map(function (type) {
      if (stream.inline == null) {
        stream.inline = type.isInline;
      } else if (stream.inline != type.isInline) {
        stream.err("Mixing inline and block content");
      }

      return {
        type: "name",
        value: type
      };
    });
    stream.pos++;
    return exprs.length == 1 ? exprs[0] : {
      type: "choice",
      exprs: exprs
    };
  } else {
    stream.err("Unexpected token '" + stream.next + "'");
  }
} // The code below helps compile a regular-expression-like language
// into a deterministic finite automaton. For a good introduction to
// these concepts, see https://swtch.com/~rsc/regexp/regexp1.html
// : (Object) → [[{term: ?any, to: number}]]
// Construct an NFA from an expression as returned by the parser. The
// NFA is represented as an array of states, which are themselves
// arrays of edges, which are `{term, to}` objects. The first state is
// the entry state and the last node is the success state.
//
// Note that unlike typical NFAs, the edge ordering in this one is
// significant, in that it is used to contruct filler content when
// necessary.


function nfa(expr) {
  var nfa = [[]];
  connect(compile(expr, 0), node());
  return nfa;

  function node() {
    return nfa.push([]) - 1;
  }

  function edge(from, to, term) {
    var edge = {
      term: term,
      to: to
    };
    nfa[from].push(edge);
    return edge;
  }

  function connect(edges, to) {
    edges.forEach(function (edge) {
      return edge.to = to;
    });
  }

  function compile(expr, from) {
    if (expr.type == "choice") {
      return expr.exprs.reduce(function (out, expr) {
        return out.concat(compile(expr, from));
      }, []);
    } else if (expr.type == "seq") {
      for (var i = 0;; i++) {
        var next = compile(expr.exprs[i], from);

        if (i == expr.exprs.length - 1) {
          return next;
        }

        connect(next, from = node());
      }
    } else if (expr.type == "star") {
      var loop = node();
      edge(from, loop);
      connect(compile(expr.expr, loop), loop);
      return [edge(loop)];
    } else if (expr.type == "plus") {
      var loop$1 = node();
      connect(compile(expr.expr, from), loop$1);
      connect(compile(expr.expr, loop$1), loop$1);
      return [edge(loop$1)];
    } else if (expr.type == "opt") {
      return [edge(from)].concat(compile(expr.expr, from));
    } else if (expr.type == "range") {
      var cur = from;

      for (var i$1 = 0; i$1 < expr.min; i$1++) {
        var next$1 = node();
        connect(compile(expr.expr, cur), next$1);
        cur = next$1;
      }

      if (expr.max == -1) {
        connect(compile(expr.expr, cur), cur);
      } else {
        for (var i$2 = expr.min; i$2 < expr.max; i$2++) {
          var next$2 = node();
          edge(cur, next$2);
          connect(compile(expr.expr, cur), next$2);
          cur = next$2;
        }
      }

      return [edge(cur)];
    } else if (expr.type == "name") {
      return [edge(from, null, expr.value)];
    }
  }
}

function cmp(a, b) {
  return b - a;
} // Get the set of nodes reachable by null edges from `node`. Omit
// nodes with only a single null-out-edge, since they may lead to
// needless duplicated nodes.


function nullFrom(nfa, node) {
  var result = [];
  scan(node);
  return result.sort(cmp);

  function scan(node) {
    var edges = nfa[node];

    if (edges.length == 1 && !edges[0].term) {
      return scan(edges[0].to);
    }

    result.push(node);

    for (var i = 0; i < edges.length; i++) {
      var ref = edges[i];
      var term = ref.term;
      var to = ref.to;

      if (!term && result.indexOf(to) == -1) {
        scan(to);
      }
    }
  }
} // : ([[{term: ?any, to: number}]]) → ContentMatch
// Compiles an NFA as produced by `nfa` into a DFA, modeled as a set
// of state objects (`ContentMatch` instances) with transitions
// between them.


function dfa(nfa) {
  var labeled = Object.create(null);
  return explore(nullFrom(nfa, 0));

  function explore(states) {
    var out = [];
    states.forEach(function (node) {
      nfa[node].forEach(function (ref) {
        var term = ref.term;
        var to = ref.to;

        if (!term) {
          return;
        }

        var known = out.indexOf(term),
            set = known > -1 && out[known + 1];
        nullFrom(nfa, to).forEach(function (node) {
          if (!set) {
            out.push(term, set = []);
          }

          if (set.indexOf(node) == -1) {
            set.push(node);
          }
        });
      });
    });
    var state = labeled[states.join(",")] = new ContentMatch(states.indexOf(nfa.length - 1) > -1);

    for (var i = 0; i < out.length; i += 2) {
      var states$1 = out[i + 1].sort(cmp);
      state.next.push(out[i], labeled[states$1.join(",")] || explore(states$1));
    }

    return state;
  }
}

function checkForDeadEnds(match, stream) {
  for (var i = 0, work = [match]; i < work.length; i++) {
    var state = work[i],
        dead = !state.validEnd,
        nodes = [];

    for (var j = 0; j < state.next.length; j += 2) {
      var node = state.next[j],
          next = state.next[j + 1];
      nodes.push(node.name);

      if (dead && !(node.isText || node.hasRequiredAttrs())) {
        dead = false;
      }

      if (work.indexOf(next) == -1) {
        work.push(next);
      }
    }

    if (dead) {
      stream.err("Only non-generatable nodes (" + nodes.join(", ") + ") in a required position");
    }
  }
} // For node types where all attrs have a default value (or which don't
// have any attributes), build up a single reusable default attribute
// object, and use it for all nodes that don't specify specific
// attributes.


function defaultAttrs(attrs) {
  var defaults = Object.create(null);

  for (var attrName in attrs) {
    var attr = attrs[attrName];

    if (!attr.hasDefault) {
      return null;
    }

    defaults[attrName] = attr.default;
  }

  return defaults;
}

function computeAttrs(attrs, value) {
  var built = Object.create(null);

  for (var name in attrs) {
    var given = value && value[name];

    if (given === undefined) {
      var attr = attrs[name];

      if (attr.hasDefault) {
        given = attr.default;
      } else {
        throw new RangeError("No value supplied for attribute " + name);
      }
    }

    built[name] = given;
  }

  return built;
}

function initAttrs(attrs) {
  var result = Object.create(null);

  if (attrs) {
    for (var name in attrs) {
      result[name] = new Attribute(attrs[name]);
    }
  }

  return result;
} // ::- Node types are objects allocated once per `Schema` and used to
// [tag](#model.Node.type) `Node` instances. They contain information
// about the node type, such as its name and what kind of node it
// represents.


var NodeType = function NodeType(name, schema, spec) {
  // :: string
  // The name the node type has in this schema.
  this.name = name; // :: Schema
  // A link back to the `Schema` the node type belongs to.

  this.schema = schema; // :: NodeSpec
  // The spec that this type is based on

  this.spec = spec;
  this.groups = spec.group ? spec.group.split(" ") : [];
  this.attrs = initAttrs(spec.attrs);
  this.defaultAttrs = defaultAttrs(this.attrs); // :: ContentMatch
  // The starting match of the node type's content expression.

  this.contentMatch = null; // : ?[MarkType]
  // The set of marks allowed in this node. `null` means all marks
  // are allowed.

  this.markSet = null; // :: bool
  // True if this node type has inline content.

  this.inlineContent = null; // :: bool
  // True if this is a block type

  this.isBlock = !(spec.inline || name == "text"); // :: bool
  // True if this is the text node type.

  this.isText = name == "text";
};

exports.NodeType = NodeType;
var prototypeAccessors$5 = {
  isInline: {
    configurable: true
  },
  isTextblock: {
    configurable: true
  },
  isLeaf: {
    configurable: true
  },
  isAtom: {
    configurable: true
  }
}; // :: bool
// True if this is an inline type.

prototypeAccessors$5.isInline.get = function () {
  return !this.isBlock;
}; // :: bool
// True if this is a textblock type, a block that contains inline
// content.


prototypeAccessors$5.isTextblock.get = function () {
  return this.isBlock && this.inlineContent;
}; // :: bool
// True for node types that allow no content.


prototypeAccessors$5.isLeaf.get = function () {
  return this.contentMatch == ContentMatch.empty;
}; // :: bool
// True when this node is an atom, i.e. when it does not have
// directly editable content.


prototypeAccessors$5.isAtom.get = function () {
  return this.isLeaf || this.spec.atom;
}; // :: () → bool
// Tells you whether this node type has any required attributes.


NodeType.prototype.hasRequiredAttrs = function hasRequiredAttrs() {
  for (var n in this.attrs) {
    if (this.attrs[n].isRequired) {
      return true;
    }
  }

  return false;
};

NodeType.prototype.compatibleContent = function compatibleContent(other) {
  return this == other || this.contentMatch.compatible(other.contentMatch);
};

NodeType.prototype.computeAttrs = function computeAttrs$1(attrs) {
  if (!attrs && this.defaultAttrs) {
    return this.defaultAttrs;
  } else {
    return computeAttrs(this.attrs, attrs);
  }
}; // :: (?Object, ?union<Fragment, Node, [Node]>, ?[Mark]) → Node
// Create a `Node` of this type. The given attributes are
// checked and defaulted (you can pass `null` to use the type's
// defaults entirely, if no required attributes exist). `content`
// may be a `Fragment`, a node, an array of nodes, or
// `null`. Similarly `marks` may be `null` to default to the empty
// set of marks.


NodeType.prototype.create = function create(attrs, content, marks) {
  if (this.isText) {
    throw new Error("NodeType.create can't construct text nodes");
  }

  return new Node(this, this.computeAttrs(attrs), Fragment.from(content), Mark.setFrom(marks));
}; // :: (?Object, ?union<Fragment, Node, [Node]>, ?[Mark]) → Node
// Like [`create`](#model.NodeType.create), but check the given content
// against the node type's content restrictions, and throw an error
// if it doesn't match.


NodeType.prototype.createChecked = function createChecked(attrs, content, marks) {
  content = Fragment.from(content);

  if (!this.validContent(content)) {
    throw new RangeError("Invalid content for node " + this.name);
  }

  return new Node(this, this.computeAttrs(attrs), content, Mark.setFrom(marks));
}; // :: (?Object, ?union<Fragment, Node, [Node]>, ?[Mark]) → ?Node
// Like [`create`](#model.NodeType.create), but see if it is necessary to
// add nodes to the start or end of the given fragment to make it
// fit the node. If no fitting wrapping can be found, return null.
// Note that, due to the fact that required nodes can always be
// created, this will always succeed if you pass null or
// `Fragment.empty` as content.


NodeType.prototype.createAndFill = function createAndFill(attrs, content, marks) {
  attrs = this.computeAttrs(attrs);
  content = Fragment.from(content);

  if (content.size) {
    var before = this.contentMatch.fillBefore(content);

    if (!before) {
      return null;
    }

    content = before.append(content);
  }

  var after = this.contentMatch.matchFragment(content).fillBefore(Fragment.empty, true);

  if (!after) {
    return null;
  }

  return new Node(this, attrs, content.append(after), Mark.setFrom(marks));
}; // :: (Fragment) → bool
// Returns true if the given fragment is valid content for this node
// type with the given attributes.


NodeType.prototype.validContent = function validContent(content) {
  var result = this.contentMatch.matchFragment(content);

  if (!result || !result.validEnd) {
    return false;
  }

  for (var i = 0; i < content.childCount; i++) {
    if (!this.allowsMarks(content.child(i).marks)) {
      return false;
    }
  }

  return true;
}; // :: (MarkType) → bool
// Check whether the given mark type is allowed in this node.


NodeType.prototype.allowsMarkType = function allowsMarkType(markType) {
  return this.markSet == null || this.markSet.indexOf(markType) > -1;
}; // :: ([Mark]) → bool
// Test whether the given set of marks are allowed in this node.


NodeType.prototype.allowsMarks = function allowsMarks(marks) {
  if (this.markSet == null) {
    return true;
  }

  for (var i = 0; i < marks.length; i++) {
    if (!this.allowsMarkType(marks[i].type)) {
      return false;
    }
  }

  return true;
}; // :: ([Mark]) → [Mark]
// Removes the marks that are not allowed in this node from the given set.


NodeType.prototype.allowedMarks = function allowedMarks(marks) {
  if (this.markSet == null) {
    return marks;
  }

  var copy;

  for (var i = 0; i < marks.length; i++) {
    if (!this.allowsMarkType(marks[i].type)) {
      if (!copy) {
        copy = marks.slice(0, i);
      }
    } else if (copy) {
      copy.push(marks[i]);
    }
  }

  return !copy ? marks : copy.length ? copy : Mark.empty;
};

NodeType.compile = function compile(nodes, schema) {
  var result = Object.create(null);
  nodes.forEach(function (name, spec) {
    return result[name] = new NodeType(name, schema, spec);
  });
  var topType = schema.spec.topNode || "doc";

  if (!result[topType]) {
    throw new RangeError("Schema is missing its top node type ('" + topType + "')");
  }

  if (!result.text) {
    throw new RangeError("Every schema needs a 'text' type");
  }

  for (var _ in result.text.attrs) {
    throw new RangeError("The text node type should not have attributes");
  }

  return result;
};

Object.defineProperties(NodeType.prototype, prototypeAccessors$5); // Attribute descriptors

var Attribute = function Attribute(options) {
  this.hasDefault = Object.prototype.hasOwnProperty.call(options, "default");
  this.default = options.default;
};

var prototypeAccessors$1$3 = {
  isRequired: {
    configurable: true
  }
};

prototypeAccessors$1$3.isRequired.get = function () {
  return !this.hasDefault;
};

Object.defineProperties(Attribute.prototype, prototypeAccessors$1$3); // Marks
// ::- Like nodes, marks (which are associated with nodes to signify
// things like emphasis or being part of a link) are
// [tagged](#model.Mark.type) with type objects, which are
// instantiated once per `Schema`.

var MarkType = function MarkType(name, rank, schema, spec) {
  // :: string
  // The name of the mark type.
  this.name = name; // :: Schema
  // The schema that this mark type instance is part of.

  this.schema = schema; // :: MarkSpec
  // The spec on which the type is based.

  this.spec = spec;
  this.attrs = initAttrs(spec.attrs);
  this.rank = rank;
  this.excluded = null;
  var defaults = defaultAttrs(this.attrs);
  this.instance = defaults && new Mark(this, defaults);
}; // :: (?Object) → Mark
// Create a mark of this type. `attrs` may be `null` or an object
// containing only some of the mark's attributes. The others, if
// they have defaults, will be added.


exports.MarkType = MarkType;

MarkType.prototype.create = function create(attrs) {
  if (!attrs && this.instance) {
    return this.instance;
  }

  return new Mark(this, computeAttrs(this.attrs, attrs));
};

MarkType.compile = function compile(marks, schema) {
  var result = Object.create(null),
      rank = 0;
  marks.forEach(function (name, spec) {
    return result[name] = new MarkType(name, rank++, schema, spec);
  });
  return result;
}; // :: ([Mark]) → [Mark]
// When there is a mark of this type in the given set, a new set
// without it is returned. Otherwise, the input set is returned.


MarkType.prototype.removeFromSet = function removeFromSet(set) {
  for (var i = 0; i < set.length; i++) {
    if (set[i].type == this) {
      return set.slice(0, i).concat(set.slice(i + 1));
    }
  }

  return set;
}; // :: ([Mark]) → ?Mark
// Tests whether there is a mark of this type in the given set.


MarkType.prototype.isInSet = function isInSet(set) {
  for (var i = 0; i < set.length; i++) {
    if (set[i].type == this) {
      return set[i];
    }
  }
}; // :: (MarkType) → bool
// Queries whether a given mark type is
// [excluded](#model.MarkSpec.excludes) by this one.


MarkType.prototype.excludes = function excludes(other) {
  return this.excluded.indexOf(other) > -1;
}; // SchemaSpec:: interface
// An object describing a schema, as passed to the [`Schema`](#model.Schema)
// constructor.
//
//   nodes:: union<Object<NodeSpec>, OrderedMap<NodeSpec>>
//   The node types in this schema. Maps names to
//   [`NodeSpec`](#model.NodeSpec) objects that describe the node type
//   associated with that name. Their order is significant—it
//   determines which [parse rules](#model.NodeSpec.parseDOM) take
//   precedence by default, and which nodes come first in a given
//   [group](#model.NodeSpec.group).
//
//   marks:: ?union<Object<MarkSpec>, OrderedMap<MarkSpec>>
//   The mark types that exist in this schema. The order in which they
//   are provided determines the order in which [mark
//   sets](#model.Mark.addToSet) are sorted and in which [parse
//   rules](#model.MarkSpec.parseDOM) are tried.
//
//   topNode:: ?string
//   The name of the default top-level node for the schema. Defaults
//   to `"doc"`.
// NodeSpec:: interface
//
//   content:: ?string
//   The content expression for this node, as described in the [schema
//   guide](/docs/guide/#schema.content_expressions). When not given,
//   the node does not allow any content.
//
//   marks:: ?string
//   The marks that are allowed inside of this node. May be a
//   space-separated string referring to mark names or groups, `"_"`
//   to explicitly allow all marks, or `""` to disallow marks. When
//   not given, nodes with inline content default to allowing all
//   marks, other nodes default to not allowing marks.
//
//   group:: ?string
//   The group or space-separated groups to which this node belongs,
//   which can be referred to in the content expressions for the
//   schema.
//
//   inline:: ?bool
//   Should be set to true for inline nodes. (Implied for text nodes.)
//
//   atom:: ?bool
//   Can be set to true to indicate that, though this isn't a [leaf
//   node](#model.NodeType.isLeaf), it doesn't have directly editable
//   content and should be treated as a single unit in the view.
//
//   attrs:: ?Object<AttributeSpec>
//   The attributes that nodes of this type get.
//
//   selectable:: ?bool
//   Controls whether nodes of this type can be selected as a [node
//   selection](#state.NodeSelection). Defaults to true for non-text
//   nodes.
//
//   draggable:: ?bool
//   Determines whether nodes of this type can be dragged without
//   being selected. Defaults to false.
//
//   code:: ?bool
//   Can be used to indicate that this node contains code, which
//   causes some commands to behave differently.
//
//   defining:: ?bool
//   Determines whether this node is considered an important parent
//   node during replace operations (such as paste). Non-defining (the
//   default) nodes get dropped when their entire content is replaced,
//   whereas defining nodes persist and wrap the inserted content.
//   Likewise, in _inserted_ content the defining parents of the
//   content are preserved when possible. Typically,
//   non-default-paragraph textblock types, and possibly list items,
//   are marked as defining.
//
//   isolating:: ?bool
//   When enabled (default is false), the sides of nodes of this type
//   count as boundaries that regular editing operations, like
//   backspacing or lifting, won't cross. An example of a node that
//   should probably have this enabled is a table cell.
//
//   toDOM:: ?(node: Node) → DOMOutputSpec
//   Defines the default way a node of this type should be serialized
//   to DOM/HTML (as used by
//   [`DOMSerializer.fromSchema`](#model.DOMSerializer^fromSchema)).
//   Should return a DOM node or an [array
//   structure](#model.DOMOutputSpec) that describes one, with an
//   optional number zero (“hole”) in it to indicate where the node's
//   content should be inserted.
//
//   For text nodes, the default is to create a text DOM node. Though
//   it is possible to create a serializer where text is rendered
//   differently, this is not supported inside the editor, so you
//   shouldn't override that in your text node spec.
//
//   parseDOM:: ?[ParseRule]
//   Associates DOM parser information with this node, which can be
//   used by [`DOMParser.fromSchema`](#model.DOMParser^fromSchema) to
//   automatically derive a parser. The `node` field in the rules is
//   implied (the name of this node will be filled in automatically).
//   If you supply your own parser, you do not need to also specify
//   parsing rules in your schema.
//
//   toDebugString:: ?(node: Node) -> string
//   Defines the default way a node of this type should be serialized
//   to a string representation for debugging (e.g. in error messages).
// MarkSpec:: interface
//
//   attrs:: ?Object<AttributeSpec>
//   The attributes that marks of this type get.
//
//   inclusive:: ?bool
//   Whether this mark should be active when the cursor is positioned
//   at its end (or at its start when that is also the start of the
//   parent node). Defaults to true.
//
//   excludes:: ?string
//   Determines which other marks this mark can coexist with. Should
//   be a space-separated strings naming other marks or groups of marks.
//   When a mark is [added](#model.Mark.addToSet) to a set, all marks
//   that it excludes are removed in the process. If the set contains
//   any mark that excludes the new mark but is not, itself, excluded
//   by the new mark, the mark can not be added an the set. You can
//   use the value `"_"` to indicate that the mark excludes all
//   marks in the schema.
//
//   Defaults to only being exclusive with marks of the same type. You
//   can set it to an empty string (or any string not containing the
//   mark's own name) to allow multiple marks of a given type to
//   coexist (as long as they have different attributes).
//
//   group:: ?string
//   The group or space-separated groups to which this mark belongs.
//
//   spanning:: ?bool
//   Determines whether marks of this type can span multiple adjacent
//   nodes when serialized to DOM/HTML. Defaults to true.
//
//   toDOM:: ?(mark: Mark, inline: bool) → DOMOutputSpec
//   Defines the default way marks of this type should be serialized
//   to DOM/HTML. When the resulting spec contains a hole, that is
//   where the marked content is placed. Otherwise, it is appended to
//   the top node.
//
//   parseDOM:: ?[ParseRule]
//   Associates DOM parser information with this mark (see the
//   corresponding [node spec field](#model.NodeSpec.parseDOM)). The
//   `mark` field in the rules is implied.
// AttributeSpec:: interface
//
// Used to [define](#model.NodeSpec.attrs) attributes on nodes or
// marks.
//
//   default:: ?any
//   The default value for this attribute, to use when no explicit
//   value is provided. Attributes that have no default must be
//   provided whenever a node or mark of a type that has them is
//   created.
// ::- A document schema. Holds [node](#model.NodeType) and [mark
// type](#model.MarkType) objects for the nodes and marks that may
// occur in conforming documents, and provides functionality for
// creating and deserializing such documents.


var Schema = function Schema(spec) {
  // :: SchemaSpec
  // The [spec](#model.SchemaSpec) on which the schema is based,
  // with the added guarantee that its `nodes` and `marks`
  // properties are
  // [`OrderedMap`](https://github.com/marijnh/orderedmap) instances
  // (not raw objects).
  this.spec = {};

  for (var prop in spec) {
    this.spec[prop] = spec[prop];
  }

  this.spec.nodes = _orderedmap.default.from(spec.nodes);
  this.spec.marks = _orderedmap.default.from(spec.marks); // :: Object<NodeType>
  // An object mapping the schema's node names to node type objects.

  this.nodes = NodeType.compile(this.spec.nodes, this); // :: Object<MarkType>
  // A map from mark names to mark type objects.

  this.marks = MarkType.compile(this.spec.marks, this);
  var contentExprCache = Object.create(null);

  for (var prop$1 in this.nodes) {
    if (prop$1 in this.marks) {
      throw new RangeError(prop$1 + " can not be both a node and a mark");
    }

    var type = this.nodes[prop$1],
        contentExpr = type.spec.content || "",
        markExpr = type.spec.marks;
    type.contentMatch = contentExprCache[contentExpr] || (contentExprCache[contentExpr] = ContentMatch.parse(contentExpr, this.nodes));
    type.inlineContent = type.contentMatch.inlineContent;
    type.markSet = markExpr == "_" ? null : markExpr ? gatherMarks(this, markExpr.split(" ")) : markExpr == "" || !type.inlineContent ? [] : null;
  }

  for (var prop$2 in this.marks) {
    var type$1 = this.marks[prop$2],
        excl = type$1.spec.excludes;
    type$1.excluded = excl == null ? [type$1] : excl == "" ? [] : gatherMarks(this, excl.split(" "));
  }

  this.nodeFromJSON = this.nodeFromJSON.bind(this);
  this.markFromJSON = this.markFromJSON.bind(this); // :: NodeType
  // The type of the [default top node](#model.SchemaSpec.topNode)
  // for this schema.

  this.topNodeType = this.nodes[this.spec.topNode || "doc"]; // :: Object
  // An object for storing whatever values modules may want to
  // compute and cache per schema. (If you want to store something
  // in it, try to use property names unlikely to clash.)

  this.cached = Object.create(null);
  this.cached.wrappings = Object.create(null);
}; // :: (union<string, NodeType>, ?Object, ?union<Fragment, Node, [Node]>, ?[Mark]) → Node
// Create a node in this schema. The `type` may be a string or a
// `NodeType` instance. Attributes will be extended
// with defaults, `content` may be a `Fragment`,
// `null`, a `Node`, or an array of nodes.


exports.Schema = Schema;

Schema.prototype.node = function node(type, attrs, content, marks) {
  if (typeof type == "string") {
    type = this.nodeType(type);
  } else if (!(type instanceof NodeType)) {
    throw new RangeError("Invalid node type: " + type);
  } else if (type.schema != this) {
    throw new RangeError("Node type from different schema used (" + type.name + ")");
  }

  return type.createChecked(attrs, content, marks);
}; // :: (string, ?[Mark]) → Node
// Create a text node in the schema. Empty text nodes are not
// allowed.


Schema.prototype.text = function text(text$1, marks) {
  var type = this.nodes.text;
  return new TextNode(type, type.defaultAttrs, text$1, Mark.setFrom(marks));
}; // :: (union<string, MarkType>, ?Object) → Mark
// Create a mark with the given type and attributes.


Schema.prototype.mark = function mark(type, attrs) {
  if (typeof type == "string") {
    type = this.marks[type];
  }

  return type.create(attrs);
}; // :: (Object) → Node
// Deserialize a node from its JSON representation. This method is
// bound.


Schema.prototype.nodeFromJSON = function nodeFromJSON(json) {
  return Node.fromJSON(this, json);
}; // :: (Object) → Mark
// Deserialize a mark from its JSON representation. This method is
// bound.


Schema.prototype.markFromJSON = function markFromJSON(json) {
  return Mark.fromJSON(this, json);
};

Schema.prototype.nodeType = function nodeType(name) {
  var found = this.nodes[name];

  if (!found) {
    throw new RangeError("Unknown node type: " + name);
  }

  return found;
};

function gatherMarks(schema, marks) {
  var found = [];

  for (var i = 0; i < marks.length; i++) {
    var name = marks[i],
        mark = schema.marks[name],
        ok = mark;

    if (mark) {
      found.push(mark);
    } else {
      for (var prop in schema.marks) {
        var mark$1 = schema.marks[prop];

        if (name == "_" || mark$1.spec.group && mark$1.spec.group.split(" ").indexOf(name) > -1) {
          found.push(ok = mark$1);
        }
      }
    }

    if (!ok) {
      throw new SyntaxError("Unknown mark type: '" + marks[i] + "'");
    }
  }

  return found;
} // ParseOptions:: interface
// These are the options recognized by the
// [`parse`](#model.DOMParser.parse) and
// [`parseSlice`](#model.DOMParser.parseSlice) methods.
//
//   preserveWhitespace:: ?union<bool, "full">
//   By default, whitespace is collapsed as per HTML's rules. Pass
//   `true` to preserve whitespace, but normalize newlines to
//   spaces, and `"full"` to preserve whitespace entirely.
//
//   findPositions:: ?[{node: dom.Node, offset: number}]
//   When given, the parser will, beside parsing the content,
//   record the document positions of the given DOM positions. It
//   will do so by writing to the objects, adding a `pos` property
//   that holds the document position. DOM positions that are not
//   in the parsed content will not be written to.
//
//   from:: ?number
//   The child node index to start parsing from.
//
//   to:: ?number
//   The child node index to stop parsing at.
//
//   topNode:: ?Node
//   By default, the content is parsed into the schema's default
//   [top node type](#model.Schema.topNodeType). You can pass this
//   option to use the type and attributes from a different node
//   as the top container.
//
//   topMatch:: ?ContentMatch
//   Provide the starting content match that content parsed into the
//   top node is matched against.
//
//   context:: ?ResolvedPos
//   A set of additional nodes to count as
//   [context](#model.ParseRule.context) when parsing, above the
//   given [top node](#model.ParseOptions.topNode).
// ParseRule:: interface
// A value that describes how to parse a given DOM node or inline
// style as a ProseMirror node or mark.
//
//   tag:: ?string
//   A CSS selector describing the kind of DOM elements to match. A
//   single rule should have _either_ a `tag` or a `style` property.
//
//   namespace:: ?string
//   The namespace to match. This should be used with `tag`.
//   Nodes are only matched when the namespace matches or this property
//   is null.
//
//   style:: ?string
//   A CSS property name to match. When given, this rule matches
//   inline styles that list that property. May also have the form
//   `"property=value"`, in which case the rule only matches if the
//   propery's value exactly matches the given value. (For more
//   complicated filters, use [`getAttrs`](#model.ParseRule.getAttrs)
//   and return false to indicate that the match failed.)
//
//   priority:: ?number
//   Can be used to change the order in which the parse rules in a
//   schema are tried. Those with higher priority come first. Rules
//   without a priority are counted as having priority 50. This
//   property is only meaningful in a schema—when directly
//   constructing a parser, the order of the rule array is used.
//
//   context:: ?string
//   When given, restricts this rule to only match when the current
//   context—the parent nodes into which the content is being
//   parsed—matches this expression. Should contain one or more node
//   names or node group names followed by single or double slashes.
//   For example `"paragraph/"` means the rule only matches when the
//   parent node is a paragraph, `"blockquote/paragraph/"` restricts
//   it to be in a paragraph that is inside a blockquote, and
//   `"section//"` matches any position inside a section—a double
//   slash matches any sequence of ancestor nodes. To allow multiple
//   different contexts, they can be separated by a pipe (`|`)
//   character, as in `"blockquote/|list_item/"`.
//
//   node:: ?string
//   The name of the node type to create when this rule matches. Only
//   valid for rules with a `tag` property, not for style rules. Each
//   rule should have one of a `node`, `mark`, or `ignore` property
//   (except when it appears in a [node](#model.NodeSpec.parseDOM) or
//   [mark spec](#model.MarkSpec.parseDOM), in which case the `node`
//   or `mark` property will be derived from its position).
//
//   mark:: ?string
//   The name of the mark type to wrap the matched content in.
//
//   ignore:: ?bool
//   When true, ignore content that matches this rule.
//
//   skip:: ?bool
//   When true, ignore the node that matches this rule, but do parse
//   its content.
//
//   attrs:: ?Object
//   Attributes for the node or mark created by this rule. When
//   `getAttrs` is provided, it takes precedence.
//
//   getAttrs:: ?(union<dom.Node, string>) → ?union<Object, false>
//   A function used to compute the attributes for the node or mark
//   created by this rule. Can also be used to describe further
//   conditions the DOM element or style must match. When it returns
//   `false`, the rule won't match. When it returns null or undefined,
//   that is interpreted as an empty/default set of attributes.
//
//   Called with a DOM Element for `tag` rules, and with a string (the
//   style's value) for `style` rules.
//
//   contentElement:: ?union<string, (dom.Node) → dom.Node>
//   For `tag` rules that produce non-leaf nodes or marks, by default
//   the content of the DOM element is parsed as content of the mark
//   or node. If the child nodes are in a descendent node, this may be
//   a CSS selector string that the parser must use to find the actual
//   content element, or a function that returns the actual content
//   element to the parser.
//
//   getContent:: ?(dom.Node, schema: Schema) → Fragment
//   Can be used to override the content of a matched node. When
//   present, instead of parsing the node's child nodes, the result of
//   this function is used.
//
//   preserveWhitespace:: ?union<bool, "full">
//   Controls whether whitespace should be preserved when parsing the
//   content inside the matched element. `false` means whitespace may
//   be collapsed, `true` means that whitespace should be preserved
//   but newlines normalized to spaces, and `"full"` means that
//   newlines should also be preserved.
// ::- A DOM parser represents a strategy for parsing DOM content into
// a ProseMirror document conforming to a given schema. Its behavior
// is defined by an array of [rules](#model.ParseRule).


var DOMParser = function DOMParser(schema, rules) {
  var this$1 = this; // :: Schema
  // The schema into which the parser parses.

  this.schema = schema; // :: [ParseRule]
  // The set of [parse rules](#model.ParseRule) that the parser
  // uses, in order of precedence.

  this.rules = rules;
  this.tags = [];
  this.styles = [];
  rules.forEach(function (rule) {
    if (rule.tag) {
      this$1.tags.push(rule);
    } else if (rule.style) {
      this$1.styles.push(rule);
    }
  });
}; // :: (dom.Node, ?ParseOptions) → Node
// Parse a document from the content of a DOM node.


exports.DOMParser = DOMParser;

DOMParser.prototype.parse = function parse(dom, options) {
  if (options === void 0) options = {};
  var context = new ParseContext(this, options, false);
  context.addAll(dom, null, options.from, options.to);
  return context.finish();
}; // :: (dom.Node, ?ParseOptions) → Slice
// Parses the content of the given DOM node, like
// [`parse`](#model.DOMParser.parse), and takes the same set of
// options. But unlike that method, which produces a whole node,
// this one returns a slice that is open at the sides, meaning that
// the schema constraints aren't applied to the start of nodes to
// the left of the input and the end of nodes at the end.


DOMParser.prototype.parseSlice = function parseSlice(dom, options) {
  if (options === void 0) options = {};
  var context = new ParseContext(this, options, true);
  context.addAll(dom, null, options.from, options.to);
  return Slice.maxOpen(context.finish());
};

DOMParser.prototype.matchTag = function matchTag(dom, context) {
  for (var i = 0; i < this.tags.length; i++) {
    var rule = this.tags[i];

    if (matches(dom, rule.tag) && (rule.namespace === undefined || dom.namespaceURI == rule.namespace) && (!rule.context || context.matchesContext(rule.context))) {
      if (rule.getAttrs) {
        var result = rule.getAttrs(dom);

        if (result === false) {
          continue;
        }

        rule.attrs = result;
      }

      return rule;
    }
  }
};

DOMParser.prototype.matchStyle = function matchStyle(prop, value, context) {
  for (var i = 0; i < this.styles.length; i++) {
    var rule = this.styles[i];

    if (rule.style.indexOf(prop) != 0 || rule.context && !context.matchesContext(rule.context) || // Test that the style string either precisely matches the prop,
    // or has an '=' sign after the prop, followed by the given
    // value.
    rule.style.length > prop.length && (rule.style.charCodeAt(prop.length) != 61 || rule.style.slice(prop.length + 1) != value)) {
      continue;
    }

    if (rule.getAttrs) {
      var result = rule.getAttrs(value);

      if (result === false) {
        continue;
      }

      rule.attrs = result;
    }

    return rule;
  }
}; // : (Schema) → [ParseRule]


DOMParser.schemaRules = function schemaRules(schema) {
  var result = [];

  function insert(rule) {
    var priority = rule.priority == null ? 50 : rule.priority,
        i = 0;

    for (; i < result.length; i++) {
      var next = result[i],
          nextPriority = next.priority == null ? 50 : next.priority;

      if (nextPriority < priority) {
        break;
      }
    }

    result.splice(i, 0, rule);
  }

  var loop = function (name) {
    var rules = schema.marks[name].spec.parseDOM;

    if (rules) {
      rules.forEach(function (rule) {
        insert(rule = copy(rule));
        rule.mark = name;
      });
    }
  };

  for (var name in schema.marks) loop(name);

  var loop$1 = function (name) {
    var rules$1 = schema.nodes[name$1].spec.parseDOM;

    if (rules$1) {
      rules$1.forEach(function (rule) {
        insert(rule = copy(rule));
        rule.node = name$1;
      });
    }
  };

  for (var name$1 in schema.nodes) loop$1();

  return result;
}; // :: (Schema) → DOMParser
// Construct a DOM parser using the parsing rules listed in a
// schema's [node specs](#model.NodeSpec.parseDOM), reordered by
// [priority](#model.ParseRule.priority).


DOMParser.fromSchema = function fromSchema(schema) {
  return schema.cached.domParser || (schema.cached.domParser = new DOMParser(schema, DOMParser.schemaRules(schema)));
}; // : Object<bool> The block-level tags in HTML5


var blockTags = {
  address: true,
  article: true,
  aside: true,
  blockquote: true,
  canvas: true,
  dd: true,
  div: true,
  dl: true,
  fieldset: true,
  figcaption: true,
  figure: true,
  footer: true,
  form: true,
  h1: true,
  h2: true,
  h3: true,
  h4: true,
  h5: true,
  h6: true,
  header: true,
  hgroup: true,
  hr: true,
  li: true,
  noscript: true,
  ol: true,
  output: true,
  p: true,
  pre: true,
  section: true,
  table: true,
  tfoot: true,
  ul: true
}; // : Object<bool> The tags that we normally ignore.

var ignoreTags = {
  head: true,
  noscript: true,
  object: true,
  script: true,
  style: true,
  title: true
}; // : Object<bool> List tags.

var listTags = {
  ol: true,
  ul: true
}; // Using a bitfield for node context options

var OPT_PRESERVE_WS = 1,
    OPT_PRESERVE_WS_FULL = 2,
    OPT_OPEN_LEFT = 4;

function wsOptionsFor(preserveWhitespace) {
  return (preserveWhitespace ? OPT_PRESERVE_WS : 0) | (preserveWhitespace === "full" ? OPT_PRESERVE_WS_FULL : 0);
}

var NodeContext = function NodeContext(type, attrs, marks, pendingMarks, solid, match, options) {
  this.type = type;
  this.attrs = attrs;
  this.solid = solid;
  this.match = match || (options & OPT_OPEN_LEFT ? null : type.contentMatch);
  this.options = options;
  this.content = []; // Marks applied to this node itself

  this.marks = marks; // Marks applied to its children

  this.activeMarks = Mark.none; // Marks that can't apply here, but will be used in children if possible

  this.pendingMarks = pendingMarks;
};

NodeContext.prototype.findWrapping = function findWrapping(node) {
  if (!this.match) {
    if (!this.type) {
      return [];
    }

    var fill = this.type.contentMatch.fillBefore(Fragment.from(node));

    if (fill) {
      this.match = this.type.contentMatch.matchFragment(fill);
    } else {
      var start = this.type.contentMatch,
          wrap;

      if (wrap = start.findWrapping(node.type)) {
        this.match = start;
        return wrap;
      } else {
        return null;
      }
    }
  }

  return this.match.findWrapping(node.type);
};

NodeContext.prototype.finish = function finish(openEnd) {
  if (!(this.options & OPT_PRESERVE_WS)) {
    // Strip trailing whitespace
    var last = this.content[this.content.length - 1],
        m;

    if (last && last.isText && (m = /[ \t\r\n\u000c]+$/.exec(last.text))) {
      if (last.text.length == m[0].length) {
        this.content.pop();
      } else {
        this.content[this.content.length - 1] = last.withText(last.text.slice(0, last.text.length - m[0].length));
      }
    }
  }

  var content = Fragment.from(this.content);

  if (!openEnd && this.match) {
    content = content.append(this.match.fillBefore(Fragment.empty, true));
  }

  return this.type ? this.type.create(this.attrs, content, this.marks) : content;
};

NodeContext.prototype.applyPending = function applyPending(nextType) {
  for (var i = 0, pending = this.pendingMarks; i < pending.length; i++) {
    var mark = pending[i];

    if ((this.type ? this.type.allowsMarkType(mark.type) : markMayApply(mark.type, nextType)) && !mark.isInSet(this.activeMarks)) {
      this.activeMarks = mark.addToSet(this.activeMarks);
      this.pendingMarks = mark.removeFromSet(this.pendingMarks);
    }
  }
};

var ParseContext = function ParseContext(parser, options, open) {
  // : DOMParser The parser we are using.
  this.parser = parser; // : Object The options passed to this parse.

  this.options = options;
  this.isOpen = open;
  var topNode = options.topNode,
      topContext;
  var topOptions = wsOptionsFor(options.preserveWhitespace) | (open ? OPT_OPEN_LEFT : 0);

  if (topNode) {
    topContext = new NodeContext(topNode.type, topNode.attrs, Mark.none, Mark.none, true, options.topMatch || topNode.type.contentMatch, topOptions);
  } else if (open) {
    topContext = new NodeContext(null, null, Mark.none, Mark.none, true, null, topOptions);
  } else {
    topContext = new NodeContext(parser.schema.topNodeType, null, Mark.none, Mark.none, true, null, topOptions);
  }

  this.nodes = [topContext]; // : [Mark] The current set of marks

  this.open = 0;
  this.find = options.findPositions;
  this.needsBlock = false;
};

var prototypeAccessors$6 = {
  top: {
    configurable: true
  },
  currentPos: {
    configurable: true
  }
};

prototypeAccessors$6.top.get = function () {
  return this.nodes[this.open];
}; // : (dom.Node)
// Add a DOM node to the content. Text is inserted as text node,
// otherwise, the node is passed to `addElement` or, if it has a
// `style` attribute, `addElementWithStyles`.


ParseContext.prototype.addDOM = function addDOM(dom) {
  if (dom.nodeType == 3) {
    this.addTextNode(dom);
  } else if (dom.nodeType == 1) {
    var style = dom.getAttribute("style");
    var marks = style ? this.readStyles(parseStyles(style)) : null,
        top = this.top;

    if (marks != null) {
      for (var i = 0; i < marks.length; i++) {
        this.addPendingMark(marks[i]);
      }
    }

    this.addElement(dom);

    if (marks != null) {
      for (var i$1 = 0; i$1 < marks.length; i$1++) {
        this.removePendingMark(marks[i$1], top);
      }
    }
  }
};

ParseContext.prototype.addTextNode = function addTextNode(dom) {
  var value = dom.nodeValue;
  var top = this.top;

  if ((top.type ? top.type.inlineContent : top.content.length && top.content[0].isInline) || /[^ \t\r\n\u000c]/.test(value)) {
    if (!(top.options & OPT_PRESERVE_WS)) {
      value = value.replace(/[ \t\r\n\u000c]+/g, " "); // If this starts with whitespace, and there is no node before it, or
      // a hard break, or a text node that ends with whitespace, strip the
      // leading space.

      if (/^[ \t\r\n\u000c]/.test(value) && this.open == this.nodes.length - 1) {
        var nodeBefore = top.content[top.content.length - 1];
        var domNodeBefore = dom.previousSibling;

        if (!nodeBefore || domNodeBefore && domNodeBefore.nodeName == 'BR' || nodeBefore.isText && /[ \t\r\n\u000c]$/.test(nodeBefore.text)) {
          value = value.slice(1);
        }
      }
    } else if (!(top.options & OPT_PRESERVE_WS_FULL)) {
      value = value.replace(/\r?\n|\r/g, " ");
    }

    if (value) {
      this.insertNode(this.parser.schema.text(value));
    }

    this.findInText(dom);
  } else {
    this.findInside(dom);
  }
}; // : (dom.Element)
// Try to find a handler for the given tag and use that to parse. If
// none is found, the element's content nodes are added directly.


ParseContext.prototype.addElement = function addElement(dom) {
  var name = dom.nodeName.toLowerCase();

  if (listTags.hasOwnProperty(name)) {
    normalizeList(dom);
  }

  var rule = this.options.ruleFromNode && this.options.ruleFromNode(dom) || this.parser.matchTag(dom, this);

  if (rule ? rule.ignore : ignoreTags.hasOwnProperty(name)) {
    this.findInside(dom);
  } else if (!rule || rule.skip) {
    if (rule && rule.skip.nodeType) {
      dom = rule.skip;
    }

    var sync,
        top = this.top,
        oldNeedsBlock = this.needsBlock;

    if (blockTags.hasOwnProperty(name)) {
      sync = true;

      if (!top.type) {
        this.needsBlock = true;
      }
    } else if (!dom.firstChild) {
      this.leafFallback(dom);
      return;
    }

    this.addAll(dom);

    if (sync) {
      this.sync(top);
    }

    this.needsBlock = oldNeedsBlock;
  } else {
    this.addElementByRule(dom, rule);
  }
}; // Called for leaf DOM nodes that would otherwise be ignored


ParseContext.prototype.leafFallback = function leafFallback(dom) {
  if (dom.nodeName == "BR" && this.top.type && this.top.type.inlineContent) {
    this.addTextNode(dom.ownerDocument.createTextNode("\n"));
  }
}; // Run any style parser associated with the node's styles. Either
// return an array of marks, or null to indicate some of the styles
// had a rule with `ignore` set.


ParseContext.prototype.readStyles = function readStyles(styles) {
  var marks = Mark.none;

  for (var i = 0; i < styles.length; i += 2) {
    var rule = this.parser.matchStyle(styles[i], styles[i + 1], this);

    if (!rule) {
      continue;
    }

    if (rule.ignore) {
      return null;
    }

    marks = this.parser.schema.marks[rule.mark].create(rule.attrs).addToSet(marks);
  }

  return marks;
}; // : (dom.Element, ParseRule) → bool
// Look up a handler for the given node. If none are found, return
// false. Otherwise, apply it, use its return value to drive the way
// the node's content is wrapped, and return true.


ParseContext.prototype.addElementByRule = function addElementByRule(dom, rule) {
  var this$1 = this;
  var sync, nodeType, markType, mark;

  if (rule.node) {
    nodeType = this.parser.schema.nodes[rule.node];

    if (!nodeType.isLeaf) {
      sync = this.enter(nodeType, rule.attrs, rule.preserveWhitespace);
    } else if (!this.insertNode(nodeType.create(rule.attrs))) {
      this.leafFallback(dom);
    }
  } else {
    markType = this.parser.schema.marks[rule.mark];
    mark = markType.create(rule.attrs);
    this.addPendingMark(mark);
  }

  var startIn = this.top;

  if (nodeType && nodeType.isLeaf) {
    this.findInside(dom);
  } else if (rule.getContent) {
    this.findInside(dom);
    rule.getContent(dom, this.parser.schema).forEach(function (node) {
      return this$1.insertNode(node);
    });
  } else {
    var contentDOM = rule.contentElement;

    if (typeof contentDOM == "string") {
      contentDOM = dom.querySelector(contentDOM);
    } else if (typeof contentDOM == "function") {
      contentDOM = contentDOM(dom);
    }

    if (!contentDOM) {
      contentDOM = dom;
    }

    this.findAround(dom, contentDOM, true);
    this.addAll(contentDOM, sync);
  }

  if (sync) {
    this.sync(startIn);
    this.open--;
  }

  if (mark) {
    this.removePendingMark(mark, startIn);
  }
}; // : (dom.Node, ?NodeBuilder, ?number, ?number)
// Add all child nodes between `startIndex` and `endIndex` (or the
// whole node, if not given). If `sync` is passed, use it to
// synchronize after every block element.


ParseContext.prototype.addAll = function addAll(parent, sync, startIndex, endIndex) {
  var index = startIndex || 0;

  for (var dom = startIndex ? parent.childNodes[startIndex] : parent.firstChild, end = endIndex == null ? null : parent.childNodes[endIndex]; dom != end; dom = dom.nextSibling, ++index) {
    this.findAtPoint(parent, index);
    this.addDOM(dom);

    if (sync && blockTags.hasOwnProperty(dom.nodeName.toLowerCase())) {
      this.sync(sync);
    }
  }

  this.findAtPoint(parent, index);
}; // Try to find a way to fit the given node type into the current
// context. May add intermediate wrappers and/or leave non-solid
// nodes that we're in.


ParseContext.prototype.findPlace = function findPlace(node) {
  var route, sync;

  for (var depth = this.open; depth >= 0; depth--) {
    var cx = this.nodes[depth];
    var found = cx.findWrapping(node);

    if (found && (!route || route.length > found.length)) {
      route = found;
      sync = cx;

      if (!found.length) {
        break;
      }
    }

    if (cx.solid) {
      break;
    }
  }

  if (!route) {
    return false;
  }

  this.sync(sync);

  for (var i = 0; i < route.length; i++) {
    this.enterInner(route[i], null, false);
  }

  return true;
}; // : (Node) → ?Node
// Try to insert the given node, adjusting the context when needed.


ParseContext.prototype.insertNode = function insertNode(node) {
  if (node.isInline && this.needsBlock && !this.top.type) {
    var block = this.textblockFromContext();

    if (block) {
      this.enterInner(block);
    }
  }

  if (this.findPlace(node)) {
    this.closeExtra();
    var top = this.top;
    top.applyPending(node.type);

    if (top.match) {
      top.match = top.match.matchType(node.type);
    }

    var marks = top.activeMarks;

    for (var i = 0; i < node.marks.length; i++) {
      if (!top.type || top.type.allowsMarkType(node.marks[i].type)) {
        marks = node.marks[i].addToSet(marks);
      }
    }

    top.content.push(node.mark(marks));
    return true;
  }

  return false;
}; // : (NodeType, ?Object) → bool
// Try to start a node of the given type, adjusting the context when
// necessary.


ParseContext.prototype.enter = function enter(type, attrs, preserveWS) {
  var ok = this.findPlace(type.create(attrs));

  if (ok) {
    this.enterInner(type, attrs, true, preserveWS);
  }

  return ok;
}; // Open a node of the given type


ParseContext.prototype.enterInner = function enterInner(type, attrs, solid, preserveWS) {
  this.closeExtra();
  var top = this.top;
  top.applyPending(type);
  top.match = top.match && top.match.matchType(type, attrs);
  var options = preserveWS == null ? top.options & ~OPT_OPEN_LEFT : wsOptionsFor(preserveWS);

  if (top.options & OPT_OPEN_LEFT && top.content.length == 0) {
    options |= OPT_OPEN_LEFT;
  }

  this.nodes.push(new NodeContext(type, attrs, top.activeMarks, top.pendingMarks, solid, null, options));
  this.open++;
}; // Make sure all nodes above this.open are finished and added to
// their parents


ParseContext.prototype.closeExtra = function closeExtra(openEnd) {
  var i = this.nodes.length - 1;

  if (i > this.open) {
    for (; i > this.open; i--) {
      this.nodes[i - 1].content.push(this.nodes[i].finish(openEnd));
    }

    this.nodes.length = this.open + 1;
  }
};

ParseContext.prototype.finish = function finish() {
  this.open = 0;
  this.closeExtra(this.isOpen);
  return this.nodes[0].finish(this.isOpen || this.options.topOpen);
};

ParseContext.prototype.sync = function sync(to) {
  for (var i = this.open; i >= 0; i--) {
    if (this.nodes[i] == to) {
      this.open = i;
      return;
    }
  }
};

prototypeAccessors$6.currentPos.get = function () {
  this.closeExtra();
  var pos = 0;

  for (var i = this.open; i >= 0; i--) {
    var content = this.nodes[i].content;

    for (var j = content.length - 1; j >= 0; j--) {
      pos += content[j].nodeSize;
    }

    if (i) {
      pos++;
    }
  }

  return pos;
};

ParseContext.prototype.findAtPoint = function findAtPoint(parent, offset) {
  if (this.find) {
    for (var i = 0; i < this.find.length; i++) {
      if (this.find[i].node == parent && this.find[i].offset == offset) {
        this.find[i].pos = this.currentPos;
      }
    }
  }
};

ParseContext.prototype.findInside = function findInside(parent) {
  if (this.find) {
    for (var i = 0; i < this.find.length; i++) {
      if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node)) {
        this.find[i].pos = this.currentPos;
      }
    }
  }
};

ParseContext.prototype.findAround = function findAround(parent, content, before) {
  if (parent != content && this.find) {
    for (var i = 0; i < this.find.length; i++) {
      if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node)) {
        var pos = content.compareDocumentPosition(this.find[i].node);

        if (pos & (before ? 2 : 4)) {
          this.find[i].pos = this.currentPos;
        }
      }
    }
  }
};

ParseContext.prototype.findInText = function findInText(textNode) {
  if (this.find) {
    for (var i = 0; i < this.find.length; i++) {
      if (this.find[i].node == textNode) {
        this.find[i].pos = this.currentPos - (textNode.nodeValue.length - this.find[i].offset);
      }
    }
  }
}; // : (string) → bool
// Determines whether the given [context
// string](#ParseRule.context) matches this context.


ParseContext.prototype.matchesContext = function matchesContext(context) {
  var this$1 = this;

  if (context.indexOf("|") > -1) {
    return context.split(/\s*\|\s*/).some(this.matchesContext, this);
  }

  var parts = context.split("/");
  var option = this.options.context;
  var useRoot = !this.isOpen && (!option || option.parent.type == this.nodes[0].type);
  var minDepth = -(option ? option.depth + 1 : 0) + (useRoot ? 0 : 1);

  var match = function (i, depth) {
    for (; i >= 0; i--) {
      var part = parts[i];

      if (part == "") {
        if (i == parts.length - 1 || i == 0) {
          continue;
        }

        for (; depth >= minDepth; depth--) {
          if (match(i - 1, depth)) {
            return true;
          }
        }

        return false;
      } else {
        var next = depth > 0 || depth == 0 && useRoot ? this$1.nodes[depth].type : option && depth >= minDepth ? option.node(depth - minDepth).type : null;

        if (!next || next.name != part && next.groups.indexOf(part) == -1) {
          return false;
        }

        depth--;
      }
    }

    return true;
  };

  return match(parts.length - 1, this.open);
};

ParseContext.prototype.textblockFromContext = function textblockFromContext() {
  var $context = this.options.context;

  if ($context) {
    for (var d = $context.depth; d >= 0; d--) {
      var deflt = $context.node(d).contentMatchAt($context.indexAfter(d)).defaultType;

      if (deflt && deflt.isTextblock && deflt.defaultAttrs) {
        return deflt;
      }
    }
  }

  for (var name in this.parser.schema.nodes) {
    var type = this.parser.schema.nodes[name];

    if (type.isTextblock && type.defaultAttrs) {
      return type;
    }
  }
};

ParseContext.prototype.addPendingMark = function addPendingMark(mark) {
  this.top.pendingMarks = mark.addToSet(this.top.pendingMarks);
};

ParseContext.prototype.removePendingMark = function removePendingMark(mark, upto) {
  for (var depth = this.open; depth >= 0; depth--) {
    var level = this.nodes[depth];
    var found = level.pendingMarks.lastIndexOf(mark);

    if (found > -1) {
      level.pendingMarks = mark.removeFromSet(level.pendingMarks);
    } else {
      level.activeMarks = mark.removeFromSet(level.activeMarks);
    }

    if (level == upto) {
      break;
    }
  }
};

Object.defineProperties(ParseContext.prototype, prototypeAccessors$6); // Kludge to work around directly nested list nodes produced by some
// tools and allowed by browsers to mean that the nested list is
// actually part of the list item above it.

function normalizeList(dom) {
  for (var child = dom.firstChild, prevItem = null; child; child = child.nextSibling) {
    var name = child.nodeType == 1 ? child.nodeName.toLowerCase() : null;

    if (name && listTags.hasOwnProperty(name) && prevItem) {
      prevItem.appendChild(child);
      child = prevItem;
    } else if (name == "li") {
      prevItem = child;
    } else if (name) {
      prevItem = null;
    }
  }
} // Apply a CSS selector.


function matches(dom, selector) {
  return (dom.matches || dom.msMatchesSelector || dom.webkitMatchesSelector || dom.mozMatchesSelector).call(dom, selector);
} // : (string) → [string]
// Tokenize a style attribute into property/value pairs.


function parseStyles(style) {
  var re = /\s*([\w-]+)\s*:\s*([^;]+)/g,
      m,
      result = [];

  while (m = re.exec(style)) {
    result.push(m[1], m[2].trim());
  }

  return result;
}

function copy(obj) {
  var copy = {};

  for (var prop in obj) {
    copy[prop] = obj[prop];
  }

  return copy;
} // Used when finding a mark at the top level of a fragment parse.
// Checks whether it would be reasonable to apply a given mark type to
// a given node, by looking at the way the mark occurs in the schema.


function markMayApply(markType, nodeType) {
  var nodes = nodeType.schema.nodes;

  var loop = function (name) {
    var parent = nodes[name];

    if (!parent.allowsMarkType(markType)) {
      return;
    }

    var seen = [],
        scan = function (match) {
      seen.push(match);

      for (var i = 0; i < match.edgeCount; i++) {
        var ref = match.edge(i);
        var type = ref.type;
        var next = ref.next;

        if (type == nodeType) {
          return true;
        }

        if (seen.indexOf(next) < 0 && scan(next)) {
          return true;
        }
      }
    };

    if (scan(parent.contentMatch)) {
      return {
        v: true
      };
    }
  };

  for (var name in nodes) {
    var returned = loop(name);
    if (returned) return returned.v;
  }
} // DOMOutputSpec:: interface
// A description of a DOM structure. Can be either a string, which is
// interpreted as a text node, a DOM node, which is interpreted as
// itself, or an array.
//
// An array describes a DOM element. The first value in the array
// should be a string—the name of the DOM element, optionally prefixed
// by a namespace URL and a space. If the second element is plain
// object, it is interpreted as a set of attributes for the element.
// Any elements after that (including the 2nd if it's not an attribute
// object) are interpreted as children of the DOM elements, and must
// either be valid `DOMOutputSpec` values, or the number zero.
//
// The number zero (pronounced “hole”) is used to indicate the place
// where a node's child nodes should be inserted. If it occurs in an
// output spec, it should be the only child element in its parent
// node.
// ::- A DOM serializer knows how to convert ProseMirror nodes and
// marks of various types to DOM nodes.


var DOMSerializer = function DOMSerializer(nodes, marks) {
  // :: Object<(node: Node) → DOMOutputSpec>
  // The node serialization functions.
  this.nodes = nodes || {}; // :: Object<?(mark: Mark, inline: bool) → DOMOutputSpec>
  // The mark serialization functions.

  this.marks = marks || {};
}; // :: (Fragment, ?Object) → dom.DocumentFragment
// Serialize the content of this fragment to a DOM fragment. When
// not in the browser, the `document` option, containing a DOM
// document, should be passed so that the serializer can create
// nodes.


exports.DOMSerializer = DOMSerializer;

DOMSerializer.prototype.serializeFragment = function serializeFragment(fragment, options, target) {
  var this$1 = this;
  if (options === void 0) options = {};

  if (!target) {
    target = doc(options).createDocumentFragment();
  }

  var top = target,
      active = null;
  fragment.forEach(function (node) {
    if (active || node.marks.length) {
      if (!active) {
        active = [];
      }

      var keep = 0,
          rendered = 0;

      while (keep < active.length && rendered < node.marks.length) {
        var next = node.marks[rendered];

        if (!this$1.marks[next.type.name]) {
          rendered++;
          continue;
        }

        if (!next.eq(active[keep]) || next.type.spec.spanning === false) {
          break;
        }

        keep += 2;
        rendered++;
      }

      while (keep < active.length) {
        top = active.pop();
        active.pop();
      }

      while (rendered < node.marks.length) {
        var add = node.marks[rendered++];
        var markDOM = this$1.serializeMark(add, node.isInline, options);

        if (markDOM) {
          active.push(add, top);
          top.appendChild(markDOM.dom);
          top = markDOM.contentDOM || markDOM.dom;
        }
      }
    }

    top.appendChild(this$1.serializeNode(node, options));
  });
  return target;
}; // :: (Node, ?Object) → dom.Node
// Serialize this node to a DOM node. This can be useful when you
// need to serialize a part of a document, as opposed to the whole
// document. To serialize a whole document, use
// [`serializeFragment`](#model.DOMSerializer.serializeFragment) on
// its [content](#model.Node.content).


DOMSerializer.prototype.serializeNode = function serializeNode(node, options) {
  if (options === void 0) options = {};
  var ref = DOMSerializer.renderSpec(doc(options), this.nodes[node.type.name](node));
  var dom = ref.dom;
  var contentDOM = ref.contentDOM;

  if (contentDOM) {
    if (node.isLeaf) {
      throw new RangeError("Content hole not allowed in a leaf node spec");
    }

    if (options.onContent) {
      options.onContent(node, contentDOM, options);
    } else {
      this.serializeFragment(node.content, options, contentDOM);
    }
  }

  return dom;
};

DOMSerializer.prototype.serializeNodeAndMarks = function serializeNodeAndMarks(node, options) {
  if (options === void 0) options = {};
  var dom = this.serializeNode(node, options);

  for (var i = node.marks.length - 1; i >= 0; i--) {
    var wrap = this.serializeMark(node.marks[i], node.isInline, options);

    if (wrap) {
      (wrap.contentDOM || wrap.dom).appendChild(dom);
      dom = wrap.dom;
    }
  }

  return dom;
};

DOMSerializer.prototype.serializeMark = function serializeMark(mark, inline, options) {
  if (options === void 0) options = {};
  var toDOM = this.marks[mark.type.name];
  return toDOM && DOMSerializer.renderSpec(doc(options), toDOM(mark, inline));
}; // :: (dom.Document, DOMOutputSpec) → {dom: dom.Node, contentDOM: ?dom.Node}
// Render an [output spec](#model.DOMOutputSpec) to a DOM node. If
// the spec has a hole (zero) in it, `contentDOM` will point at the
// node with the hole.


DOMSerializer.renderSpec = function renderSpec(doc, structure, xmlNS) {
  if (xmlNS === void 0) xmlNS = null;

  if (typeof structure == "string") {
    return {
      dom: doc.createTextNode(structure)
    };
  }

  if (structure.nodeType != null) {
    return {
      dom: structure
    };
  }

  var tagName = structure[0],
      space = tagName.indexOf(" ");

  if (space > 0) {
    xmlNS = tagName.slice(0, space);
    tagName = tagName.slice(space + 1);
  }

  var contentDOM = null,
      dom = xmlNS ? doc.createElementNS(xmlNS, tagName) : doc.createElement(tagName);
  var attrs = structure[1],
      start = 1;

  if (attrs && typeof attrs == "object" && attrs.nodeType == null && !Array.isArray(attrs)) {
    start = 2;

    for (var name in attrs) {
      if (attrs[name] != null) {
        var space$1 = name.indexOf(" ");

        if (space$1 > 0) {
          dom.setAttributeNS(name.slice(0, space$1), name.slice(space$1 + 1), attrs[name]);
        } else {
          dom.setAttribute(name, attrs[name]);
        }
      }
    }
  }

  for (var i = start; i < structure.length; i++) {
    var child = structure[i];

    if (child === 0) {
      if (i < structure.length - 1 || i > start) {
        throw new RangeError("Content hole must be the only child of its parent node");
      }

      return {
        dom: dom,
        contentDOM: dom
      };
    } else {
      var ref = DOMSerializer.renderSpec(doc, child, xmlNS);
      var inner = ref.dom;
      var innerContent = ref.contentDOM;
      dom.appendChild(inner);

      if (innerContent) {
        if (contentDOM) {
          throw new RangeError("Multiple content holes");
        }

        contentDOM = innerContent;
      }
    }
  }

  return {
    dom: dom,
    contentDOM: contentDOM
  };
}; // :: (Schema) → DOMSerializer
// Build a serializer using the [`toDOM`](#model.NodeSpec.toDOM)
// properties in a schema's node and mark specs.


DOMSerializer.fromSchema = function fromSchema(schema) {
  return schema.cached.domSerializer || (schema.cached.domSerializer = new DOMSerializer(this.nodesFromSchema(schema), this.marksFromSchema(schema)));
}; // : (Schema) → Object<(node: Node) → DOMOutputSpec>
// Gather the serializers in a schema's node specs into an object.
// This can be useful as a base to build a custom serializer from.


DOMSerializer.nodesFromSchema = function nodesFromSchema(schema) {
  var result = gatherToDOM(schema.nodes);

  if (!result.text) {
    result.text = function (node) {
      return node.text;
    };
  }

  return result;
}; // : (Schema) → Object<(mark: Mark) → DOMOutputSpec>
// Gather the serializers in a schema's mark specs into an object.


DOMSerializer.marksFromSchema = function marksFromSchema(schema) {
  return gatherToDOM(schema.marks);
};

function gatherToDOM(obj) {
  var result = {};

  for (var name in obj) {
    var toDOM = obj[name].spec.toDOM;

    if (toDOM) {
      result[name] = toDOM;
    }
  }

  return result;
}

function doc(options) {
  // declare global: window
  return options.document || window.document;
}
},{"orderedmap":"../node_modules/orderedmap/index.es.js"}],"../node_modules/html/lib/html.js":[function(require,module,exports) {
/*

 Style HTML
---------------

  Written by Nochum Sossonko, (nsossonko@hotmail.com)

  Based on code initially developed by: Einar Lielmanis, <elfz@laacz.lv>
    http://jsbeautifier.org/


  You are free to use this in any way you want, in case you find this useful or working for you.

  Usage:
    style_html(html_source);

    style_html(html_source, options);

  The options are:
    indent_size (default 4)          — indentation size,
    indent_char (default space)      — character to indent with,
    max_char (default 70)            -  maximum amount of characters per line,
    brace_style (default "collapse") - "collapse" | "expand" | "end-expand"
            put braces on the same line as control statements (default), or put braces on own line (Allman / ANSI style), or just put end braces on own line.
    unformatted (defaults to inline tags) - list of tags, that shouldn't be reformatted
    indent_scripts (default normal)  - "keep"|"separate"|"normal"

    e.g.

    style_html(html_source, {
      'indent_size': 2,
      'indent_char': ' ',
      'max_char': 78,
      'brace_style': 'expand',
      'unformatted': ['a', 'sub', 'sup', 'b', 'i', 'u']
    });
*/

function style_html(html_source, options) {
//Wrapper function to invoke all the necessary constructors and deal with the output.

  var multi_parser,
      indent_size,
      indent_character,
      max_char,
      brace_style,
      unformatted;

  options = options || {};
  indent_size = options.indent_size || 4;
  indent_character = options.indent_char || ' ';
  brace_style = options.brace_style || 'collapse';
  max_char = options.max_char == 0 ? Infinity : options.max_char || 70;
  unformatted = options.unformatted || ['a', 'span', 'bdo', 'em', 'strong', 'dfn', 'code', 'samp', 'kbd', 'var', 'cite', 'abbr', 'acronym', 'q', 'sub', 'sup', 'tt', 'i', 'b', 'big', 'small', 'u', 's', 'strike', 'font', 'ins', 'del', 'pre', 'address', 'dt', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'];

  function Parser() {

    this.pos = 0; //Parser position
    this.token = '';
    this.current_mode = 'CONTENT'; //reflects the current Parser mode: TAG/CONTENT
    this.tags = { //An object to hold tags, their position, and their parent-tags, initiated with default values
      parent: 'parent1',
      parentcount: 1,
      parent1: ''
    };
    this.tag_type = '';
    this.token_text = this.last_token = this.last_text = this.token_type = '';

    this.Utils = { //Uilities made available to the various functions
      whitespace: "\n\r\t ".split(''),
      single_token: 'br,input,link,meta,!doctype,basefont,base,area,hr,wbr,param,img,isindex,?xml,embed,?php,?,?='.split(','), //all the single tags for HTML
      extra_liners: 'head,body,/html'.split(','), //for tags that need a line of whitespace before them
      in_array: function (what, arr) {
        for (var i=0; i<arr.length; i++) {
          if (what === arr[i]) {
            return true;
          }
        }
        return false;
      }
    }

    this.get_content = function () { //function to capture regular content between tags

      var input_char = '',
          content = [],
          space = false; //if a space is needed

      while (this.input.charAt(this.pos) !== '<') {
        if (this.pos >= this.input.length) {
          return content.length?content.join(''):['', 'TK_EOF'];
        }

        input_char = this.input.charAt(this.pos);
        this.pos++;
        this.line_char_count++;

        if (this.Utils.in_array(input_char, this.Utils.whitespace)) {
          if (content.length) {
            space = true;
          }
          this.line_char_count--;
          continue; //don't want to insert unnecessary space
        }
        else if (space) {
          if (this.line_char_count >= this.max_char) { //insert a line when the max_char is reached
            content.push('\n');
            for (var i=0; i<this.indent_level; i++) {
              content.push(this.indent_string);
            }
            this.line_char_count = 0;
          }
          else{
            content.push(' ');
            this.line_char_count++;
          }
          space = false;
        }
        content.push(input_char); //letter at-a-time (or string) inserted to an array
      }
      return content.length?content.join(''):'';
    }

    this.get_contents_to = function (name) { //get the full content of a script or style to pass to js_beautify
      if (this.pos == this.input.length) {
        return ['', 'TK_EOF'];
      }
      var input_char = '';
      var content = '';
      var reg_match = new RegExp('\<\/' + name + '\\s*\>', 'igm');
      reg_match.lastIndex = this.pos;
      var reg_array = reg_match.exec(this.input);
      var end_script = reg_array?reg_array.index:this.input.length; //absolute end of script
      if(this.pos < end_script) { //get everything in between the script tags
        content = this.input.substring(this.pos, end_script);
        this.pos = end_script;
      }
      return content;
    }

    this.record_tag = function (tag){ //function to record a tag and its parent in this.tags Object
      if (this.tags[tag + 'count']) { //check for the existence of this tag type
        this.tags[tag + 'count']++;
        this.tags[tag + this.tags[tag + 'count']] = this.indent_level; //and record the present indent level
      }
      else { //otherwise initialize this tag type
        this.tags[tag + 'count'] = 1;
        this.tags[tag + this.tags[tag + 'count']] = this.indent_level; //and record the present indent level
      }
      this.tags[tag + this.tags[tag + 'count'] + 'parent'] = this.tags.parent; //set the parent (i.e. in the case of a div this.tags.div1parent)
      this.tags.parent = tag + this.tags[tag + 'count']; //and make this the current parent (i.e. in the case of a div 'div1')
    }

    this.retrieve_tag = function (tag) { //function to retrieve the opening tag to the corresponding closer
      if (this.tags[tag + 'count']) { //if the openener is not in the Object we ignore it
        var temp_parent = this.tags.parent; //check to see if it's a closable tag.
        while (temp_parent) { //till we reach '' (the initial value);
          if (tag + this.tags[tag + 'count'] === temp_parent) { //if this is it use it
            break;
          }
          temp_parent = this.tags[temp_parent + 'parent']; //otherwise keep on climbing up the DOM Tree
        }
        if (temp_parent) { //if we caught something
          this.indent_level = this.tags[tag + this.tags[tag + 'count']]; //set the indent_level accordingly
          this.tags.parent = this.tags[temp_parent + 'parent']; //and set the current parent
        }
        delete this.tags[tag + this.tags[tag + 'count'] + 'parent']; //delete the closed tags parent reference...
        delete this.tags[tag + this.tags[tag + 'count']]; //...and the tag itself
        if (this.tags[tag + 'count'] == 1) {
          delete this.tags[tag + 'count'];
        }
        else {
          this.tags[tag + 'count']--;
        }
      }
    }

    this.get_tag = function () { //function to get a full tag and parse its type
      var input_char = '',
          content = [],
          space = false,
          tag_start, tag_end;

      do {
        if (this.pos >= this.input.length) {
          return content.length?content.join(''):['', 'TK_EOF'];
        }

        input_char = this.input.charAt(this.pos);
        this.pos++;
        this.line_char_count++;

        if (this.Utils.in_array(input_char, this.Utils.whitespace)) { //don't want to insert unnecessary space
          space = true;
          this.line_char_count--;
          continue;
        }

        if (input_char === "'" || input_char === '"') {
          if (!content[1] || content[1] !== '!') { //if we're in a comment strings don't get treated specially
            input_char += this.get_unformatted(input_char);
            space = true;
          }
        }

        if (input_char === '=') { //no space before =
          space = false;
        }

        if (content.length && content[content.length-1] !== '=' && input_char !== '>'
            && space) { //no space after = or before >
          if (this.line_char_count >= this.max_char) {
            this.print_newline(false, content);
            this.line_char_count = 0;
          }
          else {
            content.push(' ');
            this.line_char_count++;
          }
          space = false;
        }
        if (input_char === '<') {
            tag_start = this.pos - 1;
        }
        content.push(input_char); //inserts character at-a-time (or string)
      } while (input_char !== '>');

      var tag_complete = content.join('');
      var tag_index;
      if (tag_complete.indexOf(' ') != -1) { //if there's whitespace, thats where the tag name ends
        tag_index = tag_complete.indexOf(' ');
      }
      else { //otherwise go with the tag ending
        tag_index = tag_complete.indexOf('>');
      }
      var tag_check = tag_complete.substring(1, tag_index).toLowerCase();
      if (tag_complete.charAt(tag_complete.length-2) === '/' ||
          this.Utils.in_array(tag_check, this.Utils.single_token)) { //if this tag name is a single tag type (either in the list or has a closing /)
        this.tag_type = 'SINGLE';
      }
      else if (tag_check === 'script') { //for later script handling
        this.record_tag(tag_check);
        this.tag_type = 'SCRIPT';
      }
      else if (tag_check === 'style') { //for future style handling (for now it justs uses get_content)
        this.record_tag(tag_check);
        this.tag_type = 'STYLE';
      }
      else if (this.Utils.in_array(tag_check, unformatted)) { // do not reformat the "unformatted" tags
        var comment = this.get_unformatted('</'+tag_check+'>', tag_complete); //...delegate to get_unformatted function
        content.push(comment);
        // Preserve collapsed whitespace either before or after this tag.
        if (tag_start > 0 && this.Utils.in_array(this.input.charAt(tag_start - 1), this.Utils.whitespace)){
            content.splice(0, 0, this.input.charAt(tag_start - 1));
        }
        tag_end = this.pos - 1;
        if (this.Utils.in_array(this.input.charAt(tag_end + 1), this.Utils.whitespace)){
            content.push(this.input.charAt(tag_end + 1));
        }
        this.tag_type = 'SINGLE';
      }
      else if (tag_check.charAt(0) === '!') { //peek for <!-- comment
        if (tag_check.indexOf('[if') != -1) { //peek for <!--[if conditional comment
          if (tag_complete.indexOf('!IE') != -1) { //this type needs a closing --> so...
            var comment = this.get_unformatted('-->', tag_complete); //...delegate to get_unformatted
            content.push(comment);
          }
          this.tag_type = 'START';
        }
        else if (tag_check.indexOf('[endif') != -1) {//peek for <!--[endif end conditional comment
          this.tag_type = 'END';
          this.unindent();
        }
        else if (tag_check.indexOf('[cdata[') != -1) { //if it's a <[cdata[ comment...
          var comment = this.get_unformatted(']]>', tag_complete); //...delegate to get_unformatted function
          content.push(comment);
          this.tag_type = 'SINGLE'; //<![CDATA[ comments are treated like single tags
        }
        else {
          var comment = this.get_unformatted('-->', tag_complete);
          content.push(comment);
          this.tag_type = 'SINGLE';
        }
      }
      else {
        if (tag_check.charAt(0) === '/') { //this tag is a double tag so check for tag-ending
          this.retrieve_tag(tag_check.substring(1)); //remove it and all ancestors
          this.tag_type = 'END';
        }
        else { //otherwise it's a start-tag
          this.record_tag(tag_check); //push it on the tag stack
          this.tag_type = 'START';
        }
        if (this.Utils.in_array(tag_check, this.Utils.extra_liners)) { //check if this double needs an extra line
          this.print_newline(true, this.output);
        }
      }
      return content.join(''); //returns fully formatted tag
    }

    this.get_unformatted = function (delimiter, orig_tag) { //function to return unformatted content in its entirety

      if (orig_tag && orig_tag.toLowerCase().indexOf(delimiter) != -1) {
        return '';
      }
      var input_char = '';
      var content = '';
      var space = true;
      do {

        if (this.pos >= this.input.length) {
          return content;
        }

        input_char = this.input.charAt(this.pos);
        this.pos++

        if (this.Utils.in_array(input_char, this.Utils.whitespace)) {
          if (!space) {
            this.line_char_count--;
            continue;
          }
          if (input_char === '\n' || input_char === '\r') {
            content += '\n';
            /*  Don't change tab indention for unformatted blocks.  If using code for html editing, this will greatly affect <pre> tags if they are specified in the 'unformatted array'
            for (var i=0; i<this.indent_level; i++) {
              content += this.indent_string;
            }
            space = false; //...and make sure other indentation is erased
            */
            this.line_char_count = 0;
            continue;
          }
        }
        content += input_char;
        this.line_char_count++;
        space = true;


      } while (content.toLowerCase().indexOf(delimiter) == -1);
      return content;
    }

    this.get_token = function () { //initial handler for token-retrieval
      var token;

      if (this.last_token === 'TK_TAG_SCRIPT' || this.last_token === 'TK_TAG_STYLE') { //check if we need to format javascript
       var type = this.last_token.substr(7)
       token = this.get_contents_to(type);
        if (typeof token !== 'string') {
          return token;
        }
        return [token, 'TK_' + type];
      }
      if (this.current_mode === 'CONTENT') {
        token = this.get_content();
        if (typeof token !== 'string') {
          return token;
        }
        else {
          return [token, 'TK_CONTENT'];
        }
      }

      if (this.current_mode === 'TAG') {
        token = this.get_tag();
        if (typeof token !== 'string') {
          return token;
        }
        else {
          var tag_name_type = 'TK_TAG_' + this.tag_type;
          return [token, tag_name_type];
        }
      }
    }

    this.get_full_indent = function (level) {
      level = this.indent_level + level || 0;
      if (level < 1)
        return '';

      return Array(level + 1).join(this.indent_string);
    }


    this.printer = function (js_source, indent_character, indent_size, max_char, brace_style) { //handles input/output and some other printing functions

      this.input = js_source || ''; //gets the input for the Parser
      this.output = [];
      this.indent_character = indent_character;
      this.indent_string = '';
      this.indent_size = indent_size;
      this.brace_style = brace_style;
      this.indent_level = 0;
      this.max_char = max_char;
      this.line_char_count = 0; //count to see if max_char was exceeded

      for (var i=0; i<this.indent_size; i++) {
        this.indent_string += this.indent_character;
      }

      this.print_newline = function (ignore, arr) {
        this.line_char_count = 0;
        if (!arr || !arr.length) {
          return;
        }
        if (!ignore) { //we might want the extra line
          while (this.Utils.in_array(arr[arr.length-1], this.Utils.whitespace)) {
            arr.pop();
          }
        }
        arr.push('\n');
        for (var i=0; i<this.indent_level; i++) {
          arr.push(this.indent_string);
        }
      }

      this.print_token = function (text) {
        this.output.push(text);
      }

      this.indent = function () {
        this.indent_level++;
      }

      this.unindent = function () {
        if (this.indent_level > 0) {
          this.indent_level--;
        }
      }
    }
    return this;
  }

  /*_____________________--------------------_____________________*/

  multi_parser = new Parser(); //wrapping functions Parser
  multi_parser.printer(html_source, indent_character, indent_size, max_char, brace_style); //initialize starting values

  while (true) {
      var t = multi_parser.get_token();
      multi_parser.token_text = t[0];
      multi_parser.token_type = t[1];

    if (multi_parser.token_type === 'TK_EOF') {
      break;
    }

    switch (multi_parser.token_type) {
      case 'TK_TAG_START':
        multi_parser.print_newline(false, multi_parser.output);
        multi_parser.print_token(multi_parser.token_text);
        multi_parser.indent();
        multi_parser.current_mode = 'CONTENT';
        break;
      case 'TK_TAG_STYLE':
      case 'TK_TAG_SCRIPT':
        multi_parser.print_newline(false, multi_parser.output);
        multi_parser.print_token(multi_parser.token_text);
        multi_parser.current_mode = 'CONTENT';
        break;
      case 'TK_TAG_END':
        //Print new line only if the tag has no content and has child
        if (multi_parser.last_token === 'TK_CONTENT' && multi_parser.last_text === '') {
            var tag_name = multi_parser.token_text.match(/\w+/)[0];
            var tag_extracted_from_last_output = multi_parser.output[multi_parser.output.length -1].match(/<\s*(\w+)/);
            if (tag_extracted_from_last_output === null || tag_extracted_from_last_output[1] !== tag_name)
                multi_parser.print_newline(true, multi_parser.output);
        }
        multi_parser.print_token(multi_parser.token_text);
        multi_parser.current_mode = 'CONTENT';
        break;
      case 'TK_TAG_SINGLE':
        // Don't add a newline before elements that should remain unformatted.
        var tag_check = multi_parser.token_text.match(/^\s*<([a-z]+)/i);
        if (!tag_check || !multi_parser.Utils.in_array(tag_check[1], unformatted)){
            multi_parser.print_newline(false, multi_parser.output);
        }
        multi_parser.print_token(multi_parser.token_text);
        multi_parser.current_mode = 'CONTENT';
        break;
      case 'TK_CONTENT':
        if (multi_parser.token_text !== '') {
          multi_parser.print_token(multi_parser.token_text);
        }
        multi_parser.current_mode = 'TAG';
        break;
      case 'TK_STYLE':
      case 'TK_SCRIPT':
        if (multi_parser.token_text !== '') {
          multi_parser.output.push('\n');
          var text = multi_parser.token_text;
          if (multi_parser.token_type == 'TK_SCRIPT') {
            var _beautifier = typeof js_beautify == 'function' && js_beautify;
          } else if (multi_parser.token_type == 'TK_STYLE') {
            var _beautifier = typeof css_beautify == 'function' && css_beautify;
          }

          if (options.indent_scripts == "keep") {
            var script_indent_level = 0;
          } else if (options.indent_scripts == "separate") {
            var script_indent_level = -multi_parser.indent_level;
          } else {
            var script_indent_level = 1;
          }

          var indentation = multi_parser.get_full_indent(script_indent_level);
          if (_beautifier) {
            // call the Beautifier if avaliable
            text = _beautifier(text.replace(/^\s*/, indentation), options);
          } else {
            // simply indent the string otherwise
            var white = text.match(/^\s*/)[0];
            var _level = white.match(/[^\n\r]*$/)[0].split(multi_parser.indent_string).length - 1;
            var reindent = multi_parser.get_full_indent(script_indent_level -_level);
            text = text.replace(/^\s*/, indentation)
                   .replace(/\r\n|\r|\n/g, '\n' + reindent)
                   .replace(/\s*$/, '');
          }
          if (text) {
            multi_parser.print_token(text);
            multi_parser.print_newline(true, multi_parser.output);
          }
        }
        multi_parser.current_mode = 'TAG';
        break;
    }
    multi_parser.last_token = multi_parser.token_type;
    multi_parser.last_text = multi_parser.token_text;
  }
  return multi_parser.output.join('');
}

module.exports = {
  prettyPrint: style_html
};
},{}],"../node_modules/nanoid/index.browser.js":[function(require,module,exports) {
// This file replaces `index.js` in bundlers like webpack or Rollup,
// according to `browser` config in `package.json`.
if ("development" !== 'production') {
  // All bundlers will remove this block in production bundle
  if (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') {
    throw new Error('React Native does not have a built-in secure random generator. ' + 'If you don’t need unpredictable IDs, you can use `nanoid/non-secure`. ' + 'For secure ID install `expo-random` locally and use `nanoid/async`.');
  }

  if (typeof self === 'undefined' || !self.crypto && !self.msCrypto) {
    throw new Error('Your browser does not have secure random generator. ' + 'If you don’t need unpredictable IDs, you can use nanoid/non-secure.');
  }
}

var crypto = self.crypto || self.msCrypto; // This alphabet uses a-z A-Z 0-9 _- symbols.
// Symbols are generated for smaller size.
// -_zyxwvutsrqponmlkjihgfedcba9876543210ZYXWVUTSRQPONMLKJIHGFEDCBA

var url = '-_'; // Loop from 36 to 0 (from z to a and 9 to 0 in Base36).

var i = 36;

while (i--) {
  // 36 is radix. Number.prototype.toString(36) returns number
  // in Base36 representation. Base36 is like hex, but it uses 0–9 and a-z.
  url += i.toString(36);
} // Loop from 36 to 10 (from Z to A in Base36).


i = 36;

while (i-- - 10) {
  url += i.toString(36).toUpperCase();
}

module.exports = function (size) {
  var id = '';
  var bytes = crypto.getRandomValues(new Uint8Array(size || 21));
  i = size || 21; // Compact alternative for `for (var i = 0; i < size; i++)`

  while (i--) {
    // We can’t use bytes bigger than the alphabet. 63 is 00111111 bitmask.
    // This mask reduces random byte 0-255 to 0-63 values.
    // There is no need in `|| ''` and `* 1.6` hacks in here,
    // because bitmask trim bytes exact to alphabet size.
    id += url[bytes[i] & 63];
  }

  return id;
};
},{}],"../src/utils/subscribe-on-updates.js":[function(require,module,exports) {
"use strict";

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

function subscribeOnUpdates(editorView, callback) {
  var dispatch = (editorView._props.dispatchTransaction || editorView.dispatch).bind(editorView);

  var handler = function handler(tr) {
    var oldState = editorView.state;
    dispatch(tr);
    callback(tr, oldState, editorView.state);
  };

  if (editorView._props.dispatchTransaction) {
    editorView._props.dispatchTransaction = handler;
  } else {
    editorView.dispatch = handler;
  }
}
},{}],"../src/utils/find-node.js":[function(require,module,exports) {
"use strict";

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

function findNode(fullPath, currentNode, nodeToFind) {
  if (nodeToFind === currentNode) {
    return fullPath;
  }

  if (!currentNode.content || !currentNode.content.content) return null;
  var res = currentNode.content.content.map(function (currentNode, i) {
    return findNode([].concat(fullPath, "content", i), currentNode, nodeToFind);
  }).filter(function (res) {
    return Array.isArray(res) && res.length;
  })[0];
  return res;
}

function findNodeIn(doc, node) {
  var path = findNode([], doc, node);

  if (path) {
    return path.reduce(function (newPath, item) {
      // [0, content, content, 0] => [0, content, 0]
      // Because JSON representation a bit different from actual DOC.
      if (item === "content" && newPath[newPath.length - 1] === "content") {
        return newPath;
      }

      newPath.push(item);
      return newPath;
    }, []);
  }
}

function findNodeJSON(fullPath, currentNode, nodeToFind) {
  if (nodeToFind === currentNode) {
    return fullPath;
  }

  if (!currentNode.content) return null;

  if (currentNode.content === nodeToFind) {
    return fullPath.concat("content");
  }

  var res = currentNode.content.map(function (currentNode, i) {
    return findNodeJSON([].concat(fullPath, "content", i), currentNode, nodeToFind);
  }).filter(function (res) {
    return Array.isArray(res) && res.length;
  })[0];
  return res;
}

function findNodeInJSON(doc, node) {
  var path = findNodeJSON([], doc, node);

  if (path) {
    return path.reduce(function (newPath, item) {
      newPath.push(item);

      if (item === "content") {
        newPath.push("content");
      }

      return newPath;
    }, []);
  }
}
},{}],"../node_modules/prosemirror-transform/dist/index.es.js":[function(require,module,exports) {
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.TransformError = TransformError;
exports.canJoin = canJoin;
exports.canSplit = canSplit;
exports.dropPoint = dropPoint;
exports.findWrapping = findWrapping;
exports.insertPoint = insertPoint;
exports.joinPoint = joinPoint;
exports.liftTarget = liftTarget;
exports.replaceStep = replaceStep;
exports.Transform = exports.StepResult = exports.StepMap = exports.Step = exports.ReplaceStep = exports.ReplaceAroundStep = exports.RemoveMarkStep = exports.Mapping = exports.MapResult = exports.AddMarkStep = void 0;

var _prosemirrorModel = require("prosemirror-model");

// Mappable:: interface
// There are several things that positions can be mapped through.
// Such objects conform to this interface.
//
//   map:: (pos: number, assoc: ?number) → number
//   Map a position through this object. When given, `assoc` (should
//   be -1 or 1, defaults to 1) determines with which side the
//   position is associated, which determines in which direction to
//   move when a chunk of content is inserted at the mapped position.
//
//   mapResult:: (pos: number, assoc: ?number) → MapResult
//   Map a position, and return an object containing additional
//   information about the mapping. The result's `deleted` field tells
//   you whether the position was deleted (completely enclosed in a
//   replaced range) during the mapping. When content on only one side
//   is deleted, the position itself is only considered deleted when
//   `assoc` points in the direction of the deleted content.
// Recovery values encode a range index and an offset. They are
// represented as numbers, because tons of them will be created when
// mapping, for example, a large number of decorations. The number's
// lower 16 bits provide the index, the remaining bits the offset.
//
// Note: We intentionally don't use bit shift operators to en- and
// decode these, since those clip to 32 bits, which we might in rare
// cases want to overflow. A 64-bit float can represent 48-bit
// integers precisely.
var lower16 = 0xffff;
var factor16 = Math.pow(2, 16);

function makeRecover(index, offset) {
  return index + offset * factor16;
}

function recoverIndex(value) {
  return value & lower16;
}

function recoverOffset(value) {
  return (value - (value & lower16)) / factor16;
} // ::- An object representing a mapped position with extra
// information.


var MapResult = function MapResult(pos, deleted, recover) {
  if (deleted === void 0) deleted = false;
  if (recover === void 0) recover = null; // :: number The mapped version of the position.

  this.pos = pos; // :: bool Tells you whether the position was deleted, that is,
  // whether the step removed its surroundings from the document.

  this.deleted = deleted;
  this.recover = recover;
}; // :: class extends Mappable
// A map describing the deletions and insertions made by a step, which
// can be used to find the correspondence between positions in the
// pre-step version of a document and the same position in the
// post-step version.


exports.MapResult = MapResult;

var StepMap = function StepMap(ranges, inverted) {
  if (inverted === void 0) inverted = false;
  this.ranges = ranges;
  this.inverted = inverted;
};

exports.StepMap = StepMap;

StepMap.prototype.recover = function recover(value) {
  var diff = 0,
      index = recoverIndex(value);

  if (!this.inverted) {
    for (var i = 0; i < index; i++) {
      diff += this.ranges[i * 3 + 2] - this.ranges[i * 3 + 1];
    }
  }

  return this.ranges[index * 3] + diff + recoverOffset(value);
}; // : (number, ?number) → MapResult


StepMap.prototype.mapResult = function mapResult(pos, assoc) {
  if (assoc === void 0) assoc = 1;
  return this._map(pos, assoc, false);
}; // : (number, ?number) → number


StepMap.prototype.map = function map(pos, assoc) {
  if (assoc === void 0) assoc = 1;
  return this._map(pos, assoc, true);
};

StepMap.prototype._map = function _map(pos, assoc, simple) {
  var diff = 0,
      oldIndex = this.inverted ? 2 : 1,
      newIndex = this.inverted ? 1 : 2;

  for (var i = 0; i < this.ranges.length; i += 3) {
    var start = this.ranges[i] - (this.inverted ? diff : 0);

    if (start > pos) {
      break;
    }

    var oldSize = this.ranges[i + oldIndex],
        newSize = this.ranges[i + newIndex],
        end = start + oldSize;

    if (pos <= end) {
      var side = !oldSize ? assoc : pos == start ? -1 : pos == end ? 1 : assoc;
      var result = start + diff + (side < 0 ? 0 : newSize);

      if (simple) {
        return result;
      }

      var recover = makeRecover(i / 3, pos - start);
      return new MapResult(result, assoc < 0 ? pos != start : pos != end, recover);
    }

    diff += newSize - oldSize;
  }

  return simple ? pos + diff : new MapResult(pos + diff);
};

StepMap.prototype.touches = function touches(pos, recover) {
  var diff = 0,
      index = recoverIndex(recover);
  var oldIndex = this.inverted ? 2 : 1,
      newIndex = this.inverted ? 1 : 2;

  for (var i = 0; i < this.ranges.length; i += 3) {
    var start = this.ranges[i] - (this.inverted ? diff : 0);

    if (start > pos) {
      break;
    }

    var oldSize = this.ranges[i + oldIndex],
        end = start + oldSize;

    if (pos <= end && i == index * 3) {
      return true;
    }

    diff += this.ranges[i + newIndex] - oldSize;
  }

  return false;
}; // :: ((oldStart: number, oldEnd: number, newStart: number, newEnd: number))
// Calls the given function on each of the changed ranges included in
// this map.


StepMap.prototype.forEach = function forEach(f) {
  var oldIndex = this.inverted ? 2 : 1,
      newIndex = this.inverted ? 1 : 2;

  for (var i = 0, diff = 0; i < this.ranges.length; i += 3) {
    var start = this.ranges[i],
        oldStart = start - (this.inverted ? diff : 0),
        newStart = start + (this.inverted ? 0 : diff);
    var oldSize = this.ranges[i + oldIndex],
        newSize = this.ranges[i + newIndex];
    f(oldStart, oldStart + oldSize, newStart, newStart + newSize);
    diff += newSize - oldSize;
  }
}; // :: () → StepMap
// Create an inverted version of this map. The result can be used to
// map positions in the post-step document to the pre-step document.


StepMap.prototype.invert = function invert() {
  return new StepMap(this.ranges, !this.inverted);
};

StepMap.prototype.toString = function toString() {
  return (this.inverted ? "-" : "") + JSON.stringify(this.ranges);
}; // :: (n: number) → StepMap
// Create a map that moves all positions by offset `n` (which may be
// negative). This can be useful when applying steps meant for a
// sub-document to a larger document, or vice-versa.


StepMap.offset = function offset(n) {
  return n == 0 ? StepMap.empty : new StepMap(n < 0 ? [0, -n, 0] : [0, 0, n]);
};

StepMap.empty = new StepMap([]); // :: class extends Mappable
// A mapping represents a pipeline of zero or more [step
// maps](#transform.StepMap). It has special provisions for losslessly
// handling mapping positions through a series of steps in which some
// steps are inverted versions of earlier steps. (This comes up when
// ‘[rebasing](/docs/guide/#transform.rebasing)’ steps for
// collaboration or history management.)

var Mapping = function Mapping(maps, mirror, from, to) {
  // :: [StepMap]
  // The step maps in this mapping.
  this.maps = maps || []; // :: number
  // The starting position in the `maps` array, used when `map` or
  // `mapResult` is called.

  this.from = from || 0; // :: number
  // The end position in the `maps` array.

  this.to = to == null ? this.maps.length : to;
  this.mirror = mirror;
}; // :: (?number, ?number) → Mapping
// Create a mapping that maps only through a part of this one.


exports.Mapping = Mapping;

Mapping.prototype.slice = function slice(from, to) {
  if (from === void 0) from = 0;
  if (to === void 0) to = this.maps.length;
  return new Mapping(this.maps, this.mirror, from, to);
};

Mapping.prototype.copy = function copy() {
  return new Mapping(this.maps.slice(), this.mirror && this.mirror.slice(), this.from, this.to);
}; // :: (StepMap, ?number)
// Add a step map to the end of this mapping. If `mirrors` is
// given, it should be the index of the step map that is the mirror
// image of this one.


Mapping.prototype.appendMap = function appendMap(map, mirrors) {
  this.to = this.maps.push(map);

  if (mirrors != null) {
    this.setMirror(this.maps.length - 1, mirrors);
  }
}; // :: (Mapping)
// Add all the step maps in a given mapping to this one (preserving
// mirroring information).


Mapping.prototype.appendMapping = function appendMapping(mapping) {
  for (var i = 0, startSize = this.maps.length; i < mapping.maps.length; i++) {
    var mirr = mapping.getMirror(i);
    this.appendMap(mapping.maps[i], mirr != null && mirr < i ? startSize + mirr : null);
  }
}; // :: (number) → ?number
// Finds the offset of the step map that mirrors the map at the
// given offset, in this mapping (as per the second argument to
// `appendMap`).


Mapping.prototype.getMirror = function getMirror(n) {
  if (this.mirror) {
    for (var i = 0; i < this.mirror.length; i++) {
      if (this.mirror[i] == n) {
        return this.mirror[i + (i % 2 ? -1 : 1)];
      }
    }
  }
};

Mapping.prototype.setMirror = function setMirror(n, m) {
  if (!this.mirror) {
    this.mirror = [];
  }

  this.mirror.push(n, m);
}; // :: (Mapping)
// Append the inverse of the given mapping to this one.


Mapping.prototype.appendMappingInverted = function appendMappingInverted(mapping) {
  for (var i = mapping.maps.length - 1, totalSize = this.maps.length + mapping.maps.length; i >= 0; i--) {
    var mirr = mapping.getMirror(i);
    this.appendMap(mapping.maps[i].invert(), mirr != null && mirr > i ? totalSize - mirr - 1 : null);
  }
}; // :: () → Mapping
// Create an inverted version of this mapping.


Mapping.prototype.invert = function invert() {
  var inverse = new Mapping();
  inverse.appendMappingInverted(this);
  return inverse;
}; // : (number, ?number) → number
// Map a position through this mapping.


Mapping.prototype.map = function map(pos, assoc) {
  if (assoc === void 0) assoc = 1;

  if (this.mirror) {
    return this._map(pos, assoc, true);
  }

  for (var i = this.from; i < this.to; i++) {
    pos = this.maps[i].map(pos, assoc);
  }

  return pos;
}; // : (number, ?number) → MapResult
// Map a position through this mapping, returning a mapping
// result.


Mapping.prototype.mapResult = function mapResult(pos, assoc) {
  if (assoc === void 0) assoc = 1;
  return this._map(pos, assoc, false);
};

Mapping.prototype._map = function _map(pos, assoc, simple) {
  var deleted = false,
      recoverables = null;

  for (var i = this.from; i < this.to; i++) {
    var map = this.maps[i],
        rec = recoverables && recoverables[i];

    if (rec != null && map.touches(pos, rec)) {
      pos = map.recover(rec);
      continue;
    }

    var result = map.mapResult(pos, assoc);

    if (result.recover != null) {
      var corr = this.getMirror(i);

      if (corr != null && corr > i && corr < this.to) {
        if (result.deleted) {
          i = corr;
          pos = this.maps[corr].recover(result.recover);
          continue;
        } else {
          (recoverables || (recoverables = Object.create(null)))[corr] = result.recover;
        }
      }
    }

    if (result.deleted) {
      deleted = true;
    }

    pos = result.pos;
  }

  return simple ? pos : new MapResult(pos, deleted);
};

function TransformError(message) {
  var err = Error.call(this, message);
  err.__proto__ = TransformError.prototype;
  return err;
}

TransformError.prototype = Object.create(Error.prototype);
TransformError.prototype.constructor = TransformError;
TransformError.prototype.name = "TransformError"; // ::- Abstraction to build up and track an array of
// [steps](#transform.Step) representing a document transformation.
//
// Most transforming methods return the `Transform` object itself, so
// that they can be chained.

var Transform = function Transform(doc) {
  // :: Node
  // The current document (the result of applying the steps in the
  // transform).
  this.doc = doc; // :: [Step]
  // The steps in this transform.

  this.steps = []; // :: [Node]
  // The documents before each of the steps.

  this.docs = []; // :: Mapping
  // A mapping with the maps for each of the steps in this transform.

  this.mapping = new Mapping();
};

exports.Transform = Transform;
var prototypeAccessors = {
  before: {
    configurable: true
  },
  docChanged: {
    configurable: true
  }
}; // :: Node The starting document.

prototypeAccessors.before.get = function () {
  return this.docs.length ? this.docs[0] : this.doc;
}; // :: (step: Step) → this
// Apply a new step in this transform, saving the result. Throws an
// error when the step fails.


Transform.prototype.step = function step(object) {
  var result = this.maybeStep(object);

  if (result.failed) {
    throw new TransformError(result.failed);
  }

  return this;
}; // :: (Step) → StepResult
// Try to apply a step in this transformation, ignoring it if it
// fails. Returns the step result.


Transform.prototype.maybeStep = function maybeStep(step) {
  var result = step.apply(this.doc);

  if (!result.failed) {
    this.addStep(step, result.doc);
  }

  return result;
}; // :: bool
// True when the document has been changed (when there are any
// steps).


prototypeAccessors.docChanged.get = function () {
  return this.steps.length > 0;
};

Transform.prototype.addStep = function addStep(step, doc) {
  this.docs.push(this.doc);
  this.steps.push(step);
  this.mapping.appendMap(step.getMap());
  this.doc = doc;
};

Object.defineProperties(Transform.prototype, prototypeAccessors);

function mustOverride() {
  throw new Error("Override me");
}

var stepsByID = Object.create(null); // ::- A step object represents an atomic change. It generally applies
// only to the document it was created for, since the positions
// stored in it will only make sense for that document.
//
// New steps are defined by creating classes that extend `Step`,
// overriding the `apply`, `invert`, `map`, `getMap` and `fromJSON`
// methods, and registering your class with a unique
// JSON-serialization identifier using
// [`Step.jsonID`](#transform.Step^jsonID).

var Step = function Step() {};

exports.Step = Step;

Step.prototype.apply = function apply(_doc) {
  return mustOverride();
}; // :: () → StepMap
// Get the step map that represents the changes made by this step,
// and which can be used to transform between positions in the old
// and the new document.


Step.prototype.getMap = function getMap() {
  return StepMap.empty;
}; // :: (doc: Node) → Step
// Create an inverted version of this step. Needs the document as it
// was before the step as argument.


Step.prototype.invert = function invert(_doc) {
  return mustOverride();
}; // :: (mapping: Mappable) → ?Step
// Map this step through a mappable thing, returning either a
// version of that step with its positions adjusted, or `null` if
// the step was entirely deleted by the mapping.


Step.prototype.map = function map(_mapping) {
  return mustOverride();
}; // :: (other: Step) → ?Step
// Try to merge this step with another one, to be applied directly
// after it. Returns the merged step when possible, null if the
// steps can't be merged.


Step.prototype.merge = function merge(_other) {
  return null;
}; // :: () → Object
// Create a JSON-serializeable representation of this step. When
// defining this for a custom subclass, make sure the result object
// includes the step type's [JSON id](#transform.Step^jsonID) under
// the `stepType` property.


Step.prototype.toJSON = function toJSON() {
  return mustOverride();
}; // :: (Schema, Object) → Step
// Deserialize a step from its JSON representation. Will call
// through to the step class' own implementation of this method.


Step.fromJSON = function fromJSON(schema, json) {
  if (!json || !json.stepType) {
    throw new RangeError("Invalid input for Step.fromJSON");
  }

  var type = stepsByID[json.stepType];

  if (!type) {
    throw new RangeError("No step type " + json.stepType + " defined");
  }

  return type.fromJSON(schema, json);
}; // :: (string, constructor<Step>)
// To be able to serialize steps to JSON, each step needs a string
// ID to attach to its JSON representation. Use this method to
// register an ID for your step classes. Try to pick something
// that's unlikely to clash with steps from other modules.


Step.jsonID = function jsonID(id, stepClass) {
  if (id in stepsByID) {
    throw new RangeError("Duplicate use of step JSON ID " + id);
  }

  stepsByID[id] = stepClass;
  stepClass.prototype.jsonID = id;
  return stepClass;
}; // ::- The result of [applying](#transform.Step.apply) a step. Contains either a
// new document or a failure value.


var StepResult = function StepResult(doc, failed) {
  // :: ?Node The transformed document.
  this.doc = doc; // :: ?string Text providing information about a failed step.

  this.failed = failed;
}; // :: (Node) → StepResult
// Create a successful step result.


exports.StepResult = StepResult;

StepResult.ok = function ok(doc) {
  return new StepResult(doc, null);
}; // :: (string) → StepResult
// Create a failed step result.


StepResult.fail = function fail(message) {
  return new StepResult(null, message);
}; // :: (Node, number, number, Slice) → StepResult
// Call [`Node.replace`](#model.Node.replace) with the given
// arguments. Create a successful result if it succeeds, and a
// failed one if it throws a `ReplaceError`.


StepResult.fromReplace = function fromReplace(doc, from, to, slice) {
  try {
    return StepResult.ok(doc.replace(from, to, slice));
  } catch (e) {
    if (e instanceof _prosemirrorModel.ReplaceError) {
      return StepResult.fail(e.message);
    }

    throw e;
  }
}; // ::- Replace a part of the document with a slice of new content.


var ReplaceStep = /*@__PURE__*/function (Step) {
  function ReplaceStep(from, to, slice, structure) {
    Step.call(this);
    this.from = from;
    this.to = to;
    this.slice = slice;
    this.structure = !!structure;
  }

  if (Step) ReplaceStep.__proto__ = Step;
  ReplaceStep.prototype = Object.create(Step && Step.prototype);
  ReplaceStep.prototype.constructor = ReplaceStep;

  ReplaceStep.prototype.apply = function apply(doc) {
    if (this.structure && contentBetween(doc, this.from, this.to)) {
      return StepResult.fail("Structure replace would overwrite content");
    }

    return StepResult.fromReplace(doc, this.from, this.to, this.slice);
  };

  ReplaceStep.prototype.getMap = function getMap() {
    return new StepMap([this.from, this.to - this.from, this.slice.size]);
  };

  ReplaceStep.prototype.invert = function invert(doc) {
    return new ReplaceStep(this.from, this.from + this.slice.size, doc.slice(this.from, this.to));
  };

  ReplaceStep.prototype.map = function map(mapping) {
    var from = mapping.mapResult(this.from, 1),
        to = mapping.mapResult(this.to, -1);

    if (from.deleted && to.deleted) {
      return null;
    }

    return new ReplaceStep(from.pos, Math.max(from.pos, to.pos), this.slice);
  };

  ReplaceStep.prototype.merge = function merge(other) {
    if (!(other instanceof ReplaceStep) || other.structure != this.structure) {
      return null;
    }

    if (this.from + this.slice.size == other.from && !this.slice.openEnd && !other.slice.openStart) {
      var slice = this.slice.size + other.slice.size == 0 ? _prosemirrorModel.Slice.empty : new _prosemirrorModel.Slice(this.slice.content.append(other.slice.content), this.slice.openStart, other.slice.openEnd);
      return new ReplaceStep(this.from, this.to + (other.to - other.from), slice, this.structure);
    } else if (other.to == this.from && !this.slice.openStart && !other.slice.openEnd) {
      var slice$1 = this.slice.size + other.slice.size == 0 ? _prosemirrorModel.Slice.empty : new _prosemirrorModel.Slice(other.slice.content.append(this.slice.content), other.slice.openStart, this.slice.openEnd);
      return new ReplaceStep(other.from, this.to, slice$1, this.structure);
    } else {
      return null;
    }
  };

  ReplaceStep.prototype.toJSON = function toJSON() {
    var json = {
      stepType: "replace",
      from: this.from,
      to: this.to
    };

    if (this.slice.size) {
      json.slice = this.slice.toJSON();
    }

    if (this.structure) {
      json.structure = true;
    }

    return json;
  };

  ReplaceStep.fromJSON = function fromJSON(schema, json) {
    if (typeof json.from != "number" || typeof json.to != "number") {
      throw new RangeError("Invalid input for ReplaceStep.fromJSON");
    }

    return new ReplaceStep(json.from, json.to, _prosemirrorModel.Slice.fromJSON(schema, json.slice), !!json.structure);
  };

  return ReplaceStep;
}(Step);

exports.ReplaceStep = ReplaceStep;
Step.jsonID("replace", ReplaceStep); // ::- Replace a part of the document with a slice of content, but
// preserve a range of the replaced content by moving it into the
// slice.

var ReplaceAroundStep = /*@__PURE__*/function (Step) {
  function ReplaceAroundStep(from, to, gapFrom, gapTo, slice, insert, structure) {
    Step.call(this);
    this.from = from;
    this.to = to;
    this.gapFrom = gapFrom;
    this.gapTo = gapTo;
    this.slice = slice;
    this.insert = insert;
    this.structure = !!structure;
  }

  if (Step) ReplaceAroundStep.__proto__ = Step;
  ReplaceAroundStep.prototype = Object.create(Step && Step.prototype);
  ReplaceAroundStep.prototype.constructor = ReplaceAroundStep;

  ReplaceAroundStep.prototype.apply = function apply(doc) {
    if (this.structure && (contentBetween(doc, this.from, this.gapFrom) || contentBetween(doc, this.gapTo, this.to))) {
      return StepResult.fail("Structure gap-replace would overwrite content");
    }

    var gap = doc.slice(this.gapFrom, this.gapTo);

    if (gap.openStart || gap.openEnd) {
      return StepResult.fail("Gap is not a flat range");
    }

    var inserted = this.slice.insertAt(this.insert, gap.content);

    if (!inserted) {
      return StepResult.fail("Content does not fit in gap");
    }

    return StepResult.fromReplace(doc, this.from, this.to, inserted);
  };

  ReplaceAroundStep.prototype.getMap = function getMap() {
    return new StepMap([this.from, this.gapFrom - this.from, this.insert, this.gapTo, this.to - this.gapTo, this.slice.size - this.insert]);
  };

  ReplaceAroundStep.prototype.invert = function invert(doc) {
    var gap = this.gapTo - this.gapFrom;
    return new ReplaceAroundStep(this.from, this.from + this.slice.size + gap, this.from + this.insert, this.from + this.insert + gap, doc.slice(this.from, this.to).removeBetween(this.gapFrom - this.from, this.gapTo - this.from), this.gapFrom - this.from, this.structure);
  };

  ReplaceAroundStep.prototype.map = function map(mapping) {
    var from = mapping.mapResult(this.from, 1),
        to = mapping.mapResult(this.to, -1);
    var gapFrom = mapping.map(this.gapFrom, -1),
        gapTo = mapping.map(this.gapTo, 1);

    if (from.deleted && to.deleted || gapFrom < from.pos || gapTo > to.pos) {
      return null;
    }

    return new ReplaceAroundStep(from.pos, to.pos, gapFrom, gapTo, this.slice, this.insert, this.structure);
  };

  ReplaceAroundStep.prototype.toJSON = function toJSON() {
    var json = {
      stepType: "replaceAround",
      from: this.from,
      to: this.to,
      gapFrom: this.gapFrom,
      gapTo: this.gapTo,
      insert: this.insert
    };

    if (this.slice.size) {
      json.slice = this.slice.toJSON();
    }

    if (this.structure) {
      json.structure = true;
    }

    return json;
  };

  ReplaceAroundStep.fromJSON = function fromJSON(schema, json) {
    if (typeof json.from != "number" || typeof json.to != "number" || typeof json.gapFrom != "number" || typeof json.gapTo != "number" || typeof json.insert != "number") {
      throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");
    }

    return new ReplaceAroundStep(json.from, json.to, json.gapFrom, json.gapTo, _prosemirrorModel.Slice.fromJSON(schema, json.slice), json.insert, !!json.structure);
  };

  return ReplaceAroundStep;
}(Step);

exports.ReplaceAroundStep = ReplaceAroundStep;
Step.jsonID("replaceAround", ReplaceAroundStep);

function contentBetween(doc, from, to) {
  var $from = doc.resolve(from),
      dist = to - from,
      depth = $from.depth;

  while (dist > 0 && depth > 0 && $from.indexAfter(depth) == $from.node(depth).childCount) {
    depth--;
    dist--;
  }

  if (dist > 0) {
    var next = $from.node(depth).maybeChild($from.indexAfter(depth));

    while (dist > 0) {
      if (!next || next.isLeaf) {
        return true;
      }

      next = next.firstChild;
      dist--;
    }
  }

  return false;
}

function canCut(node, start, end) {
  return (start == 0 || node.canReplace(start, node.childCount)) && (end == node.childCount || node.canReplace(0, end));
} // :: (NodeRange) → ?number
// Try to find a target depth to which the content in the given range
// can be lifted. Will not go across
// [isolating](#model.NodeSpec.isolating) parent nodes.


function liftTarget(range) {
  var parent = range.parent;
  var content = parent.content.cutByIndex(range.startIndex, range.endIndex);

  for (var depth = range.depth;; --depth) {
    var node = range.$from.node(depth);
    var index = range.$from.index(depth),
        endIndex = range.$to.indexAfter(depth);

    if (depth < range.depth && node.canReplace(index, endIndex, content)) {
      return depth;
    }

    if (depth == 0 || node.type.spec.isolating || !canCut(node, index, endIndex)) {
      break;
    }
  }
} // :: (NodeRange, number) → this
// Split the content in the given range off from its parent, if there
// is sibling content before or after it, and move it up the tree to
// the depth specified by `target`. You'll probably want to use
// [`liftTarget`](#transform.liftTarget) to compute `target`, to make
// sure the lift is valid.


Transform.prototype.lift = function (range, target) {
  var $from = range.$from;
  var $to = range.$to;
  var depth = range.depth;
  var gapStart = $from.before(depth + 1),
      gapEnd = $to.after(depth + 1);
  var start = gapStart,
      end = gapEnd;
  var before = _prosemirrorModel.Fragment.empty,
      openStart = 0;

  for (var d = depth, splitting = false; d > target; d--) {
    if (splitting || $from.index(d) > 0) {
      splitting = true;
      before = _prosemirrorModel.Fragment.from($from.node(d).copy(before));
      openStart++;
    } else {
      start--;
    }
  }

  var after = _prosemirrorModel.Fragment.empty,
      openEnd = 0;

  for (var d$1 = depth, splitting$1 = false; d$1 > target; d$1--) {
    if (splitting$1 || $to.after(d$1 + 1) < $to.end(d$1)) {
      splitting$1 = true;
      after = _prosemirrorModel.Fragment.from($to.node(d$1).copy(after));
      openEnd++;
    } else {
      end++;
    }
  }

  return this.step(new ReplaceAroundStep(start, end, gapStart, gapEnd, new _prosemirrorModel.Slice(before.append(after), openStart, openEnd), before.size - openStart, true));
}; // :: (NodeRange, NodeType, ?Object, ?NodeRange) → ?[{type: NodeType, attrs: ?Object}]
// Try to find a valid way to wrap the content in the given range in a
// node of the given type. May introduce extra nodes around and inside
// the wrapper node, if necessary. Returns null if no valid wrapping
// could be found. When `innerRange` is given, that range's content is
// used as the content to fit into the wrapping, instead of the
// content of `range`.


function findWrapping(range, nodeType, attrs, innerRange) {
  if (innerRange === void 0) innerRange = range;
  var around = findWrappingOutside(range, nodeType);
  var inner = around && findWrappingInside(innerRange, nodeType);

  if (!inner) {
    return null;
  }

  return around.map(withAttrs).concat({
    type: nodeType,
    attrs: attrs
  }).concat(inner.map(withAttrs));
}

function withAttrs(type) {
  return {
    type: type,
    attrs: null
  };
}

function findWrappingOutside(range, type) {
  var parent = range.parent;
  var startIndex = range.startIndex;
  var endIndex = range.endIndex;
  var around = parent.contentMatchAt(startIndex).findWrapping(type);

  if (!around) {
    return null;
  }

  var outer = around.length ? around[0] : type;
  return parent.canReplaceWith(startIndex, endIndex, outer) ? around : null;
}

function findWrappingInside(range, type) {
  var parent = range.parent;
  var startIndex = range.startIndex;
  var endIndex = range.endIndex;
  var inner = parent.child(startIndex);
  var inside = type.contentMatch.findWrapping(inner.type);

  if (!inside) {
    return null;
  }

  var lastType = inside.length ? inside[inside.length - 1] : type;
  var innerMatch = lastType.contentMatch;

  for (var i = startIndex; innerMatch && i < endIndex; i++) {
    innerMatch = innerMatch.matchType(parent.child(i).type);
  }

  if (!innerMatch || !innerMatch.validEnd) {
    return null;
  }

  return inside;
} // :: (NodeRange, [{type: NodeType, attrs: ?Object}]) → this
// Wrap the given [range](#model.NodeRange) in the given set of wrappers.
// The wrappers are assumed to be valid in this position, and should
// probably be computed with [`findWrapping`](#transform.findWrapping).


Transform.prototype.wrap = function (range, wrappers) {
  var content = _prosemirrorModel.Fragment.empty;

  for (var i = wrappers.length - 1; i >= 0; i--) {
    content = _prosemirrorModel.Fragment.from(wrappers[i].type.create(wrappers[i].attrs, content));
  }

  var start = range.start,
      end = range.end;
  return this.step(new ReplaceAroundStep(start, end, start, end, new _prosemirrorModel.Slice(content, 0, 0), wrappers.length, true));
}; // :: (number, ?number, NodeType, ?Object) → this
// Set the type of all textblocks (partly) between `from` and `to` to
// the given node type with the given attributes.


Transform.prototype.setBlockType = function (from, to, type, attrs) {
  var this$1 = this;
  if (to === void 0) to = from;

  if (!type.isTextblock) {
    throw new RangeError("Type given to setBlockType should be a textblock");
  }

  var mapFrom = this.steps.length;
  this.doc.nodesBetween(from, to, function (node, pos) {
    if (node.isTextblock && !node.hasMarkup(type, attrs) && canChangeType(this$1.doc, this$1.mapping.slice(mapFrom).map(pos), type)) {
      // Ensure all markup that isn't allowed in the new node type is cleared
      this$1.clearIncompatible(this$1.mapping.slice(mapFrom).map(pos, 1), type);
      var mapping = this$1.mapping.slice(mapFrom);
      var startM = mapping.map(pos, 1),
          endM = mapping.map(pos + node.nodeSize, 1);
      this$1.step(new ReplaceAroundStep(startM, endM, startM + 1, endM - 1, new _prosemirrorModel.Slice(_prosemirrorModel.Fragment.from(type.create(attrs, null, node.marks)), 0, 0), 1, true));
      return false;
    }
  });
  return this;
};

function canChangeType(doc, pos, type) {
  var $pos = doc.resolve(pos),
      index = $pos.index();
  return $pos.parent.canReplaceWith(index, index + 1, type);
} // :: (number, ?NodeType, ?Object, ?[Mark]) → this
// Change the type, attributes, and/or marks of the node at `pos`.
// When `type` isn't given, the existing node type is preserved,


Transform.prototype.setNodeMarkup = function (pos, type, attrs, marks) {
  var node = this.doc.nodeAt(pos);

  if (!node) {
    throw new RangeError("No node at given position");
  }

  if (!type) {
    type = node.type;
  }

  var newNode = type.create(attrs, null, marks || node.marks);

  if (node.isLeaf) {
    return this.replaceWith(pos, pos + node.nodeSize, newNode);
  }

  if (!type.validContent(node.content)) {
    throw new RangeError("Invalid content for node type " + type.name);
  }

  return this.step(new ReplaceAroundStep(pos, pos + node.nodeSize, pos + 1, pos + node.nodeSize - 1, new _prosemirrorModel.Slice(_prosemirrorModel.Fragment.from(newNode), 0, 0), 1, true));
}; // :: (Node, number, number, ?[?{type: NodeType, attrs: ?Object}]) → bool
// Check whether splitting at the given position is allowed.


function canSplit(doc, pos, depth, typesAfter) {
  if (depth === void 0) depth = 1;
  var $pos = doc.resolve(pos),
      base = $pos.depth - depth;
  var innerType = typesAfter && typesAfter[typesAfter.length - 1] || $pos.parent;

  if (base < 0 || $pos.parent.type.spec.isolating || !$pos.parent.canReplace($pos.index(), $pos.parent.childCount) || !innerType.type.validContent($pos.parent.content.cutByIndex($pos.index(), $pos.parent.childCount))) {
    return false;
  }

  for (var d = $pos.depth - 1, i = depth - 2; d > base; d--, i--) {
    var node = $pos.node(d),
        index$1 = $pos.index(d);

    if (node.type.spec.isolating) {
      return false;
    }

    var rest = node.content.cutByIndex(index$1, node.childCount);
    var after = typesAfter && typesAfter[i] || node;

    if (after != node) {
      rest = rest.replaceChild(0, after.type.create(after.attrs));
    }

    if (!node.canReplace(index$1 + 1, node.childCount) || !after.type.validContent(rest)) {
      return false;
    }
  }

  var index = $pos.indexAfter(base);
  var baseType = typesAfter && typesAfter[0];
  return $pos.node(base).canReplaceWith(index, index, baseType ? baseType.type : $pos.node(base + 1).type);
} // :: (number, ?number, ?[?{type: NodeType, attrs: ?Object}]) → this
// Split the node at the given position, and optionally, if `depth` is
// greater than one, any number of nodes above that. By default, the
// parts split off will inherit the node type of the original node.
// This can be changed by passing an array of types and attributes to
// use after the split.


Transform.prototype.split = function (pos, depth, typesAfter) {
  if (depth === void 0) depth = 1;
  var $pos = this.doc.resolve(pos),
      before = _prosemirrorModel.Fragment.empty,
      after = _prosemirrorModel.Fragment.empty;

  for (var d = $pos.depth, e = $pos.depth - depth, i = depth - 1; d > e; d--, i--) {
    before = _prosemirrorModel.Fragment.from($pos.node(d).copy(before));
    var typeAfter = typesAfter && typesAfter[i];
    after = _prosemirrorModel.Fragment.from(typeAfter ? typeAfter.type.create(typeAfter.attrs, after) : $pos.node(d).copy(after));
  }

  return this.step(new ReplaceStep(pos, pos, new _prosemirrorModel.Slice(before.append(after), depth, depth), true));
}; // :: (Node, number) → bool
// Test whether the blocks before and after a given position can be
// joined.


function canJoin(doc, pos) {
  var $pos = doc.resolve(pos),
      index = $pos.index();
  return joinable($pos.nodeBefore, $pos.nodeAfter) && $pos.parent.canReplace(index, index + 1);
}

function joinable(a, b) {
  return a && b && !a.isLeaf && a.canAppend(b);
} // :: (Node, number, ?number) → ?number
// Find an ancestor of the given position that can be joined to the
// block before (or after if `dir` is positive). Returns the joinable
// point, if any.


function joinPoint(doc, pos, dir) {
  if (dir === void 0) dir = -1;
  var $pos = doc.resolve(pos);

  for (var d = $pos.depth;; d--) {
    var before = void 0,
        after = void 0,
        index = $pos.index(d);

    if (d == $pos.depth) {
      before = $pos.nodeBefore;
      after = $pos.nodeAfter;
    } else if (dir > 0) {
      before = $pos.node(d + 1);
      index++;
      after = $pos.node(d).maybeChild(index);
    } else {
      before = $pos.node(d).maybeChild(index - 1);
      after = $pos.node(d + 1);
    }

    if (before && !before.isTextblock && joinable(before, after) && $pos.node(d).canReplace(index, index + 1)) {
      return pos;
    }

    if (d == 0) {
      break;
    }

    pos = dir < 0 ? $pos.before(d) : $pos.after(d);
  }
} // :: (number, ?number) → this
// Join the blocks around the given position. If depth is 2, their
// last and first siblings are also joined, and so on.


Transform.prototype.join = function (pos, depth) {
  if (depth === void 0) depth = 1;
  var step = new ReplaceStep(pos - depth, pos + depth, _prosemirrorModel.Slice.empty, true);
  return this.step(step);
}; // :: (Node, number, NodeType) → ?number
// Try to find a point where a node of the given type can be inserted
// near `pos`, by searching up the node hierarchy when `pos` itself
// isn't a valid place but is at the start or end of a node. Return
// null if no position was found.


function insertPoint(doc, pos, nodeType) {
  var $pos = doc.resolve(pos);

  if ($pos.parent.canReplaceWith($pos.index(), $pos.index(), nodeType)) {
    return pos;
  }

  if ($pos.parentOffset == 0) {
    for (var d = $pos.depth - 1; d >= 0; d--) {
      var index = $pos.index(d);

      if ($pos.node(d).canReplaceWith(index, index, nodeType)) {
        return $pos.before(d + 1);
      }

      if (index > 0) {
        return null;
      }
    }
  }

  if ($pos.parentOffset == $pos.parent.content.size) {
    for (var d$1 = $pos.depth - 1; d$1 >= 0; d$1--) {
      var index$1 = $pos.indexAfter(d$1);

      if ($pos.node(d$1).canReplaceWith(index$1, index$1, nodeType)) {
        return $pos.after(d$1 + 1);
      }

      if (index$1 < $pos.node(d$1).childCount) {
        return null;
      }
    }
  }
} // :: (Node, number, Slice) → ?number
// Finds a position at or around the given position where the given
// slice can be inserted. Will look at parent nodes' nearest boundary
// and try there, even if the original position wasn't directly at the
// start or end of that node. Returns null when no position was found.


function dropPoint(doc, pos, slice) {
  var $pos = doc.resolve(pos);

  if (!slice.content.size) {
    return pos;
  }

  var content = slice.content;

  for (var i = 0; i < slice.openStart; i++) {
    content = content.firstChild.content;
  }

  for (var pass = 1; pass <= (slice.openStart == 0 && slice.size ? 2 : 1); pass++) {
    for (var d = $pos.depth; d >= 0; d--) {
      var bias = d == $pos.depth ? 0 : $pos.pos <= ($pos.start(d + 1) + $pos.end(d + 1)) / 2 ? -1 : 1;
      var insertPos = $pos.index(d) + (bias > 0 ? 1 : 0);

      if (pass == 1 ? $pos.node(d).canReplace(insertPos, insertPos, content) : $pos.node(d).contentMatchAt(insertPos).findWrapping(content.firstChild.type)) {
        return bias == 0 ? $pos.pos : bias < 0 ? $pos.before(d + 1) : $pos.after(d + 1);
      }
    }
  }

  return null;
}

function mapFragment(fragment, f, parent) {
  var mapped = [];

  for (var i = 0; i < fragment.childCount; i++) {
    var child = fragment.child(i);

    if (child.content.size) {
      child = child.copy(mapFragment(child.content, f, child));
    }

    if (child.isInline) {
      child = f(child, parent, i);
    }

    mapped.push(child);
  }

  return _prosemirrorModel.Fragment.fromArray(mapped);
} // ::- Add a mark to all inline content between two positions.


var AddMarkStep = /*@__PURE__*/function (Step) {
  function AddMarkStep(from, to, mark) {
    Step.call(this);
    this.from = from;
    this.to = to;
    this.mark = mark;
  }

  if (Step) AddMarkStep.__proto__ = Step;
  AddMarkStep.prototype = Object.create(Step && Step.prototype);
  AddMarkStep.prototype.constructor = AddMarkStep;

  AddMarkStep.prototype.apply = function apply(doc) {
    var this$1 = this;
    var oldSlice = doc.slice(this.from, this.to),
        $from = doc.resolve(this.from);
    var parent = $from.node($from.sharedDepth(this.to));
    var slice = new _prosemirrorModel.Slice(mapFragment(oldSlice.content, function (node, parent) {
      if (!parent.type.allowsMarkType(this$1.mark.type)) {
        return node;
      }

      return node.mark(this$1.mark.addToSet(node.marks));
    }, parent), oldSlice.openStart, oldSlice.openEnd);
    return StepResult.fromReplace(doc, this.from, this.to, slice);
  };

  AddMarkStep.prototype.invert = function invert() {
    return new RemoveMarkStep(this.from, this.to, this.mark);
  };

  AddMarkStep.prototype.map = function map(mapping) {
    var from = mapping.mapResult(this.from, 1),
        to = mapping.mapResult(this.to, -1);

    if (from.deleted && to.deleted || from.pos >= to.pos) {
      return null;
    }

    return new AddMarkStep(from.pos, to.pos, this.mark);
  };

  AddMarkStep.prototype.merge = function merge(other) {
    if (other instanceof AddMarkStep && other.mark.eq(this.mark) && this.from <= other.to && this.to >= other.from) {
      return new AddMarkStep(Math.min(this.from, other.from), Math.max(this.to, other.to), this.mark);
    }
  };

  AddMarkStep.prototype.toJSON = function toJSON() {
    return {
      stepType: "addMark",
      mark: this.mark.toJSON(),
      from: this.from,
      to: this.to
    };
  };

  AddMarkStep.fromJSON = function fromJSON(schema, json) {
    if (typeof json.from != "number" || typeof json.to != "number") {
      throw new RangeError("Invalid input for AddMarkStep.fromJSON");
    }

    return new AddMarkStep(json.from, json.to, schema.markFromJSON(json.mark));
  };

  return AddMarkStep;
}(Step);

exports.AddMarkStep = AddMarkStep;
Step.jsonID("addMark", AddMarkStep); // ::- Remove a mark from all inline content between two positions.

var RemoveMarkStep = /*@__PURE__*/function (Step) {
  function RemoveMarkStep(from, to, mark) {
    Step.call(this);
    this.from = from;
    this.to = to;
    this.mark = mark;
  }

  if (Step) RemoveMarkStep.__proto__ = Step;
  RemoveMarkStep.prototype = Object.create(Step && Step.prototype);
  RemoveMarkStep.prototype.constructor = RemoveMarkStep;

  RemoveMarkStep.prototype.apply = function apply(doc) {
    var this$1 = this;
    var oldSlice = doc.slice(this.from, this.to);
    var slice = new _prosemirrorModel.Slice(mapFragment(oldSlice.content, function (node) {
      return node.mark(this$1.mark.removeFromSet(node.marks));
    }), oldSlice.openStart, oldSlice.openEnd);
    return StepResult.fromReplace(doc, this.from, this.to, slice);
  };

  RemoveMarkStep.prototype.invert = function invert() {
    return new AddMarkStep(this.from, this.to, this.mark);
  };

  RemoveMarkStep.prototype.map = function map(mapping) {
    var from = mapping.mapResult(this.from, 1),
        to = mapping.mapResult(this.to, -1);

    if (from.deleted && to.deleted || from.pos >= to.pos) {
      return null;
    }

    return new RemoveMarkStep(from.pos, to.pos, this.mark);
  };

  RemoveMarkStep.prototype.merge = function merge(other) {
    if (other instanceof RemoveMarkStep && other.mark.eq(this.mark) && this.from <= other.to && this.to >= other.from) {
      return new RemoveMarkStep(Math.min(this.from, other.from), Math.max(this.to, other.to), this.mark);
    }
  };

  RemoveMarkStep.prototype.toJSON = function toJSON() {
    return {
      stepType: "removeMark",
      mark: this.mark.toJSON(),
      from: this.from,
      to: this.to
    };
  };

  RemoveMarkStep.fromJSON = function fromJSON(schema, json) {
    if (typeof json.from != "number" || typeof json.to != "number") {
      throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");
    }

    return new RemoveMarkStep(json.from, json.to, schema.markFromJSON(json.mark));
  };

  return RemoveMarkStep;
}(Step);

exports.RemoveMarkStep = RemoveMarkStep;
Step.jsonID("removeMark", RemoveMarkStep); // :: (number, number, Mark) → this
// Add the given mark to the inline content between `from` and `to`.

Transform.prototype.addMark = function (from, to, mark) {
  var this$1 = this;
  var removed = [],
      added = [],
      removing = null,
      adding = null;
  this.doc.nodesBetween(from, to, function (node, pos, parent) {
    if (!node.isInline) {
      return;
    }

    var marks = node.marks;

    if (!mark.isInSet(marks) && parent.type.allowsMarkType(mark.type)) {
      var start = Math.max(pos, from),
          end = Math.min(pos + node.nodeSize, to);
      var newSet = mark.addToSet(marks);

      for (var i = 0; i < marks.length; i++) {
        if (!marks[i].isInSet(newSet)) {
          if (removing && removing.to == start && removing.mark.eq(marks[i])) {
            removing.to = end;
          } else {
            removed.push(removing = new RemoveMarkStep(start, end, marks[i]));
          }
        }
      }

      if (adding && adding.to == start) {
        adding.to = end;
      } else {
        added.push(adding = new AddMarkStep(start, end, mark));
      }
    }
  });
  removed.forEach(function (s) {
    return this$1.step(s);
  });
  added.forEach(function (s) {
    return this$1.step(s);
  });
  return this;
}; // :: (number, number, ?union<Mark, MarkType>) → this
// Remove marks from inline nodes between `from` and `to`. When `mark`
// is a single mark, remove precisely that mark. When it is a mark type,
// remove all marks of that type. When it is null, remove all marks of
// any type.


Transform.prototype.removeMark = function (from, to, mark) {
  var this$1 = this;
  if (mark === void 0) mark = null;
  var matched = [],
      step = 0;
  this.doc.nodesBetween(from, to, function (node, pos) {
    if (!node.isInline) {
      return;
    }

    step++;
    var toRemove = null;

    if (mark instanceof _prosemirrorModel.MarkType) {
      var found = mark.isInSet(node.marks);

      if (found) {
        toRemove = [found];
      }
    } else if (mark) {
      if (mark.isInSet(node.marks)) {
        toRemove = [mark];
      }
    } else {
      toRemove = node.marks;
    }

    if (toRemove && toRemove.length) {
      var end = Math.min(pos + node.nodeSize, to);

      for (var i = 0; i < toRemove.length; i++) {
        var style = toRemove[i],
            found$1 = void 0;

        for (var j = 0; j < matched.length; j++) {
          var m = matched[j];

          if (m.step == step - 1 && style.eq(matched[j].style)) {
            found$1 = m;
          }
        }

        if (found$1) {
          found$1.to = end;
          found$1.step = step;
        } else {
          matched.push({
            style: style,
            from: Math.max(pos, from),
            to: end,
            step: step
          });
        }
      }
    }
  });
  matched.forEach(function (m) {
    return this$1.step(new RemoveMarkStep(m.from, m.to, m.style));
  });
  return this;
}; // :: (number, NodeType, ?ContentMatch) → this
// Removes all marks and nodes from the content of the node at `pos`
// that don't match the given new parent node type. Accepts an
// optional starting [content match](#model.ContentMatch) as third
// argument.


Transform.prototype.clearIncompatible = function (pos, parentType, match) {
  if (match === void 0) match = parentType.contentMatch;
  var node = this.doc.nodeAt(pos);
  var delSteps = [],
      cur = pos + 1;

  for (var i = 0; i < node.childCount; i++) {
    var child = node.child(i),
        end = cur + child.nodeSize;
    var allowed = match.matchType(child.type, child.attrs);

    if (!allowed) {
      delSteps.push(new ReplaceStep(cur, end, _prosemirrorModel.Slice.empty));
    } else {
      match = allowed;

      for (var j = 0; j < child.marks.length; j++) {
        if (!parentType.allowsMarkType(child.marks[j].type)) {
          this.step(new RemoveMarkStep(cur, end, child.marks[j]));
        }
      }
    }

    cur = end;
  }

  if (!match.validEnd) {
    var fill = match.fillBefore(_prosemirrorModel.Fragment.empty, true);
    this.replace(cur, cur, new _prosemirrorModel.Slice(fill, 0, 0));
  }

  for (var i$1 = delSteps.length - 1; i$1 >= 0; i$1--) {
    this.step(delSteps[i$1]);
  }

  return this;
}; // :: (Node, number, ?number, ?Slice) → ?Step
// ‘Fit’ a slice into a given position in the document, producing a
// [step](#transform.Step) that inserts it. Will return null if
// there's no meaningful way to insert the slice here, or inserting it
// would be a no-op (an empty slice over an empty range).


function replaceStep(doc, from, to, slice) {
  if (to === void 0) to = from;
  if (slice === void 0) slice = _prosemirrorModel.Slice.empty;

  if (from == to && !slice.size) {
    return null;
  }

  var $from = doc.resolve(from),
      $to = doc.resolve(to); // Optimization -- avoid work if it's obvious that it's not needed.

  if (fitsTrivially($from, $to, slice)) {
    return new ReplaceStep(from, to, slice);
  }

  return new Fitter($from, $to, slice).fit();
} // :: (number, ?number, ?Slice) → this
// Replace the part of the document between `from` and `to` with the
// given `slice`.


Transform.prototype.replace = function (from, to, slice) {
  if (to === void 0) to = from;
  if (slice === void 0) slice = _prosemirrorModel.Slice.empty;
  var step = replaceStep(this.doc, from, to, slice);

  if (step) {
    this.step(step);
  }

  return this;
}; // :: (number, number, union<Fragment, Node, [Node]>) → this
// Replace the given range with the given content, which may be a
// fragment, node, or array of nodes.


Transform.prototype.replaceWith = function (from, to, content) {
  return this.replace(from, to, new _prosemirrorModel.Slice(_prosemirrorModel.Fragment.from(content), 0, 0));
}; // :: (number, number) → this
// Delete the content between the given positions.


Transform.prototype.delete = function (from, to) {
  return this.replace(from, to, _prosemirrorModel.Slice.empty);
}; // :: (number, union<Fragment, Node, [Node]>) → this
// Insert the given content at the given position.


Transform.prototype.insert = function (pos, content) {
  return this.replaceWith(pos, pos, content);
};

function fitsTrivially($from, $to, slice) {
  return !slice.openStart && !slice.openEnd && $from.start() == $to.start() && $from.parent.canReplace($from.index(), $to.index(), slice.content);
} // Algorithm for 'placing' the elements of a slice into a gap:
//
// We consider the content of each node that is open to the left to be
// independently placeable. I.e. in <p("foo"), p("bar")>, when the
// paragraph on the left is open, "foo" can be placed (somewhere on
// the left side of the replacement gap) independently from p("bar").
//
// This class tracks the state of the placement progress in the
// following properties:
//
//  - `frontier` holds a stack of `{type, match}` objects that
//    represent the open side of the replacement. It starts at
//    `$from`, then moves forward as content is placed, and is finally
//    reconciled with `$to`.
//
//  - `unplaced` is a slice that represents the content that hasn't
//    been placed yet.
//
//  - `placed` is a fragment of placed content. Its open-start value
//    is implicit in `$from`, and its open-end value in `frontier`.


var Fitter = function Fitter($from, $to, slice) {
  this.$to = $to;
  this.$from = $from;
  this.unplaced = slice;
  this.frontier = [];

  for (var i = 0; i <= $from.depth; i++) {
    var node = $from.node(i);
    this.frontier.push({
      type: node.type,
      match: node.contentMatchAt($from.indexAfter(i))
    });
  }

  this.placed = _prosemirrorModel.Fragment.empty;

  for (var i$1 = $from.depth; i$1 > 0; i$1--) {
    this.placed = _prosemirrorModel.Fragment.from($from.node(i$1).copy(this.placed));
  }
};

var prototypeAccessors$1 = {
  depth: {
    configurable: true
  }
};

prototypeAccessors$1.depth.get = function () {
  return this.frontier.length - 1;
};

Fitter.prototype.fit = function fit() {
  // As long as there's unplaced content, try to place some of it.
  // If that fails, either increase the open score of the unplaced
  // slice, or drop nodes from it, and then try again.
  while (this.unplaced.size) {
    var fit = this.findFittable();

    if (fit) {
      this.placeNodes(fit);
    } else {
      this.openMore() || this.dropNode();
    }
  } // When there's inline content directly after the frontier _and_
  // directly after `this.$to`, we must generate a `ReplaceAround`
  // step that pulls that content into the node after the frontier.
  // That means the fitting must be done to the end of the textblock
  // node after `this.$to`, not `this.$to` itself.


  var moveInline = this.mustMoveInline(),
      placedSize = this.placed.size - this.depth - this.$from.depth;
  var $from = this.$from,
      $to = moveInline < 0 ? this.$to : $from.doc.resolve(moveInline);

  if (this.close($to)) {
    // If closing to `$to` succeeded, create a step
    var content = this.placed,
        openStart = $from.depth,
        openEnd = $to.depth;

    while (openStart && openEnd && content.childCount == 1) {
      // Normalize by dropping open parent nodes
      content = content.firstChild.content;
      openStart--;
      openEnd--;
    }

    var slice = new _prosemirrorModel.Slice(content, openStart, openEnd);

    if (moveInline > -1) {
      return new ReplaceAroundStep($from.pos, moveInline, this.$to.pos, this.$to.end(), slice, placedSize);
    }

    if (slice.size || $from.pos != this.$to.pos) // Don't generate no-op steps
      {
        return new ReplaceStep($from.pos, $to.pos, slice);
      }
  }

  return null;
}; // Find a position on the start spine of `this.unplaced` that has
// content that can be moved somewhere on the frontier. Returns two
// depths, one for the slice and one for the frontier.


Fitter.prototype.findFittable = function findFittable() {
  // Only try wrapping nodes (pass 2) after finding a place without
  // wrapping failed.
  for (var pass = 1; pass <= 2; pass++) {
    for (var sliceDepth = this.unplaced.openStart; sliceDepth >= 0; sliceDepth--) {
      var fragment = void 0,
          parent = void 0;

      if (sliceDepth) {
        parent = contentAt(this.unplaced.content, sliceDepth - 1).firstChild;
        fragment = parent.content;
      } else {
        fragment = this.unplaced.content;
      }

      var first = fragment.firstChild;

      for (var frontierDepth = this.depth; frontierDepth >= 0; frontierDepth--) {
        var ref = this.frontier[frontierDepth];
        var type = ref.type;
        var match = ref.match;
        var wrap = void 0,
            inject = void 0; // In pass 1, if the next node matches, or there is no next
        // node but the parents look compatible, we've found a
        // place.

        if (pass == 1 && (first ? match.matchType(first.type) || (inject = match.fillBefore(_prosemirrorModel.Fragment.from(first), false)) : type.compatibleContent(parent.type))) {
          return {
            sliceDepth: sliceDepth,
            frontierDepth: frontierDepth,
            parent: parent,
            inject: inject
          };
        } // In pass 2, look for a set of wrapping nodes that make
        // `first` fit here.
        else if (pass == 2 && first && (wrap = match.findWrapping(first.type))) {
            return {
              sliceDepth: sliceDepth,
              frontierDepth: frontierDepth,
              parent: parent,
              wrap: wrap
            };
          } // Don't continue looking further up if the parent node
        // would fit here.


        if (parent && match.matchType(parent.type)) {
          break;
        }
      }
    }
  }
};

Fitter.prototype.openMore = function openMore() {
  var ref = this.unplaced;
  var content = ref.content;
  var openStart = ref.openStart;
  var openEnd = ref.openEnd;
  var inner = contentAt(content, openStart);

  if (!inner.childCount || inner.firstChild.isLeaf) {
    return false;
  }

  this.unplaced = new _prosemirrorModel.Slice(content, openStart + 1, Math.max(openEnd, inner.size + openStart >= content.size - openEnd ? openStart + 1 : 0));
  return true;
};

Fitter.prototype.dropNode = function dropNode() {
  var ref = this.unplaced;
  var content = ref.content;
  var openStart = ref.openStart;
  var openEnd = ref.openEnd;
  var inner = contentAt(content, openStart);

  if (inner.childCount <= 1 && openStart > 0) {
    var openAtEnd = content.size - openStart <= openStart + inner.size;
    this.unplaced = new _prosemirrorModel.Slice(dropFromFragment(content, openStart - 1, 1), openStart - 1, openAtEnd ? openStart - 1 : openEnd);
  } else {
    this.unplaced = new _prosemirrorModel.Slice(dropFromFragment(content, openStart, 1), openStart, openEnd);
  }
}; // : ({sliceDepth: number, frontierDepth: number, parent: ?Node, wrap: ?[NodeType], inject: ?Fragment})
// Move content from the unplaced slice at `sliceDepth` to the
// frontier node at `frontierDepth`. Close that frontier node when
// applicable.


Fitter.prototype.placeNodes = function placeNodes(ref) {
  var sliceDepth = ref.sliceDepth;
  var frontierDepth = ref.frontierDepth;
  var parent = ref.parent;
  var inject = ref.inject;
  var wrap = ref.wrap;

  while (this.depth > frontierDepth) {
    this.closeFrontierNode();
  }

  if (wrap) {
    for (var i = 0; i < wrap.length; i++) {
      this.openFrontierNode(wrap[i]);
    }
  }

  var slice = this.unplaced,
      fragment = parent ? parent.content : slice.content;
  var openStart = slice.openStart - sliceDepth;
  var taken = 0,
      add = [];
  var ref$1 = this.frontier[frontierDepth];
  var match = ref$1.match;
  var type = ref$1.type;

  if (inject) {
    for (var i$1 = 0; i$1 < inject.childCount; i$1++) {
      add.push(inject.child(i$1));
    }

    match = match.matchFragment(inject);
  } // Computes the amount of (end) open nodes at the end of the
  // fragment. When 0, the parent is open, but no more. When
  // negative, nothing is open.


  var openEndCount = fragment.size + sliceDepth - (slice.content.size - slice.openEnd); // Scan over the fragment, fitting as many child nodes as
  // possible.

  while (taken < fragment.childCount) {
    var next = fragment.child(taken),
        matches = match.matchType(next.type);

    if (!matches) {
      break;
    }

    taken++;

    if (taken > 1 || openStart == 0 || next.content.size) {
      // Drop empty open nodes
      match = matches;
      add.push(closeNodeStart(next.mark(type.allowedMarks(next.marks)), taken == 1 ? openStart : 0, taken == fragment.childCount ? openEndCount : -1));
    }
  }

  var toEnd = taken == fragment.childCount;

  if (!toEnd) {
    openEndCount = -1;
  } // If the parent types match, and the entire node was moved, and
  // it's not open, close this frontier node right away.


  if (toEnd && openEndCount < 0 && parent && parent.type == this.frontier[this.depth].type) {
    this.closeFrontierNode();
  } else {
    this.frontier[frontierDepth].match = match;
  } // Add new frontier nodes for any open nodes at the end.


  for (var i$2 = 0, cur = fragment; i$2 < openEndCount; i$2++) {
    var node = cur.lastChild;
    this.frontier.push({
      type: node.type,
      match: node.contentMatchAt(node.childCount)
    });
    cur = node.content;
  } // Update `this.unplaced`. Drop the entire node from which we
  // placed it we got to its end, otherwise just drop the placed
  // nodes.


  this.unplaced = !toEnd ? new _prosemirrorModel.Slice(dropFromFragment(slice.content, sliceDepth, taken), slice.openStart, slice.openEnd) : sliceDepth == 0 ? _prosemirrorModel.Slice.empty : new _prosemirrorModel.Slice(dropFromFragment(slice.content, sliceDepth - 1, 1), sliceDepth - 1, openEndCount < 0 ? slice.openEnd : sliceDepth - 1);
  this.placed = addToFragment(this.placed, frontierDepth, _prosemirrorModel.Fragment.from(add));
};

Fitter.prototype.mustMoveInline = function mustMoveInline() {
  if (!this.$to.parent.isTextblock) {
    return -1;
  }

  var top = this.frontier[this.depth],
      level;

  if (!top.type.isTextblock || !contentAfterFits(this.$to, this.$to.depth, top.type, top.match, false) || this.$to.depth == this.depth && (level = this.findCloseLevel(this.$to)) && level.depth == this.depth) {
    return -1;
  }

  var ref = this.$to;
  var depth = ref.depth;
  var after = this.$to.after(depth);

  while (depth > 1 && after == this.$to.end(--depth)) {
    ++after;
  }

  return after;
};

Fitter.prototype.findCloseLevel = function findCloseLevel($to) {
  scan: for (var i = Math.min(this.depth, $to.depth); i >= 0; i--) {
    var ref = this.frontier[i];
    var match = ref.match;
    var type = ref.type;
    var fit = contentAfterFits($to, i, type, match, false);

    if (!fit) {
      continue;
    }

    for (var d = i - 1; d >= 0; d--) {
      var ref$1 = this.frontier[d];
      var match$1 = ref$1.match;
      var type$1 = ref$1.type;
      var matches = contentAfterFits($to, d, type$1, match$1, true);

      if (!matches || matches.childCount) {
        continue scan;
      }
    }

    return {
      depth: i,
      fit: fit
    };
  }
};

Fitter.prototype.close = function close($to) {
  var close = this.findCloseLevel($to);

  if (!close) {
    return false;
  }

  while (this.depth > close.depth) {
    this.closeFrontierNode();
  }

  if (close.fit.childCount) {
    this.placed = addToFragment(this.placed, close.depth, close.fit);
  }

  for (var d = close.depth + 1; d <= $to.depth; d++) {
    var node = $to.node(d),
        add = node.type.contentMatch.fillBefore(node.content, true, $to.index(d));
    this.openFrontierNode(node.type, node.attrs, add);
  }

  return true;
};

Fitter.prototype.openFrontierNode = function openFrontierNode(type, attrs, content) {
  var top = this.frontier[this.depth];
  top.match = top.match.matchType(type);
  this.placed = addToFragment(this.placed, this.depth, _prosemirrorModel.Fragment.from(type.create(attrs, content)));
  this.frontier.push({
    type: type,
    match: type.contentMatch
  });
};

Fitter.prototype.closeFrontierNode = function closeFrontierNode() {
  var open = this.frontier.pop();
  var add = open.match.fillBefore(_prosemirrorModel.Fragment.empty, true);

  if (add.childCount) {
    this.placed = addToFragment(this.placed, this.frontier.length, add);
  }
};

Object.defineProperties(Fitter.prototype, prototypeAccessors$1);

function dropFromFragment(fragment, depth, count) {
  if (depth == 0) {
    return fragment.cutByIndex(count);
  }

  return fragment.replaceChild(0, fragment.firstChild.copy(dropFromFragment(fragment.firstChild.content, depth - 1, count)));
}

function addToFragment(fragment, depth, content) {
  if (depth == 0) {
    return fragment.append(content);
  }

  return fragment.replaceChild(fragment.childCount - 1, fragment.lastChild.copy(addToFragment(fragment.lastChild.content, depth - 1, content)));
}

function contentAt(fragment, depth) {
  for (var i = 0; i < depth; i++) {
    fragment = fragment.firstChild.content;
  }

  return fragment;
}

function closeNodeStart(node, openStart, openEnd) {
  if (openStart <= 0) {
    return node;
  }

  var frag = node.content;

  if (openStart > 1) {
    frag = frag.replaceChild(0, closeNodeStart(frag.firstChild, openStart - 1, frag.childCount == 1 ? openEnd - 1 : 0));
  }

  if (openStart > 0) {
    frag = node.type.contentMatch.fillBefore(frag).append(frag);

    if (openEnd <= 0) {
      frag = frag.append(node.type.contentMatch.matchFragment(frag).fillBefore(_prosemirrorModel.Fragment.empty, true));
    }
  }

  return node.copy(frag);
}

function contentAfterFits($to, depth, type, match, open) {
  var node = $to.node(depth),
      index = open ? $to.indexAfter(depth) : $to.index(depth);

  if (index == node.childCount && !type.compatibleContent(node.type)) {
    return null;
  }

  var fit = match.fillBefore(node.content, true, index);
  return fit && !invalidMarks(type, node.content, index) ? fit : null;
}

function invalidMarks(type, fragment, start) {
  for (var i = start; i < fragment.childCount; i++) {
    if (!type.allowsMarks(fragment.child(i).marks)) {
      return true;
    }
  }

  return false;
} // :: (number, number, Slice) → this
// Replace a range of the document with a given slice, using `from`,
// `to`, and the slice's [`openStart`](#model.Slice.openStart) property
// as hints, rather than fixed start and end points. This method may
// grow the replaced area or close open nodes in the slice in order to
// get a fit that is more in line with WYSIWYG expectations, by
// dropping fully covered parent nodes of the replaced region when
// they are marked [non-defining](#model.NodeSpec.defining), or
// including an open parent node from the slice that _is_ marked as
// [defining](#model.NodeSpec.defining).
//
// This is the method, for example, to handle paste. The similar
// [`replace`](#transform.Transform.replace) method is a more
// primitive tool which will _not_ move the start and end of its given
// range, and is useful in situations where you need more precise
// control over what happens.


Transform.prototype.replaceRange = function (from, to, slice) {
  if (!slice.size) {
    return this.deleteRange(from, to);
  }

  var $from = this.doc.resolve(from),
      $to = this.doc.resolve(to);

  if (fitsTrivially($from, $to, slice)) {
    return this.step(new ReplaceStep(from, to, slice));
  }

  var targetDepths = coveredDepths($from, this.doc.resolve(to)); // Can't replace the whole document, so remove 0 if it's present

  if (targetDepths[targetDepths.length - 1] == 0) {
    targetDepths.pop();
  } // Negative numbers represent not expansion over the whole node at
  // that depth, but replacing from $from.before(-D) to $to.pos.


  var preferredTarget = -($from.depth + 1);
  targetDepths.unshift(preferredTarget); // This loop picks a preferred target depth, if one of the covering
  // depths is not outside of a defining node, and adds negative
  // depths for any depth that has $from at its start and does not
  // cross a defining node.

  for (var d = $from.depth, pos = $from.pos - 1; d > 0; d--, pos--) {
    var spec = $from.node(d).type.spec;

    if (spec.defining || spec.isolating) {
      break;
    }

    if (targetDepths.indexOf(d) > -1) {
      preferredTarget = d;
    } else if ($from.before(d) == pos) {
      targetDepths.splice(1, 0, -d);
    }
  } // Try to fit each possible depth of the slice into each possible
  // target depth, starting with the preferred depths.


  var preferredTargetIndex = targetDepths.indexOf(preferredTarget);
  var leftNodes = [],
      preferredDepth = slice.openStart;

  for (var content = slice.content, i = 0;; i++) {
    var node = content.firstChild;
    leftNodes.push(node);

    if (i == slice.openStart) {
      break;
    }

    content = node.content;
  } // Back up if the node directly above openStart, or the node above
  // that separated only by a non-defining textblock node, is defining.


  if (preferredDepth > 0 && leftNodes[preferredDepth - 1].type.spec.defining && $from.node(preferredTargetIndex).type != leftNodes[preferredDepth - 1].type) {
    preferredDepth -= 1;
  } else if (preferredDepth >= 2 && leftNodes[preferredDepth - 1].isTextblock && leftNodes[preferredDepth - 2].type.spec.defining && $from.node(preferredTargetIndex).type != leftNodes[preferredDepth - 2].type) {
    preferredDepth -= 2;
  }

  for (var j = slice.openStart; j >= 0; j--) {
    var openDepth = (j + preferredDepth + 1) % (slice.openStart + 1);
    var insert = leftNodes[openDepth];

    if (!insert) {
      continue;
    }

    for (var i$1 = 0; i$1 < targetDepths.length; i$1++) {
      // Loop over possible expansion levels, starting with the
      // preferred one
      var targetDepth = targetDepths[(i$1 + preferredTargetIndex) % targetDepths.length],
          expand = true;

      if (targetDepth < 0) {
        expand = false;
        targetDepth = -targetDepth;
      }

      var parent = $from.node(targetDepth - 1),
          index = $from.index(targetDepth - 1);

      if (parent.canReplaceWith(index, index, insert.type, insert.marks)) {
        return this.replace($from.before(targetDepth), expand ? $to.after(targetDepth) : to, new _prosemirrorModel.Slice(closeFragment(slice.content, 0, slice.openStart, openDepth), openDepth, slice.openEnd));
      }
    }
  }

  var startSteps = this.steps.length;

  for (var i$2 = targetDepths.length - 1; i$2 >= 0; i$2--) {
    this.replace(from, to, slice);

    if (this.steps.length > startSteps) {
      break;
    }

    var depth = targetDepths[i$2];

    if (i$2 < 0) {
      continue;
    }

    from = $from.before(depth);
    to = $to.after(depth);
  }

  return this;
};

function closeFragment(fragment, depth, oldOpen, newOpen, parent) {
  if (depth < oldOpen) {
    var first = fragment.firstChild;
    fragment = fragment.replaceChild(0, first.copy(closeFragment(first.content, depth + 1, oldOpen, newOpen, first)));
  }

  if (depth > newOpen) {
    var match = parent.contentMatchAt(0);
    var start = match.fillBefore(fragment).append(fragment);
    fragment = start.append(match.matchFragment(start).fillBefore(_prosemirrorModel.Fragment.empty, true));
  }

  return fragment;
} // :: (number, number, Node) → this
// Replace the given range with a node, but use `from` and `to` as
// hints, rather than precise positions. When from and to are the same
// and are at the start or end of a parent node in which the given
// node doesn't fit, this method may _move_ them out towards a parent
// that does allow the given node to be placed. When the given range
// completely covers a parent node, this method may completely replace
// that parent node.


Transform.prototype.replaceRangeWith = function (from, to, node) {
  if (!node.isInline && from == to && this.doc.resolve(from).parent.content.size) {
    var point = insertPoint(this.doc, from, node.type);

    if (point != null) {
      from = to = point;
    }
  }

  return this.replaceRange(from, to, new _prosemirrorModel.Slice(_prosemirrorModel.Fragment.from(node), 0, 0));
}; // :: (number, number) → this
// Delete the given range, expanding it to cover fully covered
// parent nodes until a valid replace is found.


Transform.prototype.deleteRange = function (from, to) {
  var $from = this.doc.resolve(from),
      $to = this.doc.resolve(to);
  var covered = coveredDepths($from, $to);

  for (var i = 0; i < covered.length; i++) {
    var depth = covered[i],
        last = i == covered.length - 1;

    if (last && depth == 0 || $from.node(depth).type.contentMatch.validEnd) {
      return this.delete($from.start(depth), $to.end(depth));
    }

    if (depth > 0 && (last || $from.node(depth - 1).canReplace($from.index(depth - 1), $to.indexAfter(depth - 1)))) {
      return this.delete($from.before(depth), $to.after(depth));
    }
  }

  for (var d = 1; d <= $from.depth && d <= $to.depth; d++) {
    if (from - $from.start(d) == $from.depth - d && to > $from.end(d) && $to.end(d) - to != $to.depth - d) {
      return this.delete($from.before(d), to);
    }
  }

  return this.delete(from, to);
}; // : (ResolvedPos, ResolvedPos) → [number]
// Returns an array of all depths for which $from - $to spans the
// whole content of the nodes at that depth.


function coveredDepths($from, $to) {
  var result = [],
      minDepth = Math.min($from.depth, $to.depth);

  for (var d = minDepth; d >= 0; d--) {
    var start = $from.start(d);

    if (start < $from.pos - ($from.depth - d) || $to.end(d) > $to.pos + ($to.depth - d) || $from.node(d).type.spec.isolating || $to.node(d).type.spec.isolating) {
      break;
    }

    if (start == $to.start(d)) {
      result.push(d);
    }
  }

  return result;
}
},{"prosemirror-model":"../node_modules/prosemirror-model/dist/index.es.js"}],"../node_modules/prosemirror-state/dist/index.es.js":[function(require,module,exports) {
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Transaction = exports.TextSelection = exports.SelectionRange = exports.Selection = exports.PluginKey = exports.Plugin = exports.NodeSelection = exports.EditorState = exports.AllSelection = void 0;

var _prosemirrorModel = require("prosemirror-model");

var _prosemirrorTransform = require("prosemirror-transform");

var classesById = Object.create(null); // ::- Superclass for editor selections. Every selection type should
// extend this. Should not be instantiated directly.

var Selection = function Selection($anchor, $head, ranges) {
  // :: [SelectionRange]
  // The ranges covered by the selection.
  this.ranges = ranges || [new SelectionRange($anchor.min($head), $anchor.max($head))]; // :: ResolvedPos
  // The resolved anchor of the selection (the side that stays in
  // place when the selection is modified).

  this.$anchor = $anchor; // :: ResolvedPos
  // The resolved head of the selection (the side that moves when
  // the selection is modified).

  this.$head = $head;
};

exports.Selection = Selection;
var prototypeAccessors = {
  anchor: {
    configurable: true
  },
  head: {
    configurable: true
  },
  from: {
    configurable: true
  },
  to: {
    configurable: true
  },
  $from: {
    configurable: true
  },
  $to: {
    configurable: true
  },
  empty: {
    configurable: true
  }
}; // :: number
// The selection's anchor, as an unresolved position.

prototypeAccessors.anchor.get = function () {
  return this.$anchor.pos;
}; // :: number
// The selection's head.


prototypeAccessors.head.get = function () {
  return this.$head.pos;
}; // :: number
// The lower bound of the selection's main range.


prototypeAccessors.from.get = function () {
  return this.$from.pos;
}; // :: number
// The upper bound of the selection's main range.


prototypeAccessors.to.get = function () {
  return this.$to.pos;
}; // :: ResolvedPos
// The resolved lowerbound of the selection's main range.


prototypeAccessors.$from.get = function () {
  return this.ranges[0].$from;
}; // :: ResolvedPos
// The resolved upper bound of the selection's main range.


prototypeAccessors.$to.get = function () {
  return this.ranges[0].$to;
}; // :: bool
// Indicates whether the selection contains any content.


prototypeAccessors.empty.get = function () {
  var ranges = this.ranges;

  for (var i = 0; i < ranges.length; i++) {
    if (ranges[i].$from.pos != ranges[i].$to.pos) {
      return false;
    }
  }

  return true;
}; // eq:: (Selection) → bool
// Test whether the selection is the same as another selection.
// map:: (doc: Node, mapping: Mappable) → Selection
// Map this selection through a [mappable](#transform.Mappable) thing. `doc`
// should be the new document to which we are mapping.
// :: () → Slice
// Get the content of this selection as a slice.


Selection.prototype.content = function content() {
  return this.$from.node(0).slice(this.from, this.to, true);
}; // :: (Transaction, ?Slice)
// Replace the selection with a slice or, if no slice is given,
// delete the selection. Will append to the given transaction.


Selection.prototype.replace = function replace(tr, content) {
  if (content === void 0) content = _prosemirrorModel.Slice.empty; // Put the new selection at the position after the inserted
  // content. When that ended in an inline node, search backwards,
  // to get the position after that node. If not, search forward.

  var lastNode = content.content.lastChild,
      lastParent = null;

  for (var i = 0; i < content.openEnd; i++) {
    lastParent = lastNode;
    lastNode = lastNode.lastChild;
  }

  var mapFrom = tr.steps.length,
      ranges = this.ranges;

  for (var i$1 = 0; i$1 < ranges.length; i$1++) {
    var ref = ranges[i$1];
    var $from = ref.$from;
    var $to = ref.$to;
    var mapping = tr.mapping.slice(mapFrom);
    tr.replaceRange(mapping.map($from.pos), mapping.map($to.pos), i$1 ? _prosemirrorModel.Slice.empty : content);

    if (i$1 == 0) {
      selectionToInsertionEnd(tr, mapFrom, (lastNode ? lastNode.isInline : lastParent && lastParent.isTextblock) ? -1 : 1);
    }
  }
}; // :: (Transaction, Node)
// Replace the selection with the given node, appending the changes
// to the given transaction.


Selection.prototype.replaceWith = function replaceWith(tr, node) {
  var mapFrom = tr.steps.length,
      ranges = this.ranges;

  for (var i = 0; i < ranges.length; i++) {
    var ref = ranges[i];
    var $from = ref.$from;
    var $to = ref.$to;
    var mapping = tr.mapping.slice(mapFrom);
    var from = mapping.map($from.pos),
        to = mapping.map($to.pos);

    if (i) {
      tr.deleteRange(from, to);
    } else {
      tr.replaceRangeWith(from, to, node);
      selectionToInsertionEnd(tr, mapFrom, node.isInline ? -1 : 1);
    }
  }
}; // toJSON:: () → Object
// Convert the selection to a JSON representation. When implementing
// this for a custom selection class, make sure to give the object a
// `type` property whose value matches the ID under which you
// [registered](#state.Selection^jsonID) your class.
// :: (ResolvedPos, number, ?bool) → ?Selection
// Find a valid cursor or leaf node selection starting at the given
// position and searching back if `dir` is negative, and forward if
// positive. When `textOnly` is true, only consider cursor
// selections. Will return null when no valid selection position is
// found.


Selection.findFrom = function findFrom($pos, dir, textOnly) {
  var inner = $pos.parent.inlineContent ? new TextSelection($pos) : findSelectionIn($pos.node(0), $pos.parent, $pos.pos, $pos.index(), dir, textOnly);

  if (inner) {
    return inner;
  }

  for (var depth = $pos.depth - 1; depth >= 0; depth--) {
    var found = dir < 0 ? findSelectionIn($pos.node(0), $pos.node(depth), $pos.before(depth + 1), $pos.index(depth), dir, textOnly) : findSelectionIn($pos.node(0), $pos.node(depth), $pos.after(depth + 1), $pos.index(depth) + 1, dir, textOnly);

    if (found) {
      return found;
    }
  }
}; // :: (ResolvedPos, ?number) → Selection
// Find a valid cursor or leaf node selection near the given
// position. Searches forward first by default, but if `bias` is
// negative, it will search backwards first.


Selection.near = function near($pos, bias) {
  if (bias === void 0) bias = 1;
  return this.findFrom($pos, bias) || this.findFrom($pos, -bias) || new AllSelection($pos.node(0));
}; // :: (Node) → Selection
// Find the cursor or leaf node selection closest to the start of
// the given document. Will return an
// [`AllSelection`](#state.AllSelection) if no valid position
// exists.


Selection.atStart = function atStart(doc) {
  return findSelectionIn(doc, doc, 0, 0, 1) || new AllSelection(doc);
}; // :: (Node) → Selection
// Find the cursor or leaf node selection closest to the end of the
// given document.


Selection.atEnd = function atEnd(doc) {
  return findSelectionIn(doc, doc, doc.content.size, doc.childCount, -1) || new AllSelection(doc);
}; // :: (Node, Object) → Selection
// Deserialize the JSON representation of a selection. Must be
// implemented for custom classes (as a static class method).


Selection.fromJSON = function fromJSON(doc, json) {
  if (!json || !json.type) {
    throw new RangeError("Invalid input for Selection.fromJSON");
  }

  var cls = classesById[json.type];

  if (!cls) {
    throw new RangeError("No selection type " + json.type + " defined");
  }

  return cls.fromJSON(doc, json);
}; // :: (string, constructor<Selection>)
// To be able to deserialize selections from JSON, custom selection
// classes must register themselves with an ID string, so that they
// can be disambiguated. Try to pick something that's unlikely to
// clash with classes from other modules.


Selection.jsonID = function jsonID(id, selectionClass) {
  if (id in classesById) {
    throw new RangeError("Duplicate use of selection JSON ID " + id);
  }

  classesById[id] = selectionClass;
  selectionClass.prototype.jsonID = id;
  return selectionClass;
}; // :: () → SelectionBookmark
// Get a [bookmark](#state.SelectionBookmark) for this selection,
// which is a value that can be mapped without having access to a
// current document, and later resolved to a real selection for a
// given document again. (This is used mostly by the history to
// track and restore old selections.) The default implementation of
// this method just converts the selection to a text selection and
// returns the bookmark for that.


Selection.prototype.getBookmark = function getBookmark() {
  return TextSelection.between(this.$anchor, this.$head).getBookmark();
};

Object.defineProperties(Selection.prototype, prototypeAccessors); // :: bool
// Controls whether, when a selection of this type is active in the
// browser, the selected range should be visible to the user. Defaults
// to `true`.

Selection.prototype.visible = true; // SelectionBookmark:: interface
// A lightweight, document-independent representation of a selection.
// You can define a custom bookmark type for a custom selection class
// to make the history handle it well.
//
//   map:: (mapping: Mapping) → SelectionBookmark
//   Map the bookmark through a set of changes.
//
//   resolve:: (doc: Node) → Selection
//   Resolve the bookmark to a real selection again. This may need to
//   do some error checking and may fall back to a default (usually
//   [`TextSelection.between`](#state.TextSelection^between)) if
//   mapping made the bookmark invalid.
// ::- Represents a selected range in a document.

var SelectionRange = function SelectionRange($from, $to) {
  // :: ResolvedPos
  // The lower bound of the range.
  this.$from = $from; // :: ResolvedPos
  // The upper bound of the range.

  this.$to = $to;
}; // ::- A text selection represents a classical editor selection, with
// a head (the moving side) and anchor (immobile side), both of which
// point into textblock nodes. It can be empty (a regular cursor
// position).


exports.SelectionRange = SelectionRange;

var TextSelection = /*@__PURE__*/function (Selection) {
  function TextSelection($anchor, $head) {
    if ($head === void 0) $head = $anchor;
    Selection.call(this, $anchor, $head);
  }

  if (Selection) TextSelection.__proto__ = Selection;
  TextSelection.prototype = Object.create(Selection && Selection.prototype);
  TextSelection.prototype.constructor = TextSelection;
  var prototypeAccessors$1 = {
    $cursor: {
      configurable: true
    }
  }; // :: ?ResolvedPos
  // Returns a resolved position if this is a cursor selection (an
  // empty text selection), and null otherwise.

  prototypeAccessors$1.$cursor.get = function () {
    return this.$anchor.pos == this.$head.pos ? this.$head : null;
  };

  TextSelection.prototype.map = function map(doc, mapping) {
    var $head = doc.resolve(mapping.map(this.head));

    if (!$head.parent.inlineContent) {
      return Selection.near($head);
    }

    var $anchor = doc.resolve(mapping.map(this.anchor));
    return new TextSelection($anchor.parent.inlineContent ? $anchor : $head, $head);
  };

  TextSelection.prototype.replace = function replace(tr, content) {
    if (content === void 0) content = _prosemirrorModel.Slice.empty;
    Selection.prototype.replace.call(this, tr, content);

    if (content == _prosemirrorModel.Slice.empty) {
      var marks = this.$from.marksAcross(this.$to);

      if (marks) {
        tr.ensureMarks(marks);
      }
    }
  };

  TextSelection.prototype.eq = function eq(other) {
    return other instanceof TextSelection && other.anchor == this.anchor && other.head == this.head;
  };

  TextSelection.prototype.getBookmark = function getBookmark() {
    return new TextBookmark(this.anchor, this.head);
  };

  TextSelection.prototype.toJSON = function toJSON() {
    return {
      type: "text",
      anchor: this.anchor,
      head: this.head
    };
  };

  TextSelection.fromJSON = function fromJSON(doc, json) {
    if (typeof json.anchor != "number" || typeof json.head != "number") {
      throw new RangeError("Invalid input for TextSelection.fromJSON");
    }

    return new TextSelection(doc.resolve(json.anchor), doc.resolve(json.head));
  }; // :: (Node, number, ?number) → TextSelection
  // Create a text selection from non-resolved positions.


  TextSelection.create = function create(doc, anchor, head) {
    if (head === void 0) head = anchor;
    var $anchor = doc.resolve(anchor);
    return new this($anchor, head == anchor ? $anchor : doc.resolve(head));
  }; // :: (ResolvedPos, ResolvedPos, ?number) → Selection
  // Return a text selection that spans the given positions or, if
  // they aren't text positions, find a text selection near them.
  // `bias` determines whether the method searches forward (default)
  // or backwards (negative number) first. Will fall back to calling
  // [`Selection.near`](#state.Selection^near) when the document
  // doesn't contain a valid text position.


  TextSelection.between = function between($anchor, $head, bias) {
    var dPos = $anchor.pos - $head.pos;

    if (!bias || dPos) {
      bias = dPos >= 0 ? 1 : -1;
    }

    if (!$head.parent.inlineContent) {
      var found = Selection.findFrom($head, bias, true) || Selection.findFrom($head, -bias, true);

      if (found) {
        $head = found.$head;
      } else {
        return Selection.near($head, bias);
      }
    }

    if (!$anchor.parent.inlineContent) {
      if (dPos == 0) {
        $anchor = $head;
      } else {
        $anchor = (Selection.findFrom($anchor, -bias, true) || Selection.findFrom($anchor, bias, true)).$anchor;

        if ($anchor.pos < $head.pos != dPos < 0) {
          $anchor = $head;
        }
      }
    }

    return new TextSelection($anchor, $head);
  };

  Object.defineProperties(TextSelection.prototype, prototypeAccessors$1);
  return TextSelection;
}(Selection);

exports.TextSelection = TextSelection;
Selection.jsonID("text", TextSelection);

var TextBookmark = function TextBookmark(anchor, head) {
  this.anchor = anchor;
  this.head = head;
};

TextBookmark.prototype.map = function map(mapping) {
  return new TextBookmark(mapping.map(this.anchor), mapping.map(this.head));
};

TextBookmark.prototype.resolve = function resolve(doc) {
  return TextSelection.between(doc.resolve(this.anchor), doc.resolve(this.head));
}; // ::- A node selection is a selection that points at a single node.
// All nodes marked [selectable](#model.NodeSpec.selectable) can be
// the target of a node selection. In such a selection, `from` and
// `to` point directly before and after the selected node, `anchor`
// equals `from`, and `head` equals `to`..


var NodeSelection = /*@__PURE__*/function (Selection) {
  function NodeSelection($pos) {
    var node = $pos.nodeAfter;
    var $end = $pos.node(0).resolve($pos.pos + node.nodeSize);
    Selection.call(this, $pos, $end); // :: Node The selected node.

    this.node = node;
  }

  if (Selection) NodeSelection.__proto__ = Selection;
  NodeSelection.prototype = Object.create(Selection && Selection.prototype);
  NodeSelection.prototype.constructor = NodeSelection;

  NodeSelection.prototype.map = function map(doc, mapping) {
    var ref = mapping.mapResult(this.anchor);
    var deleted = ref.deleted;
    var pos = ref.pos;
    var $pos = doc.resolve(pos);

    if (deleted) {
      return Selection.near($pos);
    }

    return new NodeSelection($pos);
  };

  NodeSelection.prototype.content = function content() {
    return new _prosemirrorModel.Slice(_prosemirrorModel.Fragment.from(this.node), 0, 0);
  };

  NodeSelection.prototype.eq = function eq(other) {
    return other instanceof NodeSelection && other.anchor == this.anchor;
  };

  NodeSelection.prototype.toJSON = function toJSON() {
    return {
      type: "node",
      anchor: this.anchor
    };
  };

  NodeSelection.prototype.getBookmark = function getBookmark() {
    return new NodeBookmark(this.anchor);
  };

  NodeSelection.fromJSON = function fromJSON(doc, json) {
    if (typeof json.anchor != "number") {
      throw new RangeError("Invalid input for NodeSelection.fromJSON");
    }

    return new NodeSelection(doc.resolve(json.anchor));
  }; // :: (Node, number) → NodeSelection
  // Create a node selection from non-resolved positions.


  NodeSelection.create = function create(doc, from) {
    return new this(doc.resolve(from));
  }; // :: (Node) → bool
  // Determines whether the given node may be selected as a node
  // selection.


  NodeSelection.isSelectable = function isSelectable(node) {
    return !node.isText && node.type.spec.selectable !== false;
  };

  return NodeSelection;
}(Selection);

exports.NodeSelection = NodeSelection;
NodeSelection.prototype.visible = false;
Selection.jsonID("node", NodeSelection);

var NodeBookmark = function NodeBookmark(anchor) {
  this.anchor = anchor;
};

NodeBookmark.prototype.map = function map(mapping) {
  var ref = mapping.mapResult(this.anchor);
  var deleted = ref.deleted;
  var pos = ref.pos;
  return deleted ? new TextBookmark(pos, pos) : new NodeBookmark(pos);
};

NodeBookmark.prototype.resolve = function resolve(doc) {
  var $pos = doc.resolve(this.anchor),
      node = $pos.nodeAfter;

  if (node && NodeSelection.isSelectable(node)) {
    return new NodeSelection($pos);
  }

  return Selection.near($pos);
}; // ::- A selection type that represents selecting the whole document
// (which can not necessarily be expressed with a text selection, when
// there are for example leaf block nodes at the start or end of the
// document).


var AllSelection = /*@__PURE__*/function (Selection) {
  function AllSelection(doc) {
    Selection.call(this, doc.resolve(0), doc.resolve(doc.content.size));
  }

  if (Selection) AllSelection.__proto__ = Selection;
  AllSelection.prototype = Object.create(Selection && Selection.prototype);
  AllSelection.prototype.constructor = AllSelection;

  AllSelection.prototype.replace = function replace(tr, content) {
    if (content === void 0) content = _prosemirrorModel.Slice.empty;

    if (content == _prosemirrorModel.Slice.empty) {
      tr.delete(0, tr.doc.content.size);
      var sel = Selection.atStart(tr.doc);

      if (!sel.eq(tr.selection)) {
        tr.setSelection(sel);
      }
    } else {
      Selection.prototype.replace.call(this, tr, content);
    }
  };

  AllSelection.prototype.toJSON = function toJSON() {
    return {
      type: "all"
    };
  };

  AllSelection.fromJSON = function fromJSON(doc) {
    return new AllSelection(doc);
  };

  AllSelection.prototype.map = function map(doc) {
    return new AllSelection(doc);
  };

  AllSelection.prototype.eq = function eq(other) {
    return other instanceof AllSelection;
  };

  AllSelection.prototype.getBookmark = function getBookmark() {
    return AllBookmark;
  };

  return AllSelection;
}(Selection);

exports.AllSelection = AllSelection;
Selection.jsonID("all", AllSelection);
var AllBookmark = {
  map: function map() {
    return this;
  },
  resolve: function resolve(doc) {
    return new AllSelection(doc);
  }
}; // FIXME we'll need some awareness of text direction when scanning for selections
// Try to find a selection inside the given node. `pos` points at the
// position where the search starts. When `text` is true, only return
// text selections.

function findSelectionIn(doc, node, pos, index, dir, text) {
  if (node.inlineContent) {
    return TextSelection.create(doc, pos);
  }

  for (var i = index - (dir > 0 ? 0 : 1); dir > 0 ? i < node.childCount : i >= 0; i += dir) {
    var child = node.child(i);

    if (!child.isAtom) {
      var inner = findSelectionIn(doc, child, pos + dir, dir < 0 ? child.childCount : 0, dir, text);

      if (inner) {
        return inner;
      }
    } else if (!text && NodeSelection.isSelectable(child)) {
      return NodeSelection.create(doc, pos - (dir < 0 ? child.nodeSize : 0));
    }

    pos += child.nodeSize * dir;
  }
}

function selectionToInsertionEnd(tr, startLen, bias) {
  var last = tr.steps.length - 1;

  if (last < startLen) {
    return;
  }

  var step = tr.steps[last];

  if (!(step instanceof _prosemirrorTransform.ReplaceStep || step instanceof _prosemirrorTransform.ReplaceAroundStep)) {
    return;
  }

  var map = tr.mapping.maps[last],
      end;
  map.forEach(function (_from, _to, _newFrom, newTo) {
    if (end == null) {
      end = newTo;
    }
  });
  tr.setSelection(Selection.near(tr.doc.resolve(end), bias));
}

var UPDATED_SEL = 1,
    UPDATED_MARKS = 2,
    UPDATED_SCROLL = 4; // ::- An editor state transaction, which can be applied to a state to
// create an updated state. Use
// [`EditorState.tr`](#state.EditorState.tr) to create an instance.
//
// Transactions track changes to the document (they are a subclass of
// [`Transform`](#transform.Transform)), but also other state changes,
// like selection updates and adjustments of the set of [stored
// marks](#state.EditorState.storedMarks). In addition, you can store
// metadata properties in a transaction, which are extra pieces of
// information that client code or plugins can use to describe what a
// transacion represents, so that they can update their [own
// state](#state.StateField) accordingly.
//
// The [editor view](#view.EditorView) uses a few metadata properties:
// it will attach a property `"pointer"` with the value `true` to
// selection transactions directly caused by mouse or touch input, and
// a `"uiEvent"` property of that may be `"paste"`, `"cut"`, or `"drop"`.

var Transaction = /*@__PURE__*/function (Transform) {
  function Transaction(state) {
    Transform.call(this, state.doc); // :: number
    // The timestamp associated with this transaction, in the same
    // format as `Date.now()`.

    this.time = Date.now();
    this.curSelection = state.selection; // The step count for which the current selection is valid.

    this.curSelectionFor = 0; // :: ?[Mark]
    // The stored marks set by this transaction, if any.

    this.storedMarks = state.storedMarks; // Bitfield to track which aspects of the state were updated by
    // this transaction.

    this.updated = 0; // Object used to store metadata properties for the transaction.

    this.meta = Object.create(null);
  }

  if (Transform) Transaction.__proto__ = Transform;
  Transaction.prototype = Object.create(Transform && Transform.prototype);
  Transaction.prototype.constructor = Transaction;
  var prototypeAccessors = {
    selection: {
      configurable: true
    },
    selectionSet: {
      configurable: true
    },
    storedMarksSet: {
      configurable: true
    },
    isGeneric: {
      configurable: true
    },
    scrolledIntoView: {
      configurable: true
    }
  }; // :: Selection
  // The transaction's current selection. This defaults to the editor
  // selection [mapped](#state.Selection.map) through the steps in the
  // transaction, but can be overwritten with
  // [`setSelection`](#state.Transaction.setSelection).

  prototypeAccessors.selection.get = function () {
    if (this.curSelectionFor < this.steps.length) {
      this.curSelection = this.curSelection.map(this.doc, this.mapping.slice(this.curSelectionFor));
      this.curSelectionFor = this.steps.length;
    }

    return this.curSelection;
  }; // :: (Selection) → Transaction
  // Update the transaction's current selection. Will determine the
  // selection that the editor gets when the transaction is applied.


  Transaction.prototype.setSelection = function setSelection(selection) {
    if (selection.$from.doc != this.doc) {
      throw new RangeError("Selection passed to setSelection must point at the current document");
    }

    this.curSelection = selection;
    this.curSelectionFor = this.steps.length;
    this.updated = (this.updated | UPDATED_SEL) & ~UPDATED_MARKS;
    this.storedMarks = null;
    return this;
  }; // :: bool
  // Whether the selection was explicitly updated by this transaction.


  prototypeAccessors.selectionSet.get = function () {
    return (this.updated & UPDATED_SEL) > 0;
  }; // :: (?[Mark]) → Transaction
  // Set the current stored marks.


  Transaction.prototype.setStoredMarks = function setStoredMarks(marks) {
    this.storedMarks = marks;
    this.updated |= UPDATED_MARKS;
    return this;
  }; // :: ([Mark]) → Transaction
  // Make sure the current stored marks or, if that is null, the marks
  // at the selection, match the given set of marks. Does nothing if
  // this is already the case.


  Transaction.prototype.ensureMarks = function ensureMarks(marks) {
    if (!_prosemirrorModel.Mark.sameSet(this.storedMarks || this.selection.$from.marks(), marks)) {
      this.setStoredMarks(marks);
    }

    return this;
  }; // :: (Mark) → Transaction
  // Add a mark to the set of stored marks.


  Transaction.prototype.addStoredMark = function addStoredMark(mark) {
    return this.ensureMarks(mark.addToSet(this.storedMarks || this.selection.$head.marks()));
  }; // :: (union<Mark, MarkType>) → Transaction
  // Remove a mark or mark type from the set of stored marks.


  Transaction.prototype.removeStoredMark = function removeStoredMark(mark) {
    return this.ensureMarks(mark.removeFromSet(this.storedMarks || this.selection.$head.marks()));
  }; // :: bool
  // Whether the stored marks were explicitly set for this transaction.


  prototypeAccessors.storedMarksSet.get = function () {
    return (this.updated & UPDATED_MARKS) > 0;
  };

  Transaction.prototype.addStep = function addStep(step, doc) {
    Transform.prototype.addStep.call(this, step, doc);
    this.updated = this.updated & ~UPDATED_MARKS;
    this.storedMarks = null;
  }; // :: (number) → Transaction
  // Update the timestamp for the transaction.


  Transaction.prototype.setTime = function setTime(time) {
    this.time = time;
    return this;
  }; // :: (Slice) → Transaction
  // Replace the current selection with the given slice.


  Transaction.prototype.replaceSelection = function replaceSelection(slice) {
    this.selection.replace(this, slice);
    return this;
  }; // :: (Node, ?bool) → Transaction
  // Replace the selection with the given node. When `inheritMarks` is
  // true and the content is inline, it inherits the marks from the
  // place where it is inserted.


  Transaction.prototype.replaceSelectionWith = function replaceSelectionWith(node, inheritMarks) {
    var selection = this.selection;

    if (inheritMarks !== false) {
      node = node.mark(this.storedMarks || (selection.empty ? selection.$from.marks() : selection.$from.marksAcross(selection.$to) || _prosemirrorModel.Mark.none));
    }

    selection.replaceWith(this, node);
    return this;
  }; // :: () → Transaction
  // Delete the selection.


  Transaction.prototype.deleteSelection = function deleteSelection() {
    this.selection.replace(this);
    return this;
  }; // :: (string, from: ?number, to: ?number) → Transaction
  // Replace the given range, or the selection if no range is given,
  // with a text node containing the given string.


  Transaction.prototype.insertText = function insertText(text, from, to) {
    if (to === void 0) to = from;
    var schema = this.doc.type.schema;

    if (from == null) {
      if (!text) {
        return this.deleteSelection();
      }

      return this.replaceSelectionWith(schema.text(text), true);
    } else {
      if (!text) {
        return this.deleteRange(from, to);
      }

      var marks = this.storedMarks;

      if (!marks) {
        var $from = this.doc.resolve(from);
        marks = to == from ? $from.marks() : $from.marksAcross(this.doc.resolve(to));
      }

      this.replaceRangeWith(from, to, schema.text(text, marks));

      if (!this.selection.empty) {
        this.setSelection(Selection.near(this.selection.$to));
      }

      return this;
    }
  }; // :: (union<string, Plugin, PluginKey>, any) → Transaction
  // Store a metadata property in this transaction, keyed either by
  // name or by plugin.


  Transaction.prototype.setMeta = function setMeta(key, value) {
    this.meta[typeof key == "string" ? key : key.key] = value;
    return this;
  }; // :: (union<string, Plugin, PluginKey>) → any
  // Retrieve a metadata property for a given name or plugin.


  Transaction.prototype.getMeta = function getMeta(key) {
    return this.meta[typeof key == "string" ? key : key.key];
  }; // :: bool
  // Returns true if this transaction doesn't contain any metadata,
  // and can thus safely be extended.


  prototypeAccessors.isGeneric.get = function () {
    for (var _ in this.meta) {
      return false;
    }

    return true;
  }; // :: () → Transaction
  // Indicate that the editor should scroll the selection into view
  // when updated to the state produced by this transaction.


  Transaction.prototype.scrollIntoView = function scrollIntoView() {
    this.updated |= UPDATED_SCROLL;
    return this;
  };

  prototypeAccessors.scrolledIntoView.get = function () {
    return (this.updated & UPDATED_SCROLL) > 0;
  };

  Object.defineProperties(Transaction.prototype, prototypeAccessors);
  return Transaction;
}(_prosemirrorTransform.Transform);

exports.Transaction = Transaction;

function bind(f, self) {
  return !self || !f ? f : f.bind(self);
}

var FieldDesc = function FieldDesc(name, desc, self) {
  this.name = name;
  this.init = bind(desc.init, self);
  this.apply = bind(desc.apply, self);
};

var baseFields = [new FieldDesc("doc", {
  init: function init(config) {
    return config.doc || config.schema.topNodeType.createAndFill();
  },
  apply: function apply(tr) {
    return tr.doc;
  }
}), new FieldDesc("selection", {
  init: function init(config, instance) {
    return config.selection || Selection.atStart(instance.doc);
  },
  apply: function apply(tr) {
    return tr.selection;
  }
}), new FieldDesc("storedMarks", {
  init: function init(config) {
    return config.storedMarks || null;
  },
  apply: function apply(tr, _marks, _old, state) {
    return state.selection.$cursor ? tr.storedMarks : null;
  }
}), new FieldDesc("scrollToSelection", {
  init: function init() {
    return 0;
  },
  apply: function apply(tr, prev) {
    return tr.scrolledIntoView ? prev + 1 : prev;
  }
})]; // Object wrapping the part of a state object that stays the same
// across transactions. Stored in the state's `config` property.

var Configuration = function Configuration(schema, plugins) {
  var this$1 = this;
  this.schema = schema;
  this.fields = baseFields.concat();
  this.plugins = [];
  this.pluginsByKey = Object.create(null);

  if (plugins) {
    plugins.forEach(function (plugin) {
      if (this$1.pluginsByKey[plugin.key]) {
        throw new RangeError("Adding different instances of a keyed plugin (" + plugin.key + ")");
      }

      this$1.plugins.push(plugin);
      this$1.pluginsByKey[plugin.key] = plugin;

      if (plugin.spec.state) {
        this$1.fields.push(new FieldDesc(plugin.key, plugin.spec.state, plugin));
      }
    });
  }
}; // ::- The state of a ProseMirror editor is represented by an object
// of this type. A state is a persistent data structure—it isn't
// updated, but rather a new state value is computed from an old one
// using the [`apply`](#state.EditorState.apply) method.
//
// A state holds a number of built-in fields, and plugins can
// [define](#state.PluginSpec.state) additional fields.


var EditorState = function EditorState(config) {
  this.config = config;
};

exports.EditorState = EditorState;
var prototypeAccessors$1 = {
  schema: {
    configurable: true
  },
  plugins: {
    configurable: true
  },
  tr: {
    configurable: true
  }
}; // doc:: Node
// The current document.
// selection:: Selection
// The selection.
// storedMarks:: ?[Mark]
// A set of marks to apply to the next input. Will be null when
// no explicit marks have been set.
// :: Schema
// The schema of the state's document.

prototypeAccessors$1.schema.get = function () {
  return this.config.schema;
}; // :: [Plugin]
// The plugins that are active in this state.


prototypeAccessors$1.plugins.get = function () {
  return this.config.plugins;
}; // :: (Transaction) → EditorState
// Apply the given transaction to produce a new state.


EditorState.prototype.apply = function apply(tr) {
  return this.applyTransaction(tr).state;
}; // : (Transaction) → bool


EditorState.prototype.filterTransaction = function filterTransaction(tr, ignore) {
  if (ignore === void 0) ignore = -1;

  for (var i = 0; i < this.config.plugins.length; i++) {
    if (i != ignore) {
      var plugin = this.config.plugins[i];

      if (plugin.spec.filterTransaction && !plugin.spec.filterTransaction.call(plugin, tr, this)) {
        return false;
      }
    }
  }

  return true;
}; // :: (Transaction) → {state: EditorState, transactions: [Transaction]}
// Verbose variant of [`apply`](#state.EditorState.apply) that
// returns the precise transactions that were applied (which might
// be influenced by the [transaction
// hooks](#state.PluginSpec.filterTransaction) of
// plugins) along with the new state.


EditorState.prototype.applyTransaction = function applyTransaction(rootTr) {
  if (!this.filterTransaction(rootTr)) {
    return {
      state: this,
      transactions: []
    };
  }

  var trs = [rootTr],
      newState = this.applyInner(rootTr),
      seen = null; // This loop repeatedly gives plugins a chance to respond to
  // transactions as new transactions are added, making sure to only
  // pass the transactions the plugin did not see before.

  for (;;) {
    var haveNew = false;

    for (var i = 0; i < this.config.plugins.length; i++) {
      var plugin = this.config.plugins[i];

      if (plugin.spec.appendTransaction) {
        var n = seen ? seen[i].n : 0,
            oldState = seen ? seen[i].state : this;
        var tr = n < trs.length && plugin.spec.appendTransaction.call(plugin, n ? trs.slice(n) : trs, oldState, newState);

        if (tr && newState.filterTransaction(tr, i)) {
          tr.setMeta("appendedTransaction", rootTr);

          if (!seen) {
            seen = [];

            for (var j = 0; j < this.config.plugins.length; j++) {
              seen.push(j < i ? {
                state: newState,
                n: trs.length
              } : {
                state: this,
                n: 0
              });
            }
          }

          trs.push(tr);
          newState = newState.applyInner(tr);
          haveNew = true;
        }

        if (seen) {
          seen[i] = {
            state: newState,
            n: trs.length
          };
        }
      }
    }

    if (!haveNew) {
      return {
        state: newState,
        transactions: trs
      };
    }
  }
}; // : (Transaction) → EditorState


EditorState.prototype.applyInner = function applyInner(tr) {
  if (!tr.before.eq(this.doc)) {
    throw new RangeError("Applying a mismatched transaction");
  }

  var newInstance = new EditorState(this.config),
      fields = this.config.fields;

  for (var i = 0; i < fields.length; i++) {
    var field = fields[i];
    newInstance[field.name] = field.apply(tr, this[field.name], this, newInstance);
  }

  for (var i$1 = 0; i$1 < applyListeners.length; i$1++) {
    applyListeners[i$1](this, tr, newInstance);
  }

  return newInstance;
}; // :: Transaction
// Start a [transaction](#state.Transaction) from this state.


prototypeAccessors$1.tr.get = function () {
  return new Transaction(this);
}; // :: (Object) → EditorState
// Create a new state.
//
// config::- Configuration options. Must contain `schema` or `doc` (or both).
//
//    schema:: ?Schema
//    The schema to use.
//
//    doc:: ?Node
//    The starting document.
//
//    selection:: ?Selection
//    A valid selection in the document.
//
//    storedMarks:: ?[Mark]
//    The initial set of [stored marks](#state.EditorState.storedMarks).
//
//    plugins:: ?[Plugin]
//    The plugins that should be active in this state.


EditorState.create = function create(config) {
  var $config = new Configuration(config.schema || config.doc.type.schema, config.plugins);
  var instance = new EditorState($config);

  for (var i = 0; i < $config.fields.length; i++) {
    instance[$config.fields[i].name] = $config.fields[i].init(config, instance);
  }

  return instance;
}; // :: (Object) → EditorState
// Create a new state based on this one, but with an adjusted set of
// active plugins. State fields that exist in both sets of plugins
// are kept unchanged. Those that no longer exist are dropped, and
// those that are new are initialized using their
// [`init`](#state.StateField.init) method, passing in the new
// configuration object..
//
// config::- configuration options
//
//   schema:: ?Schema
//   New schema to use.
//
//   plugins:: ?[Plugin]
//   New set of active plugins.


EditorState.prototype.reconfigure = function reconfigure(config) {
  var $config = new Configuration(config.schema || this.schema, config.plugins);
  var fields = $config.fields,
      instance = new EditorState($config);

  for (var i = 0; i < fields.length; i++) {
    var name = fields[i].name;
    instance[name] = this.hasOwnProperty(name) ? this[name] : fields[i].init(config, instance);
  }

  return instance;
}; // :: (?union<Object<Plugin>, string, number>) → Object
// Serialize this state to JSON. If you want to serialize the state
// of plugins, pass an object mapping property names to use in the
// resulting JSON object to plugin objects. The argument may also be
// a string or number, in which case it is ignored, to support the
// way `JSON.stringify` calls `toString` methods.


EditorState.prototype.toJSON = function toJSON(pluginFields) {
  var result = {
    doc: this.doc.toJSON(),
    selection: this.selection.toJSON()
  };

  if (this.storedMarks) {
    result.storedMarks = this.storedMarks.map(function (m) {
      return m.toJSON();
    });
  }

  if (pluginFields && typeof pluginFields == 'object') {
    for (var prop in pluginFields) {
      if (prop == "doc" || prop == "selection") {
        throw new RangeError("The JSON fields `doc` and `selection` are reserved");
      }

      var plugin = pluginFields[prop],
          state = plugin.spec.state;

      if (state && state.toJSON) {
        result[prop] = state.toJSON.call(plugin, this[plugin.key]);
      }
    }
  }

  return result;
}; // :: (Object, Object, ?Object<Plugin>) → EditorState
// Deserialize a JSON representation of a state. `config` should
// have at least a `schema` field, and should contain array of
// plugins to initialize the state with. `pluginFields` can be used
// to deserialize the state of plugins, by associating plugin
// instances with the property names they use in the JSON object.
//
// config::- configuration options
//
//   schema:: Schema
//   The schema to use.
//
//   plugins:: ?[Plugin]
//   The set of active plugins.


EditorState.fromJSON = function fromJSON(config, json, pluginFields) {
  if (!json) {
    throw new RangeError("Invalid input for EditorState.fromJSON");
  }

  if (!config.schema) {
    throw new RangeError("Required config field 'schema' missing");
  }

  var $config = new Configuration(config.schema, config.plugins);
  var instance = new EditorState($config);
  $config.fields.forEach(function (field) {
    if (field.name == "doc") {
      instance.doc = _prosemirrorModel.Node.fromJSON(config.schema, json.doc);
    } else if (field.name == "selection") {
      instance.selection = Selection.fromJSON(instance.doc, json.selection);
    } else if (field.name == "storedMarks") {
      if (json.storedMarks) {
        instance.storedMarks = json.storedMarks.map(config.schema.markFromJSON);
      }
    } else {
      if (pluginFields) {
        for (var prop in pluginFields) {
          var plugin = pluginFields[prop],
              state = plugin.spec.state;

          if (plugin.key == field.name && state && state.fromJSON && Object.prototype.hasOwnProperty.call(json, prop)) {
            // This field belongs to a plugin mapped to a JSON field, read it from there.
            instance[field.name] = state.fromJSON.call(plugin, config, json[prop], instance);
            return;
          }
        }
      }

      instance[field.name] = field.init(config, instance);
    }
  });
  return instance;
}; // Kludge to allow the view to track mappings between different
// instances of a state.
//
// FIXME this is no longer needed as of prosemirror-view 1.9.0,
// though due to backwards-compat we should probably keep it around
// for a while (if only as a no-op)


EditorState.addApplyListener = function addApplyListener(f) {
  applyListeners.push(f);
};

EditorState.removeApplyListener = function removeApplyListener(f) {
  var found = applyListeners.indexOf(f);

  if (found > -1) {
    applyListeners.splice(found, 1);
  }
};

Object.defineProperties(EditorState.prototype, prototypeAccessors$1);
var applyListeners = []; // PluginSpec:: interface
//
// This is the type passed to the [`Plugin`](#state.Plugin)
// constructor. It provides a definition for a plugin.
//
//   props:: ?EditorProps
//   The [view props](#view.EditorProps) added by this plugin. Props
//   that are functions will be bound to have the plugin instance as
//   their `this` binding.
//
//   state:: ?StateField<any>
//   Allows a plugin to define a [state field](#state.StateField), an
//   extra slot in the state object in which it can keep its own data.
//
//   key:: ?PluginKey
//   Can be used to make this a keyed plugin. You can have only one
//   plugin with a given key in a given state, but it is possible to
//   access the plugin's configuration and state through the key,
//   without having access to the plugin instance object.
//
//   view:: ?(EditorView) → Object
//   When the plugin needs to interact with the editor view, or
//   set something up in the DOM, use this field. The function
//   will be called when the plugin's state is associated with an
//   editor view.
//
//     return::-
//     Should return an object with the following optional
//     properties:
//
//       update:: ?(view: EditorView, prevState: EditorState)
//       Called whenever the view's state is updated.
//
//       destroy:: ?()
//       Called when the view is destroyed or receives a state
//       with different plugins.
//
//   filterTransaction:: ?(Transaction, EditorState) → bool
//   When present, this will be called before a transaction is
//   applied by the state, allowing the plugin to cancel it (by
//   returning false).
//
//   appendTransaction:: ?(transactions: [Transaction], oldState: EditorState, newState: EditorState) → ?Transaction
//   Allows the plugin to append another transaction to be applied
//   after the given array of transactions. When another plugin
//   appends a transaction after this was called, it is called again
//   with the new state and new transactions—but only the new
//   transactions, i.e. it won't be passed transactions that it
//   already saw.

function bindProps(obj, self, target) {
  for (var prop in obj) {
    var val = obj[prop];

    if (val instanceof Function) {
      val = val.bind(self);
    } else if (prop == "handleDOMEvents") {
      val = bindProps(val, self, {});
    }

    target[prop] = val;
  }

  return target;
} // ::- Plugins bundle functionality that can be added to an editor.
// They are part of the [editor state](#state.EditorState) and
// may influence that state and the view that contains it.


var Plugin = function Plugin(spec) {
  // :: EditorProps
  // The [props](#view.EditorProps) exported by this plugin.
  this.props = {};

  if (spec.props) {
    bindProps(spec.props, this, this.props);
  } // :: Object
  // The plugin's [spec object](#state.PluginSpec).


  this.spec = spec;
  this.key = spec.key ? spec.key.key : createKey("plugin");
}; // :: (EditorState) → any
// Extract the plugin's state field from an editor state.


exports.Plugin = Plugin;

Plugin.prototype.getState = function getState(state) {
  return state[this.key];
}; // StateField:: interface<T>
// A plugin spec may provide a state field (under its
// [`state`](#state.PluginSpec.state) property) of this type, which
// describes the state it wants to keep. Functions provided here are
// always called with the plugin instance as their `this` binding.
//
//   init:: (config: Object, instance: EditorState) → T
//   Initialize the value of the field. `config` will be the object
//   passed to [`EditorState.create`](#state.EditorState^create). Note
//   that `instance` is a half-initialized state instance, and will
//   not have values for plugin fields initialized after this one.
//
//   apply:: (tr: Transaction, value: T, oldState: EditorState, newState: EditorState) → T
//   Apply the given transaction to this state field, producing a new
//   field value. Note that the `newState` argument is again a partially
//   constructed state does not yet contain the state from plugins
//   coming after this one.
//
//   toJSON:: ?(value: T) → *
//   Convert this field to JSON. Optional, can be left off to disable
//   JSON serialization for the field.
//
//   fromJSON:: ?(config: Object, value: *, state: EditorState) → T
//   Deserialize the JSON representation of this field. Note that the
//   `state` argument is again a half-initialized state.


var keys = Object.create(null);

function createKey(name) {
  if (name in keys) {
    return name + "$" + ++keys[name];
  }

  keys[name] = 0;
  return name + "$";
} // ::- A key is used to [tag](#state.PluginSpec.key)
// plugins in a way that makes it possible to find them, given an
// editor state. Assigning a key does mean only one plugin of that
// type can be active in a state.


var PluginKey = function PluginKey(name) {
  if (name === void 0) name = "key";
  this.key = createKey(name);
}; // :: (EditorState) → ?Plugin
// Get the active plugin with this key, if any, from an editor
// state.


exports.PluginKey = PluginKey;

PluginKey.prototype.get = function get(state) {
  return state.config.pluginsByKey[this.key];
}; // :: (EditorState) → ?any
// Get the plugin's state from an editor state.


PluginKey.prototype.getState = function getState(state) {
  return state[this.key];
};
},{"prosemirror-model":"../node_modules/prosemirror-model/dist/index.es.js","prosemirror-transform":"../node_modules/prosemirror-transform/dist/index.es.js"}],"../src/state/get-editor-state.js":[function(require,module,exports) {
"use strict";

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

var _prosemirrorState = require("prosemirror-state");

function getEditorStateClass() {
  return _prosemirrorState.EditorState;
}
},{"prosemirror-state":"../node_modules/prosemirror-state/dist/index.es.js"}],"../node_modules/parcel/src/builtins/bundle-url.js":[function(require,module,exports) {
var bundleURL = null;

function getBundleURLCached() {
  if (!bundleURL) {
    bundleURL = getBundleURL();
  }

  return bundleURL;
}

function getBundleURL() {
  // Attempt to find the URL of the current script and use that as the base URL
  try {
    throw new Error();
  } catch (err) {
    var matches = ('' + err.stack).match(/(https?|file|ftp|chrome-extension|moz-extension):\/\/[^)\n]+/g);

    if (matches) {
      return getBaseURL(matches[0]);
    }
  }

  return '/';
}

function getBaseURL(url) {
  return ('' + url).replace(/^((?:https?|file|ftp|chrome-extension|moz-extension):\/\/.+)\/[^/]+$/, '$1') + '/';
}

exports.getBundleURL = getBundleURLCached;
exports.getBaseURL = getBaseURL;
},{}],"../node_modules/parcel/src/builtins/bundle-loader.js":[function(require,module,exports) {
var getBundleURL = require('./bundle-url').getBundleURL;

function loadBundlesLazy(bundles) {
  if (!Array.isArray(bundles)) {
    bundles = [bundles];
  }

  var id = bundles[bundles.length - 1];

  try {
    return Promise.resolve(require(id));
  } catch (err) {
    if (err.code === 'MODULE_NOT_FOUND') {
      return new LazyPromise(function (resolve, reject) {
        loadBundles(bundles.slice(0, -1)).then(function () {
          return require(id);
        }).then(resolve, reject);
      });
    }

    throw err;
  }
}

function loadBundles(bundles) {
  return Promise.all(bundles.map(loadBundle));
}

var bundleLoaders = {};

function registerBundleLoader(type, loader) {
  bundleLoaders[type] = loader;
}

module.exports = exports = loadBundlesLazy;
exports.load = loadBundles;
exports.register = registerBundleLoader;
var bundles = {};

function loadBundle(bundle) {
  var id;

  if (Array.isArray(bundle)) {
    id = bundle[1];
    bundle = bundle[0];
  }

  if (bundles[bundle]) {
    return bundles[bundle];
  }

  var type = (bundle.substring(bundle.lastIndexOf('.') + 1, bundle.length) || bundle).toLowerCase();
  var bundleLoader = bundleLoaders[type];

  if (bundleLoader) {
    return bundles[bundle] = bundleLoader(getBundleURL() + bundle).then(function (resolved) {
      if (resolved) {
        module.bundle.register(id, resolved);
      }

      return resolved;
    }).catch(function (e) {
      delete bundles[bundle];
      throw e;
    });
  }
}

function LazyPromise(executor) {
  this.executor = executor;
  this.promise = null;
}

LazyPromise.prototype.then = function (onSuccess, onError) {
  if (this.promise === null) this.promise = new Promise(this.executor);
  return this.promise.then(onSuccess, onError);
};

LazyPromise.prototype.catch = function (onError) {
  if (this.promise === null) this.promise = new Promise(this.executor);
  return this.promise.catch(onError);
};
},{"./bundle-url":"../node_modules/parcel/src/builtins/bundle-url.js"}],"../src/state/editor.js":[function(require,module,exports) {
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.calculateSafeIndex = calculateSafeIndex;
exports.buildColors = buildColors;
exports.findPMNode = findPMNode;
exports.getActiveMarks = getActiveMarks;
exports.buildSelection = buildSelection;
exports.createHistoryEntry = createHistoryEntry;
exports.shrinkEditorHistory = shrinkEditorHistory;
exports.updateEditorHistory = updateEditorHistory;
exports.default = void 0;

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _prosemirrorModel = require("prosemirror-model");

var _unstated = require("unstated");

var _html = require("html");

var _nanoid = _interopRequireDefault(require("nanoid"));

var _subscribeOnUpdates = _interopRequireDefault(require("../utils/subscribe-on-updates"));

var _findNode = _interopRequireWildcard(require("../utils/find-node"));

var _getEditorState = _interopRequireDefault(require("./get-editor-state"));

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (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; }

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

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 asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function () { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

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; }

var NODE_PICKER_DEFAULT = {
  top: 0,
  left: 0,
  width: 0,
  height: 0,
  active: false
};
var HISTORY_SIZE = 200;
var SNAPSHOTS_KEY = "prosemirror-dev-tools-snapshots";
var nodesColors = ["#EA7C7F", // red
"#67B0C6", // cyan 400
"#94BB7F", // green
"#CA9EDB", // deep purple
"#DCDC5D", // lime
"#B9CC7C", // light green
"#DD97D8", // purple
"#FFB761", // orange
"#4D8FD1", // light blue
"#F36E98", // pink
"#E45F44", // deep orange
"#A6A4AE", // blue grey
"#FCC047", // yellow
"#FFC129", // amber
"#D3929C", // can can
"#4CBCD4", // cyan
"#8D7BC0" // indigo
];

function calculateSafeIndex(index, total) {
  var quotient = index / total;
  return Math.round(total * (quotient - Math.floor(quotient)));
}

function buildColors(schema) {
  return Object.keys(schema.nodes).reduce(function (acc, node, index) {
    var safeIndex = index >= nodesColors.length ? calculateSafeIndex(index, nodesColors.length) : index;
    acc[node] = nodesColors[safeIndex];
    return acc;
  }, {});
}

function findPMNode(domNode) {
  var node;
  var target = domNode;

  while (!node && target) {
    if (target.pmViewDesc) {
      node = target;
    }

    target = target.parentNode;
  }

  return node;
}

function getActiveMarks(editorState) {
  var selection = editorState.selection;
  var marks = [];

  if (selection.empty) {
    marks = selection.storedMarks || selection.$from.marks();
  } else {
    editorState.doc.nodesBetween(selection.from, selection.to, function (node) {
      marks = marks.concat(node.marks);
    });
  }

  marks = marks.reduce(function (acc, mark) {
    if (acc.indexOf(mark) === -1) {
      acc.push(mark);
    }

    return acc;
  }, []).map(function (m) {
    return m.toJSON();
  });
  return marks;
}

function buildSelection(selection) {
  return {
    type: selection.type,
    empty: selection.empty,
    anchor: selection.anchor,
    head: selection.head,
    from: selection.from,
    to: selection.to
  };
}

function createHistoryEntry(editorState) {
  var serializer = _prosemirrorModel.DOMSerializer.fromSchema(editorState.schema);

  var selection = editorState.selection;
  var domFragment = serializer.serializeFragment(selection.content().content);
  var selectionContent = [];

  if (domFragment) {
    var child = domFragment.firstChild;

    while (child) {
      selectionContent.push(child.outerHTML);
      child = child.nextSibling;
    }
  }

  return {
    id: (0, _nanoid.default)(),
    state: editorState,
    timestamp: Date.now(),
    diffPending: true,
    diff: undefined,
    selection: undefined,
    selectionContent: (0, _html.prettyPrint)(selectionContent.join("\n"), {
      max_char: 60,
      indent_size: 2
    })
  };
}

function shrinkEditorHistory(history, historyRolledBackTo) {
  var startIndex = historyRolledBackTo !== false ? historyRolledBackTo : 0;
  return history.slice(startIndex, HISTORY_SIZE);
}

function updateEditorHistory(history, historyRolledBackTo, tr, newState) {
  var skipHistory = tr.getMeta("_skip-dev-tools-history_");
  if (skipHistory) return;
  var newHistory = shrinkEditorHistory(history, historyRolledBackTo);
  newHistory.unshift(createHistoryEntry(newState));
  return newHistory;
}

var EditorStateContainer = /*#__PURE__*/function (_Container) {
  _inherits(EditorStateContainer, _Container);

  var _super = _createSuper(EditorStateContainer);

  function EditorStateContainer(_editorView, props) {
    var _this;

    _classCallCheck(this, EditorStateContainer);

    _this = _super.call(this);

    _defineProperty(_assertThisInitialized(_this), "state", {
      EditorState: function EditorState() {},
      view: null,
      state: {},
      schema: {},
      nodeColors: {},
      activeMarks: [],
      history: [],
      expandPath: [],
      historyRolledBackTo: false,
      selectedHistoryItem: 0,
      snapshots: JSON.parse(window.localStorage.getItem(SNAPSHOTS_KEY)) || [],
      nodePicker: NODE_PICKER_DEFAULT
    });

    _defineProperty(_assertThisInitialized(_this), "activatePicker", function () {
      _this.setState({
        nodePicker: Object.assign({}, NODE_PICKER_DEFAULT, {
          active: true
        })
      });
    });

    _defineProperty(_assertThisInitialized(_this), "deactivatePicker", function () {
      var picker = _this.state.nodePicker;

      if (picker.onMouseOver) {
        document.removeEventListener("mouseover", picker.onMouseOver);
      }

      if (picker.onMouseOver) {
        document.removeEventListener("click", picker.onClick);
      }

      _this.setState({
        nodePicker: NODE_PICKER_DEFAULT
      });
    });

    _defineProperty(_assertThisInitialized(_this), "updateNodePickerPossition", function (target) {
      var node = findPMNode(target);

      if (node && (node.pmViewDesc.node && node.pmViewDesc.node.type.name !== "doc" || node.pmViewDesc.mark)) {
        var _node$getBoundingClie = node.getBoundingClientRect(),
            top = _node$getBoundingClie.top,
            left = _node$getBoundingClie.left,
            width = _node$getBoundingClie.width,
            height = _node$getBoundingClie.height;

        _this.setState({
          nodePicker: {
            top: top + window.scrollY,
            left: left,
            width: width,
            height: height,
            active: true
          }
        });
      } else {
        _this.setState({
          nodePicker: Object.assign({}, NODE_PICKER_DEFAULT, {
            active: true
          })
        });
      }
    });

    _defineProperty(_assertThisInitialized(_this), "nodePickerSelect", function (target) {
      var node = findPMNode(target);

      if (node) {
        var editorState = _this.state.state;
        var path = (0, _findNode.default)(editorState.doc, editorState.doc.nodeAt(node.pmViewDesc.posAtStart));

        _this.setState({
          expandPath: path
        });
      }

      _this.setState({
        nodePicker: NODE_PICKER_DEFAULT
      });
    });

    _defineProperty(_assertThisInitialized(_this), "saveSnapshot", function () {
      var snapshotName = prompt("Enter snapshot name", Date.now());
      if (!snapshotName) return;
      var snapshots = [{
        name: snapshotName,
        timestamp: Date.now(),
        snapshot: _this.state.state.doc.toJSON()
      }].concat(_this.state.snapshots);

      _this.setState({
        snapshots: snapshots
      });

      window.localStorage.setItem(SNAPSHOTS_KEY, JSON.stringify(snapshots));
    });

    _defineProperty(_assertThisInitialized(_this), "loadSnapshot", function (snapshot) {
      var EditorState = _this.state.EditorState;
      var editorView = _this.state.view;
      var editorState = editorView.state;
      var newState = EditorState.create({
        schema: editorState.schema,
        plugins: editorState.plugins,
        doc: editorState.schema.nodeFromJSON(snapshot.snapshot)
      });

      _this.setState({
        history: [createHistoryEntry(newState)],
        state: newState
      });

      editorView.updateState(newState);
    });

    _defineProperty(_assertThisInitialized(_this), "deleteSnapshot", function (snapshot) {
      var snapshots = _this.state.snapshots;
      var snapshotIndex = snapshots.indexOf(snapshot);
      snapshots.splice(snapshotIndex, 1);

      _this.setState({
        snapshots: [].concat(snapshots)
      });

      window.localStorage.setItem(SNAPSHOTS_KEY, JSON.stringify(snapshots));
    });

    _defineProperty(_assertThisInitialized(_this), "logNodeFromJSON", function (_ref) {
      var doc = _ref.doc,
          node = _ref.node;
      var fullDoc = _this.state.state.doc;
      var path = (0, _findNode.findNodeInJSON)(doc, node);

      if (path) {
        console.log(path.reduce(function (node, pathItem) {
          return node[pathItem];
        }, fullDoc));
      } else {
        console.log(node);
      }
    });

    _defineProperty(_assertThisInitialized(_this), "selectHistoryItem", function (index) {
      return _this.setState({
        selectedHistoryItem: index
      });
    });

    _defineProperty(_assertThisInitialized(_this), "rollbackHistory", function (index) {
      var EditorState = _this.state.EditorState;
      var editorState = _this.state.history[index].state;
      var editorView = _this.state.view;
      var newState = EditorState.create({
        schema: editorState.schema,
        plugins: editorState.plugins,
        doc: editorState.schema.nodeFromJSON(editorState.doc.toJSON())
      });
      editorView.updateState(newState);
      editorView.dom.focus();
      var tr = editorView.state.tr.setSelection(editorState.selection).setMeta("addToHistory", false).setMeta("_skip-dev-tools-history_", true);
      editorView.dispatch(tr);

      _this.setState({
        state: newState,
        historyRolledBackTo: index
      });
    });

    _this.diffWorker = props && props.diffWorker ? require("_bundle_loader")(require.resolve("./json-diff-worker")).then(function (_ref2) {
      var JsonDiffWorker = _ref2.JsonDiffWorker;
      return new JsonDiffWorker(props.diffWorker);
    }) : require("_bundle_loader")(require.resolve("./json-diff-main")).then(function (_ref3) {
      var JsonDiffMain = _ref3.JsonDiffMain;
      return new JsonDiffMain();
    });
    _this.state = Object.assign({}, _this.state, {
      EditorState: (0, _getEditorState.default)(props),
      view: _editorView,
      state: _editorView.state,
      nodeColors: buildColors(_editorView.state.schema),
      history: [{
        state: _editorView.state,
        timestamp: Date.now()
      }]
    });
    (0, _subscribeOnUpdates.default)(_editorView, function (tr, oldState, newState) {
      var updatedHistory = updateEditorHistory(_this.state.history, _this.state.historyRolledBackTo, tr, newState);

      if (oldState && updatedHistory) {
        var _updatedHistory = _slicedToArray(updatedHistory, 1),
            id = _updatedHistory[0].id;

        var self = _assertThisInitialized(_this);

        _asyncToGenerator( /*#__PURE__*/_regenerator.default.mark(function _callee() {
          var diffWorker, _yield$Promise$all, _yield$Promise$all2, diff, selection, history;

          return _regenerator.default.wrap(function _callee$(_context) {
            while (1) {
              switch (_context.prev = _context.next) {
                case 0:
                  _context.next = 2;
                  return _this.diffWorker;

                case 2:
                  diffWorker = _context.sent;
                  _context.next = 5;
                  return Promise.all([diffWorker.diff({
                    a: oldState.doc.toJSON(),
                    b: newState.doc.toJSON(),
                    id: id
                  }), diffWorker.diff({
                    a: buildSelection(oldState.selection),
                    b: buildSelection(newState.selection),
                    id: id
                  })]);

                case 5:
                  _yield$Promise$all = _context.sent;
                  _yield$Promise$all2 = _slicedToArray(_yield$Promise$all, 2);
                  diff = _yield$Promise$all2[0].delta;
                  selection = _yield$Promise$all2[1].delta;
                  history = updatedHistory.map(function (item) {
                    return item.id === id ? Object.assign({}, item, {
                      diff: diff,
                      diffPending: false,
                      selection: selection
                    }) : item;
                  });
                  self.setState({
                    history: history
                  });

                case 11:
                case "end":
                  return _context.stop();
              }
            }
          }, _callee);
        }))();
      }

      _this.setState({
        state: newState,
        nodeColors: buildColors(newState.schema),
        activeMarks: getActiveMarks(newState),
        history: updatedHistory || _this.state.history,
        selectedHistoryItem: updatedHistory ? 0 : _this.state.selectedHistoryItem,
        historyRolledBackTo: updatedHistory ? false : _this.state.historyRolledBackTo
      });
    });
    return _this;
  }

  return EditorStateContainer;
}(_unstated.Container);

exports.default = EditorStateContainer;
},{"@babel/runtime/regenerator":"../node_modules/@babel/runtime/regenerator/index.js","prosemirror-model":"../node_modules/prosemirror-model/dist/index.es.js","unstated":"../node_modules/unstated/lib/unstated.es.js","html":"../node_modules/html/lib/html.js","nanoid":"../node_modules/nanoid/index.browser.js","../utils/subscribe-on-updates":"../src/utils/subscribe-on-updates.js","../utils/find-node":"../src/utils/find-node.js","./get-editor-state":"../src/state/get-editor-state.js","_bundle_loader":"../node_modules/parcel/src/builtins/bundle-loader.js","./json-diff-worker":[["json-diff-worker.13db5fcf.js","../src/state/json-diff-worker.js"],"json-diff-worker.13db5fcf.js.map","../src/state/json-diff-worker.js"],"./json-diff-main":[["json-diff-main.51504cb0.js","../src/state/json-diff-main.js"],"json-diff-main.51504cb0.js.map","../src/state/json-diff-main.js"]}],"../src/state/state-tab.js":[function(require,module,exports) {
"use strict";

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

var _unstated = require("unstated");

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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function () { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

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; }

var StateTabStateContainer = /*#__PURE__*/function (_Container) {
  _inherits(StateTabStateContainer, _Container);

  var _super = _createSuper(StateTabStateContainer);

  function StateTabStateContainer() {
    var _this;

    _classCallCheck(this, StateTabStateContainer);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _super.call.apply(_super, [this].concat(args));

    _defineProperty(_assertThisInitialized(_this), "state", {
      selectionExpanded: false
    });

    _defineProperty(_assertThisInitialized(_this), "toggleSelection", function () {
      _this.setState({
        selectionExpanded: !_this.state.selectionExpanded
      });
    });

    return _this;
  }

  return StateTabStateContainer;
}(_unstated.Container);

exports.default = StateTabStateContainer;
},{"unstated":"../node_modules/unstated/lib/unstated.es.js"}],"../src/utils/format-selection-object.js":[function(require,module,exports) {
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.expandedStateFormatSelection = expandedStateFormatSelection;
exports.collapsedStateFormatSelection = collapsedStateFormatSelection;
var copyProps = ["jsonID", "empty", "anchor", "from", "head", "to", "$anchor", "$head", "$cursor", "$to", "$from"];
var copySubProps = {
  $from: ["nodeAfter", "nodeBefore", "parent", "textOffset", "depth", "pos"],
  $to: ["nodeAfter", "nodeBefore", "parent", "textOffset", "depth", "pos"]
};
var isNode = ["nodeAfter", "nodeBefore", "parent"];

function filterProps(selection, props, subProps) {
  return props.reduce(function (acc, prop) {
    if (subProps && subProps[prop]) {
      acc[prop] = subProps[prop].reduce(function (subAcc, subProp) {
        subAcc[subProp] = isNode.indexOf(subProp) === -1 || !selection[prop][subProp] ? selection[prop][subProp] : selection[prop][subProp].toJSON();
        return subAcc;
      }, {});
    } else {
      acc[prop === "jsonID" ? "type" : prop] = selection[prop];
    }

    return acc;
  }, {});
}

function expandedStateFormatSelection(selection) {
  return filterProps(selection, copyProps, copySubProps);
}

function collapsedStateFormatSelection(selection) {
  return filterProps(selection, copyProps.slice(0, 6));
}
},{}],"../src/components/split-view.js":[function(require,module,exports) {
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SplitViewCol = exports.SplitView = void 0;

var _styled = _interopRequireDefault(require("@emotion/styled"));

var _theme = _interopRequireDefault(require("../theme"));

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

var SplitView = (0, _styled.default)("div")({
  display: "flex",
  height: "100%"
});
exports.SplitView = SplitView;
SplitView.displayName = "SplitView";
var SplitViewCol = (0, _styled.default)("div")({
  boxSizing: "border-box",
  height: "100%",
  overflow: "scroll"
}, function (_ref) {
  var grow = _ref.grow,
      sep = _ref.sep,
      noPaddings = _ref.noPaddings,
      minWidth = _ref.minWidth,
      maxWidth = _ref.maxWidth;
  return {
    flexGrow: grow ? 1 : 0,
    borderLeft: sep ? "1px solid " + _theme.default.main20 : "none",
    padding: noPaddings ? "" : "16px 18px 18px",
    minWidth: minWidth ? "".concat(minWidth, "px") : "none",
    maxWidth: maxWidth ? "".concat(maxWidth, "px") : "none"
  };
});
exports.SplitViewCol = SplitViewCol;
SplitViewCol.displayName = "SplitViewCol";
},{"@emotion/styled":"../node_modules/@emotion/styled/dist/styled.browser.esm.js","../theme":"../src/theme.js"}],"../node_modules/babel-runtime/helpers/objectWithoutProperties.js":[function(require,module,exports) {
"use strict";

exports.__esModule = true;

exports.default = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};
},{}],"../node_modules/babel-runtime/helpers/classCallCheck.js":[function(require,module,exports) {
"use strict";

exports.__esModule = true;

exports.default = function (instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
};
},{}],"../node_modules/core-js/library/modules/_to-integer.js":[function(require,module,exports) {
// 7.1.4 ToInteger
var ceil = Math.ceil;
var floor = Math.floor;
module.exports = function (it) {
  return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
};

},{}],"../node_modules/core-js/library/modules/_defined.js":[function(require,module,exports) {
// 7.2.1 RequireObjectCoercible(argument)
module.exports = function (it) {
  if (it == undefined) throw TypeError("Can't call method on  " + it);
  return it;
};

},{}],"../node_modules/core-js/library/modules/_string-at.js":[function(require,module,exports) {
var toInteger = require('./_to-integer');
var defined = require('./_defined');
// true  -> String#at
// false -> String#codePointAt
module.exports = function (TO_STRING) {
  return function (that, pos) {
    var s = String(defined(that));
    var i = toInteger(pos);
    var l = s.length;
    var a, b;
    if (i < 0 || i >= l) return TO_STRING ? '' : undefined;
    a = s.charCodeAt(i);
    return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff
      ? TO_STRING ? s.charAt(i) : a
      : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000;
  };
};

},{"./_to-integer":"../node_modules/core-js/library/modules/_to-integer.js","./_defined":"../node_modules/core-js/library/modules/_defined.js"}],"../node_modules/core-js/library/modules/_library.js":[function(require,module,exports) {
module.exports = true;

},{}],"../node_modules/core-js/library/modules/_global.js":[function(require,module,exports) {

// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global = module.exports = typeof window != 'undefined' && window.Math == Math
  ? window : typeof self != 'undefined' && self.Math == Math ? self
  // eslint-disable-next-line no-new-func
  : Function('return this')();
if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef

},{}],"../node_modules/core-js/library/modules/_core.js":[function(require,module,exports) {
var core = module.exports = { version: '2.6.11' };
if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef

},{}],"../node_modules/core-js/library/modules/_a-function.js":[function(require,module,exports) {
module.exports = function (it) {
  if (typeof it != 'function') throw TypeError(it + ' is not a function!');
  return it;
};

},{}],"../node_modules/core-js/library/modules/_ctx.js":[function(require,module,exports) {
// optional / simple context binding
var aFunction = require('./_a-function');
module.exports = function (fn, that, length) {
  aFunction(fn);
  if (that === undefined) return fn;
  switch (length) {
    case 1: return function (a) {
      return fn.call(that, a);
    };
    case 2: return function (a, b) {
      return fn.call(that, a, b);
    };
    case 3: return function (a, b, c) {
      return fn.call(that, a, b, c);
    };
  }
  return function (/* ...args */) {
    return fn.apply(that, arguments);
  };
};

},{"./_a-function":"../node_modules/core-js/library/modules/_a-function.js"}],"../node_modules/core-js/library/modules/_is-object.js":[function(require,module,exports) {
module.exports = function (it) {
  return typeof it === 'object' ? it !== null : typeof it === 'function';
};

},{}],"../node_modules/core-js/library/modules/_an-object.js":[function(require,module,exports) {
var isObject = require('./_is-object');
module.exports = function (it) {
  if (!isObject(it)) throw TypeError(it + ' is not an object!');
  return it;
};

},{"./_is-object":"../node_modules/core-js/library/modules/_is-object.js"}],"../node_modules/core-js/library/modules/_fails.js":[function(require,module,exports) {
module.exports = function (exec) {
  try {
    return !!exec();
  } catch (e) {
    return true;
  }
};

},{}],"../node_modules/core-js/library/modules/_descriptors.js":[function(require,module,exports) {
// Thank's IE8 for his funny defineProperty
module.exports = !require('./_fails')(function () {
  return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7;
});

},{"./_fails":"../node_modules/core-js/library/modules/_fails.js"}],"../node_modules/core-js/library/modules/_dom-create.js":[function(require,module,exports) {
var isObject = require('./_is-object');
var document = require('./_global').document;
// typeof document.createElement is 'object' in old IE
var is = isObject(document) && isObject(document.createElement);
module.exports = function (it) {
  return is ? document.createElement(it) : {};
};

},{"./_is-object":"../node_modules/core-js/library/modules/_is-object.js","./_global":"../node_modules/core-js/library/modules/_global.js"}],"../node_modules/core-js/library/modules/_ie8-dom-define.js":[function(require,module,exports) {
module.exports = !require('./_descriptors') && !require('./_fails')(function () {
  return Object.defineProperty(require('./_dom-create')('div'), 'a', { get: function () { return 7; } }).a != 7;
});

},{"./_descriptors":"../node_modules/core-js/library/modules/_descriptors.js","./_fails":"../node_modules/core-js/library/modules/_fails.js","./_dom-create":"../node_modules/core-js/library/modules/_dom-create.js"}],"../node_modules/core-js/library/modules/_to-primitive.js":[function(require,module,exports) {
// 7.1.1 ToPrimitive(input [, PreferredType])
var isObject = require('./_is-object');
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
module.exports = function (it, S) {
  if (!isObject(it)) return it;
  var fn, val;
  if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;
  if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val;
  if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;
  throw TypeError("Can't convert object to primitive value");
};

},{"./_is-object":"../node_modules/core-js/library/modules/_is-object.js"}],"../node_modules/core-js/library/modules/_object-dp.js":[function(require,module,exports) {
var anObject = require('./_an-object');
var IE8_DOM_DEFINE = require('./_ie8-dom-define');
var toPrimitive = require('./_to-primitive');
var dP = Object.defineProperty;

exports.f = require('./_descriptors') ? Object.defineProperty : function defineProperty(O, P, Attributes) {
  anObject(O);
  P = toPrimitive(P, true);
  anObject(Attributes);
  if (IE8_DOM_DEFINE) try {
    return dP(O, P, Attributes);
  } catch (e) { /* empty */ }
  if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!');
  if ('value' in Attributes) O[P] = Attributes.value;
  return O;
};

},{"./_an-object":"../node_modules/core-js/library/modules/_an-object.js","./_ie8-dom-define":"../node_modules/core-js/library/modules/_ie8-dom-define.js","./_to-primitive":"../node_modules/core-js/library/modules/_to-primitive.js","./_descriptors":"../node_modules/core-js/library/modules/_descriptors.js"}],"../node_modules/core-js/library/modules/_property-desc.js":[function(require,module,exports) {
module.exports = function (bitmap, value) {
  return {
    enumerable: !(bitmap & 1),
    configurable: !(bitmap & 2),
    writable: !(bitmap & 4),
    value: value
  };
};

},{}],"../node_modules/core-js/library/modules/_hide.js":[function(require,module,exports) {
var dP = require('./_object-dp');
var createDesc = require('./_property-desc');
module.exports = require('./_descriptors') ? function (object, key, value) {
  return dP.f(object, key, createDesc(1, value));
} : function (object, key, value) {
  object[key] = value;
  return object;
};

},{"./_object-dp":"../node_modules/core-js/library/modules/_object-dp.js","./_property-desc":"../node_modules/core-js/library/modules/_property-desc.js","./_descriptors":"../node_modules/core-js/library/modules/_descriptors.js"}],"../node_modules/core-js/library/modules/_has.js":[function(require,module,exports) {
var hasOwnProperty = {}.hasOwnProperty;
module.exports = function (it, key) {
  return hasOwnProperty.call(it, key);
};

},{}],"../node_modules/core-js/library/modules/_export.js":[function(require,module,exports) {

var global = require('./_global');
var core = require('./_core');
var ctx = require('./_ctx');
var hide = require('./_hide');
var has = require('./_has');
var PROTOTYPE = 'prototype';

var $export = function (type, name, source) {
  var IS_FORCED = type & $export.F;
  var IS_GLOBAL = type & $export.G;
  var IS_STATIC = type & $export.S;
  var IS_PROTO = type & $export.P;
  var IS_BIND = type & $export.B;
  var IS_WRAP = type & $export.W;
  var exports = IS_GLOBAL ? core : core[name] || (core[name] = {});
  var expProto = exports[PROTOTYPE];
  var target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE];
  var key, own, out;
  if (IS_GLOBAL) source = name;
  for (key in source) {
    // contains in native
    own = !IS_FORCED && target && target[key] !== undefined;
    if (own && has(exports, key)) continue;
    // export native or passed
    out = own ? target[key] : source[key];
    // prevent global pollution for namespaces
    exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key]
    // bind timers to global for call from export context
    : IS_BIND && own ? ctx(out, global)
    // wrap global constructors for prevent change them in library
    : IS_WRAP && target[key] == out ? (function (C) {
      var F = function (a, b, c) {
        if (this instanceof C) {
          switch (arguments.length) {
            case 0: return new C();
            case 1: return new C(a);
            case 2: return new C(a, b);
          } return new C(a, b, c);
        } return C.apply(this, arguments);
      };
      F[PROTOTYPE] = C[PROTOTYPE];
      return F;
    // make static versions for prototype methods
    })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
    // export proto methods to core.%CONSTRUCTOR%.methods.%NAME%
    if (IS_PROTO) {
      (exports.virtual || (exports.virtual = {}))[key] = out;
      // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME%
      if (type & $export.R && expProto && !expProto[key]) hide(expProto, key, out);
    }
  }
};
// type bitmap
$export.F = 1;   // forced
$export.G = 2;   // global
$export.S = 4;   // static
$export.P = 8;   // proto
$export.B = 16;  // bind
$export.W = 32;  // wrap
$export.U = 64;  // safe
$export.R = 128; // real proto method for `library`
module.exports = $export;

},{"./_global":"../node_modules/core-js/library/modules/_global.js","./_core":"../node_modules/core-js/library/modules/_core.js","./_ctx":"../node_modules/core-js/library/modules/_ctx.js","./_hide":"../node_modules/core-js/library/modules/_hide.js","./_has":"../node_modules/core-js/library/modules/_has.js"}],"../node_modules/core-js/library/modules/_redefine.js":[function(require,module,exports) {
module.exports = require('./_hide');

},{"./_hide":"../node_modules/core-js/library/modules/_hide.js"}],"../node_modules/core-js/library/modules/_iterators.js":[function(require,module,exports) {
module.exports = {};

},{}],"../node_modules/core-js/library/modules/_cof.js":[function(require,module,exports) {
var toString = {}.toString;

module.exports = function (it) {
  return toString.call(it).slice(8, -1);
};

},{}],"../node_modules/core-js/library/modules/_iobject.js":[function(require,module,exports) {
// fallback for non-array-like ES3 and non-enumerable old V8 strings
var cof = require('./_cof');
// eslint-disable-next-line no-prototype-builtins
module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) {
  return cof(it) == 'String' ? it.split('') : Object(it);
};

},{"./_cof":"../node_modules/core-js/library/modules/_cof.js"}],"../node_modules/core-js/library/modules/_to-iobject.js":[function(require,module,exports) {
// to indexed object, toObject with fallback for non-array-like ES3 strings
var IObject = require('./_iobject');
var defined = require('./_defined');
module.exports = function (it) {
  return IObject(defined(it));
};

},{"./_iobject":"../node_modules/core-js/library/modules/_iobject.js","./_defined":"../node_modules/core-js/library/modules/_defined.js"}],"../node_modules/core-js/library/modules/_to-length.js":[function(require,module,exports) {
// 7.1.15 ToLength
var toInteger = require('./_to-integer');
var min = Math.min;
module.exports = function (it) {
  return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
};

},{"./_to-integer":"../node_modules/core-js/library/modules/_to-integer.js"}],"../node_modules/core-js/library/modules/_to-absolute-index.js":[function(require,module,exports) {
var toInteger = require('./_to-integer');
var max = Math.max;
var min = Math.min;
module.exports = function (index, length) {
  index = toInteger(index);
  return index < 0 ? max(index + length, 0) : min(index, length);
};

},{"./_to-integer":"../node_modules/core-js/library/modules/_to-integer.js"}],"../node_modules/core-js/library/modules/_array-includes.js":[function(require,module,exports) {
// false -> Array#indexOf
// true  -> Array#includes
var toIObject = require('./_to-iobject');
var toLength = require('./_to-length');
var toAbsoluteIndex = require('./_to-absolute-index');
module.exports = function (IS_INCLUDES) {
  return function ($this, el, fromIndex) {
    var O = toIObject($this);
    var length = toLength(O.length);
    var index = toAbsoluteIndex(fromIndex, length);
    var value;
    // Array#includes uses SameValueZero equality algorithm
    // eslint-disable-next-line no-self-compare
    if (IS_INCLUDES && el != el) while (length > index) {
      value = O[index++];
      // eslint-disable-next-line no-self-compare
      if (value != value) return true;
    // Array#indexOf ignores holes, Array#includes - not
    } else for (;length > index; index++) if (IS_INCLUDES || index in O) {
      if (O[index] === el) return IS_INCLUDES || index || 0;
    } return !IS_INCLUDES && -1;
  };
};

},{"./_to-iobject":"../node_modules/core-js/library/modules/_to-iobject.js","./_to-length":"../node_modules/core-js/library/modules/_to-length.js","./_to-absolute-index":"../node_modules/core-js/library/modules/_to-absolute-index.js"}],"../node_modules/core-js/library/modules/_shared.js":[function(require,module,exports) {

var core = require('./_core');
var global = require('./_global');
var SHARED = '__core-js_shared__';
var store = global[SHARED] || (global[SHARED] = {});

(module.exports = function (key, value) {
  return store[key] || (store[key] = value !== undefined ? value : {});
})('versions', []).push({
  version: core.version,
  mode: require('./_library') ? 'pure' : 'global',
  copyright: '© 2019 Denis Pushkarev (zloirock.ru)'
});

},{"./_core":"../node_modules/core-js/library/modules/_core.js","./_global":"../node_modules/core-js/library/modules/_global.js","./_library":"../node_modules/core-js/library/modules/_library.js"}],"../node_modules/core-js/library/modules/_uid.js":[function(require,module,exports) {
var id = 0;
var px = Math.random();
module.exports = function (key) {
  return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
};

},{}],"../node_modules/core-js/library/modules/_shared-key.js":[function(require,module,exports) {
var shared = require('./_shared')('keys');
var uid = require('./_uid');
module.exports = function (key) {
  return shared[key] || (shared[key] = uid(key));
};

},{"./_shared":"../node_modules/core-js/library/modules/_shared.js","./_uid":"../node_modules/core-js/library/modules/_uid.js"}],"../node_modules/core-js/library/modules/_object-keys-internal.js":[function(require,module,exports) {
var has = require('./_has');
var toIObject = require('./_to-iobject');
var arrayIndexOf = require('./_array-includes')(false);
var IE_PROTO = require('./_shared-key')('IE_PROTO');

module.exports = function (object, names) {
  var O = toIObject(object);
  var i = 0;
  var result = [];
  var key;
  for (key in O) if (key != IE_PROTO) has(O, key) && result.push(key);
  // Don't enum bug & hidden keys
  while (names.length > i) if (has(O, key = names[i++])) {
    ~arrayIndexOf(result, key) || result.push(key);
  }
  return result;
};

},{"./_has":"../node_modules/core-js/library/modules/_has.js","./_to-iobject":"../node_modules/core-js/library/modules/_to-iobject.js","./_array-includes":"../node_modules/core-js/library/modules/_array-includes.js","./_shared-key":"../node_modules/core-js/library/modules/_shared-key.js"}],"../node_modules/core-js/library/modules/_enum-bug-keys.js":[function(require,module,exports) {
// IE 8- don't enum bug keys
module.exports = (
  'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'
).split(',');

},{}],"../node_modules/core-js/library/modules/_object-keys.js":[function(require,module,exports) {
// 19.1.2.14 / 15.2.3.14 Object.keys(O)
var $keys = require('./_object-keys-internal');
var enumBugKeys = require('./_enum-bug-keys');

module.exports = Object.keys || function keys(O) {
  return $keys(O, enumBugKeys);
};

},{"./_object-keys-internal":"../node_modules/core-js/library/modules/_object-keys-internal.js","./_enum-bug-keys":"../node_modules/core-js/library/modules/_enum-bug-keys.js"}],"../node_modules/core-js/library/modules/_object-dps.js":[function(require,module,exports) {
var dP = require('./_object-dp');
var anObject = require('./_an-object');
var getKeys = require('./_object-keys');

module.exports = require('./_descriptors') ? Object.defineProperties : function defineProperties(O, Properties) {
  anObject(O);
  var keys = getKeys(Properties);
  var length = keys.length;
  var i = 0;
  var P;
  while (length > i) dP.f(O, P = keys[i++], Properties[P]);
  return O;
};

},{"./_object-dp":"../node_modules/core-js/library/modules/_object-dp.js","./_an-object":"../node_modules/core-js/library/modules/_an-object.js","./_object-keys":"../node_modules/core-js/library/modules/_object-keys.js","./_descriptors":"../node_modules/core-js/library/modules/_descriptors.js"}],"../node_modules/core-js/library/modules/_html.js":[function(require,module,exports) {
var document = require('./_global').document;
module.exports = document && document.documentElement;

},{"./_global":"../node_modules/core-js/library/modules/_global.js"}],"../node_modules/core-js/library/modules/_object-create.js":[function(require,module,exports) {
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
var anObject = require('./_an-object');
var dPs = require('./_object-dps');
var enumBugKeys = require('./_enum-bug-keys');
var IE_PROTO = require('./_shared-key')('IE_PROTO');
var Empty = function () { /* empty */ };
var PROTOTYPE = 'prototype';

// Create object with fake `null` prototype: use iframe Object with cleared prototype
var createDict = function () {
  // Thrash, waste and sodomy: IE GC bug
  var iframe = require('./_dom-create')('iframe');
  var i = enumBugKeys.length;
  var lt = '<';
  var gt = '>';
  var iframeDocument;
  iframe.style.display = 'none';
  require('./_html').appendChild(iframe);
  iframe.src = 'javascript:'; // eslint-disable-line no-script-url
  // createDict = iframe.contentWindow.Object;
  // html.removeChild(iframe);
  iframeDocument = iframe.contentWindow.document;
  iframeDocument.open();
  iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt);
  iframeDocument.close();
  createDict = iframeDocument.F;
  while (i--) delete createDict[PROTOTYPE][enumBugKeys[i]];
  return createDict();
};

module.exports = Object.create || function create(O, Properties) {
  var result;
  if (O !== null) {
    Empty[PROTOTYPE] = anObject(O);
    result = new Empty();
    Empty[PROTOTYPE] = null;
    // add "__proto__" for Object.getPrototypeOf polyfill
    result[IE_PROTO] = O;
  } else result = createDict();
  return Properties === undefined ? result : dPs(result, Properties);
};

},{"./_an-object":"../node_modules/core-js/library/modules/_an-object.js","./_object-dps":"../node_modules/core-js/library/modules/_object-dps.js","./_enum-bug-keys":"../node_modules/core-js/library/modules/_enum-bug-keys.js","./_shared-key":"../node_modules/core-js/library/modules/_shared-key.js","./_dom-create":"../node_modules/core-js/library/modules/_dom-create.js","./_html":"../node_modules/core-js/library/modules/_html.js"}],"../node_modules/core-js/library/modules/_wks.js":[function(require,module,exports) {
var store = require('./_shared')('wks');
var uid = require('./_uid');
var Symbol = require('./_global').Symbol;
var USE_SYMBOL = typeof Symbol == 'function';

var $exports = module.exports = function (name) {
  return store[name] || (store[name] =
    USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name));
};

$exports.store = store;

},{"./_shared":"../node_modules/core-js/library/modules/_shared.js","./_uid":"../node_modules/core-js/library/modules/_uid.js","./_global":"../node_modules/core-js/library/modules/_global.js"}],"../node_modules/core-js/library/modules/_set-to-string-tag.js":[function(require,module,exports) {
var def = require('./_object-dp').f;
var has = require('./_has');
var TAG = require('./_wks')('toStringTag');

module.exports = function (it, tag, stat) {
  if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag });
};

},{"./_object-dp":"../node_modules/core-js/library/modules/_object-dp.js","./_has":"../node_modules/core-js/library/modules/_has.js","./_wks":"../node_modules/core-js/library/modules/_wks.js"}],"../node_modules/core-js/library/modules/_iter-create.js":[function(require,module,exports) {
'use strict';
var create = require('./_object-create');
var descriptor = require('./_property-desc');
var setToStringTag = require('./_set-to-string-tag');
var IteratorPrototype = {};

// 25.1.2.1.1 %IteratorPrototype%[@@iterator]()
require('./_hide')(IteratorPrototype, require('./_wks')('iterator'), function () { return this; });

module.exports = function (Constructor, NAME, next) {
  Constructor.prototype = create(IteratorPrototype, { next: descriptor(1, next) });
  setToStringTag(Constructor, NAME + ' Iterator');
};

},{"./_object-create":"../node_modules/core-js/library/modules/_object-create.js","./_property-desc":"../node_modules/core-js/library/modules/_property-desc.js","./_set-to-string-tag":"../node_modules/core-js/library/modules/_set-to-string-tag.js","./_hide":"../node_modules/core-js/library/modules/_hide.js","./_wks":"../node_modules/core-js/library/modules/_wks.js"}],"../node_modules/core-js/library/modules/_to-object.js":[function(require,module,exports) {
// 7.1.13 ToObject(argument)
var defined = require('./_defined');
module.exports = function (it) {
  return Object(defined(it));
};

},{"./_defined":"../node_modules/core-js/library/modules/_defined.js"}],"../node_modules/core-js/library/modules/_object-gpo.js":[function(require,module,exports) {
// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O)
var has = require('./_has');
var toObject = require('./_to-object');
var IE_PROTO = require('./_shared-key')('IE_PROTO');
var ObjectProto = Object.prototype;

module.exports = Object.getPrototypeOf || function (O) {
  O = toObject(O);
  if (has(O, IE_PROTO)) return O[IE_PROTO];
  if (typeof O.constructor == 'function' && O instanceof O.constructor) {
    return O.constructor.prototype;
  } return O instanceof Object ? ObjectProto : null;
};

},{"./_has":"../node_modules/core-js/library/modules/_has.js","./_to-object":"../node_modules/core-js/library/modules/_to-object.js","./_shared-key":"../node_modules/core-js/library/modules/_shared-key.js"}],"../node_modules/core-js/library/modules/_iter-define.js":[function(require,module,exports) {
'use strict';
var LIBRARY = require('./_library');
var $export = require('./_export');
var redefine = require('./_redefine');
var hide = require('./_hide');
var Iterators = require('./_iterators');
var $iterCreate = require('./_iter-create');
var setToStringTag = require('./_set-to-string-tag');
var getPrototypeOf = require('./_object-gpo');
var ITERATOR = require('./_wks')('iterator');
var BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next`
var FF_ITERATOR = '@@iterator';
var KEYS = 'keys';
var VALUES = 'values';

var returnThis = function () { return this; };

module.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) {
  $iterCreate(Constructor, NAME, next);
  var getMethod = function (kind) {
    if (!BUGGY && kind in proto) return proto[kind];
    switch (kind) {
      case KEYS: return function keys() { return new Constructor(this, kind); };
      case VALUES: return function values() { return new Constructor(this, kind); };
    } return function entries() { return new Constructor(this, kind); };
  };
  var TAG = NAME + ' Iterator';
  var DEF_VALUES = DEFAULT == VALUES;
  var VALUES_BUG = false;
  var proto = Base.prototype;
  var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT];
  var $default = $native || getMethod(DEFAULT);
  var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined;
  var $anyNative = NAME == 'Array' ? proto.entries || $native : $native;
  var methods, key, IteratorPrototype;
  // Fix native
  if ($anyNative) {
    IteratorPrototype = getPrototypeOf($anyNative.call(new Base()));
    if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) {
      // Set @@toStringTag to native iterators
      setToStringTag(IteratorPrototype, TAG, true);
      // fix for some old engines
      if (!LIBRARY && typeof IteratorPrototype[ITERATOR] != 'function') hide(IteratorPrototype, ITERATOR, returnThis);
    }
  }
  // fix Array#{values, @@iterator}.name in V8 / FF
  if (DEF_VALUES && $native && $native.name !== VALUES) {
    VALUES_BUG = true;
    $default = function values() { return $native.call(this); };
  }
  // Define iterator
  if ((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) {
    hide(proto, ITERATOR, $default);
  }
  // Plug for library
  Iterators[NAME] = $default;
  Iterators[TAG] = returnThis;
  if (DEFAULT) {
    methods = {
      values: DEF_VALUES ? $default : getMethod(VALUES),
      keys: IS_SET ? $default : getMethod(KEYS),
      entries: $entries
    };
    if (FORCED) for (key in methods) {
      if (!(key in proto)) redefine(proto, key, methods[key]);
    } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods);
  }
  return methods;
};

},{"./_library":"../node_modules/core-js/library/modules/_library.js","./_export":"../node_modules/core-js/library/modules/_export.js","./_redefine":"../node_modules/core-js/library/modules/_redefine.js","./_hide":"../node_modules/core-js/library/modules/_hide.js","./_iterators":"../node_modules/core-js/library/modules/_iterators.js","./_iter-create":"../node_modules/core-js/library/modules/_iter-create.js","./_set-to-string-tag":"../node_modules/core-js/library/modules/_set-to-string-tag.js","./_object-gpo":"../node_modules/core-js/library/modules/_object-gpo.js","./_wks":"../node_modules/core-js/library/modules/_wks.js"}],"../node_modules/core-js/library/modules/es6.string.iterator.js":[function(require,module,exports) {
'use strict';
var $at = require('./_string-at')(true);

// 21.1.3.27 String.prototype[@@iterator]()
require('./_iter-define')(String, 'String', function (iterated) {
  this._t = String(iterated); // target
  this._i = 0;                // next index
// 21.1.5.2.1 %StringIteratorPrototype%.next()
}, function () {
  var O = this._t;
  var index = this._i;
  var point;
  if (index >= O.length) return { value: undefined, done: true };
  point = $at(O, index);
  this._i += point.length;
  return { value: point, done: false };
});

},{"./_string-at":"../node_modules/core-js/library/modules/_string-at.js","./_iter-define":"../node_modules/core-js/library/modules/_iter-define.js"}],"../node_modules/core-js/library/modules/_add-to-unscopables.js":[function(require,module,exports) {
module.exports = function () { /* empty */ };

},{}],"../node_modules/core-js/library/modules/_iter-step.js":[function(require,module,exports) {
module.exports = function (done, value) {
  return { value: value, done: !!done };
};

},{}],"../node_modules/core-js/library/modules/es6.array.iterator.js":[function(require,module,exports) {
'use strict';
var addToUnscopables = require('./_add-to-unscopables');
var step = require('./_iter-step');
var Iterators = require('./_iterators');
var toIObject = require('./_to-iobject');

// 22.1.3.4 Array.prototype.entries()
// 22.1.3.13 Array.prototype.keys()
// 22.1.3.29 Array.prototype.values()
// 22.1.3.30 Array.prototype[@@iterator]()
module.exports = require('./_iter-define')(Array, 'Array', function (iterated, kind) {
  this._t = toIObject(iterated); // target
  this._i = 0;                   // next index
  this._k = kind;                // kind
// 22.1.5.2.1 %ArrayIteratorPrototype%.next()
}, function () {
  var O = this._t;
  var kind = this._k;
  var index = this._i++;
  if (!O || index >= O.length) {
    this._t = undefined;
    return step(1);
  }
  if (kind == 'keys') return step(0, index);
  if (kind == 'values') return step(0, O[index]);
  return step(0, [index, O[index]]);
}, 'values');

// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7)
Iterators.Arguments = Iterators.Array;

addToUnscopables('keys');
addToUnscopables('values');
addToUnscopables('entries');

},{"./_add-to-unscopables":"../node_modules/core-js/library/modules/_add-to-unscopables.js","./_iter-step":"../node_modules/core-js/library/modules/_iter-step.js","./_iterators":"../node_modules/core-js/library/modules/_iterators.js","./_to-iobject":"../node_modules/core-js/library/modules/_to-iobject.js","./_iter-define":"../node_modules/core-js/library/modules/_iter-define.js"}],"../node_modules/core-js/library/modules/web.dom.iterable.js":[function(require,module,exports) {

require('./es6.array.iterator');
var global = require('./_global');
var hide = require('./_hide');
var Iterators = require('./_iterators');
var TO_STRING_TAG = require('./_wks')('toStringTag');

var DOMIterables = ('CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,' +
  'DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,' +
  'MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,' +
  'SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,' +
  'TextTrackList,TouchList').split(',');

for (var i = 0; i < DOMIterables.length; i++) {
  var NAME = DOMIterables[i];
  var Collection = global[NAME];
  var proto = Collection && Collection.prototype;
  if (proto && !proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME);
  Iterators[NAME] = Iterators.Array;
}

},{"./es6.array.iterator":"../node_modules/core-js/library/modules/es6.array.iterator.js","./_global":"../node_modules/core-js/library/modules/_global.js","./_hide":"../node_modules/core-js/library/modules/_hide.js","./_iterators":"../node_modules/core-js/library/modules/_iterators.js","./_wks":"../node_modules/core-js/library/modules/_wks.js"}],"../node_modules/core-js/library/modules/_wks-ext.js":[function(require,module,exports) {
exports.f = require('./_wks');

},{"./_wks":"../node_modules/core-js/library/modules/_wks.js"}],"../node_modules/core-js/library/fn/symbol/iterator.js":[function(require,module,exports) {
require('../../modules/es6.string.iterator');
require('../../modules/web.dom.iterable');
module.exports = require('../../modules/_wks-ext').f('iterator');

},{"../../modules/es6.string.iterator":"../node_modules/core-js/library/modules/es6.string.iterator.js","../../modules/web.dom.iterable":"../node_modules/core-js/library/modules/web.dom.iterable.js","../../modules/_wks-ext":"../node_modules/core-js/library/modules/_wks-ext.js"}],"../node_modules/babel-runtime/core-js/symbol/iterator.js":[function(require,module,exports) {
module.exports = { "default": require("core-js/library/fn/symbol/iterator"), __esModule: true };
},{"core-js/library/fn/symbol/iterator":"../node_modules/core-js/library/fn/symbol/iterator.js"}],"../node_modules/core-js/library/modules/_meta.js":[function(require,module,exports) {
var META = require('./_uid')('meta');
var isObject = require('./_is-object');
var has = require('./_has');
var setDesc = require('./_object-dp').f;
var id = 0;
var isExtensible = Object.isExtensible || function () {
  return true;
};
var FREEZE = !require('./_fails')(function () {
  return isExtensible(Object.preventExtensions({}));
});
var setMeta = function (it) {
  setDesc(it, META, { value: {
    i: 'O' + ++id, // object ID
    w: {}          // weak collections IDs
  } });
};
var fastKey = function (it, create) {
  // return primitive with prefix
  if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;
  if (!has(it, META)) {
    // can't set metadata to uncaught frozen object
    if (!isExtensible(it)) return 'F';
    // not necessary to add metadata
    if (!create) return 'E';
    // add missing metadata
    setMeta(it);
  // return object ID
  } return it[META].i;
};
var getWeak = function (it, create) {
  if (!has(it, META)) {
    // can't set metadata to uncaught frozen object
    if (!isExtensible(it)) return true;
    // not necessary to add metadata
    if (!create) return false;
    // add missing metadata
    setMeta(it);
  // return hash weak collections IDs
  } return it[META].w;
};
// add metadata on freeze-family methods calling
var onFreeze = function (it) {
  if (FREEZE && meta.NEED && isExtensible(it) && !has(it, META)) setMeta(it);
  return it;
};
var meta = module.exports = {
  KEY: META,
  NEED: false,
  fastKey: fastKey,
  getWeak: getWeak,
  onFreeze: onFreeze
};

},{"./_uid":"../node_modules/core-js/library/modules/_uid.js","./_is-object":"../node_modules/core-js/library/modules/_is-object.js","./_has":"../node_modules/core-js/library/modules/_has.js","./_object-dp":"../node_modules/core-js/library/modules/_object-dp.js","./_fails":"../node_modules/core-js/library/modules/_fails.js"}],"../node_modules/core-js/library/modules/_wks-define.js":[function(require,module,exports) {

var global = require('./_global');
var core = require('./_core');
var LIBRARY = require('./_library');
var wksExt = require('./_wks-ext');
var defineProperty = require('./_object-dp').f;
module.exports = function (name) {
  var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {});
  if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty($Symbol, name, { value: wksExt.f(name) });
};

},{"./_global":"../node_modules/core-js/library/modules/_global.js","./_core":"../node_modules/core-js/library/modules/_core.js","./_library":"../node_modules/core-js/library/modules/_library.js","./_wks-ext":"../node_modules/core-js/library/modules/_wks-ext.js","./_object-dp":"../node_modules/core-js/library/modules/_object-dp.js"}],"../node_modules/core-js/library/modules/_object-gops.js":[function(require,module,exports) {
exports.f = Object.getOwnPropertySymbols;

},{}],"../node_modules/core-js/library/modules/_object-pie.js":[function(require,module,exports) {
exports.f = {}.propertyIsEnumerable;

},{}],"../node_modules/core-js/library/modules/_enum-keys.js":[function(require,module,exports) {
// all enumerable object keys, includes symbols
var getKeys = require('./_object-keys');
var gOPS = require('./_object-gops');
var pIE = require('./_object-pie');
module.exports = function (it) {
  var result = getKeys(it);
  var getSymbols = gOPS.f;
  if (getSymbols) {
    var symbols = getSymbols(it);
    var isEnum = pIE.f;
    var i = 0;
    var key;
    while (symbols.length > i) if (isEnum.call(it, key = symbols[i++])) result.push(key);
  } return result;
};

},{"./_object-keys":"../node_modules/core-js/library/modules/_object-keys.js","./_object-gops":"../node_modules/core-js/library/modules/_object-gops.js","./_object-pie":"../node_modules/core-js/library/modules/_object-pie.js"}],"../node_modules/core-js/library/modules/_is-array.js":[function(require,module,exports) {
// 7.2.2 IsArray(argument)
var cof = require('./_cof');
module.exports = Array.isArray || function isArray(arg) {
  return cof(arg) == 'Array';
};

},{"./_cof":"../node_modules/core-js/library/modules/_cof.js"}],"../node_modules/core-js/library/modules/_object-gopn.js":[function(require,module,exports) {
// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O)
var $keys = require('./_object-keys-internal');
var hiddenKeys = require('./_enum-bug-keys').concat('length', 'prototype');

exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
  return $keys(O, hiddenKeys);
};

},{"./_object-keys-internal":"../node_modules/core-js/library/modules/_object-keys-internal.js","./_enum-bug-keys":"../node_modules/core-js/library/modules/_enum-bug-keys.js"}],"../node_modules/core-js/library/modules/_object-gopn-ext.js":[function(require,module,exports) {
// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
var toIObject = require('./_to-iobject');
var gOPN = require('./_object-gopn').f;
var toString = {}.toString;

var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames
  ? Object.getOwnPropertyNames(window) : [];

var getWindowNames = function (it) {
  try {
    return gOPN(it);
  } catch (e) {
    return windowNames.slice();
  }
};

module.exports.f = function getOwnPropertyNames(it) {
  return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it));
};

},{"./_to-iobject":"../node_modules/core-js/library/modules/_to-iobject.js","./_object-gopn":"../node_modules/core-js/library/modules/_object-gopn.js"}],"../node_modules/core-js/library/modules/_object-gopd.js":[function(require,module,exports) {
var pIE = require('./_object-pie');
var createDesc = require('./_property-desc');
var toIObject = require('./_to-iobject');
var toPrimitive = require('./_to-primitive');
var has = require('./_has');
var IE8_DOM_DEFINE = require('./_ie8-dom-define');
var gOPD = Object.getOwnPropertyDescriptor;

exports.f = require('./_descriptors') ? gOPD : function getOwnPropertyDescriptor(O, P) {
  O = toIObject(O);
  P = toPrimitive(P, true);
  if (IE8_DOM_DEFINE) try {
    return gOPD(O, P);
  } catch (e) { /* empty */ }
  if (has(O, P)) return createDesc(!pIE.f.call(O, P), O[P]);
};

},{"./_object-pie":"../node_modules/core-js/library/modules/_object-pie.js","./_property-desc":"../node_modules/core-js/library/modules/_property-desc.js","./_to-iobject":"../node_modules/core-js/library/modules/_to-iobject.js","./_to-primitive":"../node_modules/core-js/library/modules/_to-primitive.js","./_has":"../node_modules/core-js/library/modules/_has.js","./_ie8-dom-define":"../node_modules/core-js/library/modules/_ie8-dom-define.js","./_descriptors":"../node_modules/core-js/library/modules/_descriptors.js"}],"../node_modules/core-js/library/modules/es6.symbol.js":[function(require,module,exports) {

'use strict';
// ECMAScript 6 symbols shim
var global = require('./_global');
var has = require('./_has');
var DESCRIPTORS = require('./_descriptors');
var $export = require('./_export');
var redefine = require('./_redefine');
var META = require('./_meta').KEY;
var $fails = require('./_fails');
var shared = require('./_shared');
var setToStringTag = require('./_set-to-string-tag');
var uid = require('./_uid');
var wks = require('./_wks');
var wksExt = require('./_wks-ext');
var wksDefine = require('./_wks-define');
var enumKeys = require('./_enum-keys');
var isArray = require('./_is-array');
var anObject = require('./_an-object');
var isObject = require('./_is-object');
var toObject = require('./_to-object');
var toIObject = require('./_to-iobject');
var toPrimitive = require('./_to-primitive');
var createDesc = require('./_property-desc');
var _create = require('./_object-create');
var gOPNExt = require('./_object-gopn-ext');
var $GOPD = require('./_object-gopd');
var $GOPS = require('./_object-gops');
var $DP = require('./_object-dp');
var $keys = require('./_object-keys');
var gOPD = $GOPD.f;
var dP = $DP.f;
var gOPN = gOPNExt.f;
var $Symbol = global.Symbol;
var $JSON = global.JSON;
var _stringify = $JSON && $JSON.stringify;
var PROTOTYPE = 'prototype';
var HIDDEN = wks('_hidden');
var TO_PRIMITIVE = wks('toPrimitive');
var isEnum = {}.propertyIsEnumerable;
var SymbolRegistry = shared('symbol-registry');
var AllSymbols = shared('symbols');
var OPSymbols = shared('op-symbols');
var ObjectProto = Object[PROTOTYPE];
var USE_NATIVE = typeof $Symbol == 'function' && !!$GOPS.f;
var QObject = global.QObject;
// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173
var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild;

// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687
var setSymbolDesc = DESCRIPTORS && $fails(function () {
  return _create(dP({}, 'a', {
    get: function () { return dP(this, 'a', { value: 7 }).a; }
  })).a != 7;
}) ? function (it, key, D) {
  var protoDesc = gOPD(ObjectProto, key);
  if (protoDesc) delete ObjectProto[key];
  dP(it, key, D);
  if (protoDesc && it !== ObjectProto) dP(ObjectProto, key, protoDesc);
} : dP;

var wrap = function (tag) {
  var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]);
  sym._k = tag;
  return sym;
};

var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function (it) {
  return typeof it == 'symbol';
} : function (it) {
  return it instanceof $Symbol;
};

var $defineProperty = function defineProperty(it, key, D) {
  if (it === ObjectProto) $defineProperty(OPSymbols, key, D);
  anObject(it);
  key = toPrimitive(key, true);
  anObject(D);
  if (has(AllSymbols, key)) {
    if (!D.enumerable) {
      if (!has(it, HIDDEN)) dP(it, HIDDEN, createDesc(1, {}));
      it[HIDDEN][key] = true;
    } else {
      if (has(it, HIDDEN) && it[HIDDEN][key]) it[HIDDEN][key] = false;
      D = _create(D, { enumerable: createDesc(0, false) });
    } return setSymbolDesc(it, key, D);
  } return dP(it, key, D);
};
var $defineProperties = function defineProperties(it, P) {
  anObject(it);
  var keys = enumKeys(P = toIObject(P));
  var i = 0;
  var l = keys.length;
  var key;
  while (l > i) $defineProperty(it, key = keys[i++], P[key]);
  return it;
};
var $create = function create(it, P) {
  return P === undefined ? _create(it) : $defineProperties(_create(it), P);
};
var $propertyIsEnumerable = function propertyIsEnumerable(key) {
  var E = isEnum.call(this, key = toPrimitive(key, true));
  if (this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return false;
  return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true;
};
var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key) {
  it = toIObject(it);
  key = toPrimitive(key, true);
  if (it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return;
  var D = gOPD(it, key);
  if (D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) D.enumerable = true;
  return D;
};
var $getOwnPropertyNames = function getOwnPropertyNames(it) {
  var names = gOPN(toIObject(it));
  var result = [];
  var i = 0;
  var key;
  while (names.length > i) {
    if (!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META) result.push(key);
  } return result;
};
var $getOwnPropertySymbols = function getOwnPropertySymbols(it) {
  var IS_OP = it === ObjectProto;
  var names = gOPN(IS_OP ? OPSymbols : toIObject(it));
  var result = [];
  var i = 0;
  var key;
  while (names.length > i) {
    if (has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true)) result.push(AllSymbols[key]);
  } return result;
};

// 19.4.1.1 Symbol([description])
if (!USE_NATIVE) {
  $Symbol = function Symbol() {
    if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor!');
    var tag = uid(arguments.length > 0 ? arguments[0] : undefined);
    var $set = function (value) {
      if (this === ObjectProto) $set.call(OPSymbols, value);
      if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false;
      setSymbolDesc(this, tag, createDesc(1, value));
    };
    if (DESCRIPTORS && setter) setSymbolDesc(ObjectProto, tag, { configurable: true, set: $set });
    return wrap(tag);
  };
  redefine($Symbol[PROTOTYPE], 'toString', function toString() {
    return this._k;
  });

  $GOPD.f = $getOwnPropertyDescriptor;
  $DP.f = $defineProperty;
  require('./_object-gopn').f = gOPNExt.f = $getOwnPropertyNames;
  require('./_object-pie').f = $propertyIsEnumerable;
  $GOPS.f = $getOwnPropertySymbols;

  if (DESCRIPTORS && !require('./_library')) {
    redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true);
  }

  wksExt.f = function (name) {
    return wrap(wks(name));
  };
}

$export($export.G + $export.W + $export.F * !USE_NATIVE, { Symbol: $Symbol });

for (var es6Symbols = (
  // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14
  'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables'
).split(','), j = 0; es6Symbols.length > j;)wks(es6Symbols[j++]);

for (var wellKnownSymbols = $keys(wks.store), k = 0; wellKnownSymbols.length > k;) wksDefine(wellKnownSymbols[k++]);

$export($export.S + $export.F * !USE_NATIVE, 'Symbol', {
  // 19.4.2.1 Symbol.for(key)
  'for': function (key) {
    return has(SymbolRegistry, key += '')
      ? SymbolRegistry[key]
      : SymbolRegistry[key] = $Symbol(key);
  },
  // 19.4.2.5 Symbol.keyFor(sym)
  keyFor: function keyFor(sym) {
    if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol!');
    for (var key in SymbolRegistry) if (SymbolRegistry[key] === sym) return key;
  },
  useSetter: function () { setter = true; },
  useSimple: function () { setter = false; }
});

$export($export.S + $export.F * !USE_NATIVE, 'Object', {
  // 19.1.2.2 Object.create(O [, Properties])
  create: $create,
  // 19.1.2.4 Object.defineProperty(O, P, Attributes)
  defineProperty: $defineProperty,
  // 19.1.2.3 Object.defineProperties(O, Properties)
  defineProperties: $defineProperties,
  // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
  getOwnPropertyDescriptor: $getOwnPropertyDescriptor,
  // 19.1.2.7 Object.getOwnPropertyNames(O)
  getOwnPropertyNames: $getOwnPropertyNames,
  // 19.1.2.8 Object.getOwnPropertySymbols(O)
  getOwnPropertySymbols: $getOwnPropertySymbols
});

// Chrome 38 and 39 `Object.getOwnPropertySymbols` fails on primitives
// https://bugs.chromium.org/p/v8/issues/detail?id=3443
var FAILS_ON_PRIMITIVES = $fails(function () { $GOPS.f(1); });

$export($export.S + $export.F * FAILS_ON_PRIMITIVES, 'Object', {
  getOwnPropertySymbols: function getOwnPropertySymbols(it) {
    return $GOPS.f(toObject(it));
  }
});

// 24.3.2 JSON.stringify(value [, replacer [, space]])
$JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function () {
  var S = $Symbol();
  // MS Edge converts symbol values to JSON as {}
  // WebKit converts symbol values to JSON as null
  // V8 throws on boxed symbols
  return _stringify([S]) != '[null]' || _stringify({ a: S }) != '{}' || _stringify(Object(S)) != '{}';
})), 'JSON', {
  stringify: function stringify(it) {
    var args = [it];
    var i = 1;
    var replacer, $replacer;
    while (arguments.length > i) args.push(arguments[i++]);
    $replacer = replacer = args[1];
    if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined
    if (!isArray(replacer)) replacer = function (key, value) {
      if (typeof $replacer == 'function') value = $replacer.call(this, key, value);
      if (!isSymbol(value)) return value;
    };
    args[1] = replacer;
    return _stringify.apply($JSON, args);
  }
});

// 19.4.3.4 Symbol.prototype[@@toPrimitive](hint)
$Symbol[PROTOTYPE][TO_PRIMITIVE] || require('./_hide')($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf);
// 19.4.3.5 Symbol.prototype[@@toStringTag]
setToStringTag($Symbol, 'Symbol');
// 20.2.1.9 Math[@@toStringTag]
setToStringTag(Math, 'Math', true);
// 24.3.3 JSON[@@toStringTag]
setToStringTag(global.JSON, 'JSON', true);

},{"./_global":"../node_modules/core-js/library/modules/_global.js","./_has":"../node_modules/core-js/library/modules/_has.js","./_descriptors":"../node_modules/core-js/library/modules/_descriptors.js","./_export":"../node_modules/core-js/library/modules/_export.js","./_redefine":"../node_modules/core-js/library/modules/_redefine.js","./_meta":"../node_modules/core-js/library/modules/_meta.js","./_fails":"../node_modules/core-js/library/modules/_fails.js","./_shared":"../node_modules/core-js/library/modules/_shared.js","./_set-to-string-tag":"../node_modules/core-js/library/modules/_set-to-string-tag.js","./_uid":"../node_modules/core-js/library/modules/_uid.js","./_wks":"../node_modules/core-js/library/modules/_wks.js","./_wks-ext":"../node_modules/core-js/library/modules/_wks-ext.js","./_wks-define":"../node_modules/core-js/library/modules/_wks-define.js","./_enum-keys":"../node_modules/core-js/library/modules/_enum-keys.js","./_is-array":"../node_modules/core-js/library/modules/_is-array.js","./_an-object":"../node_modules/core-js/library/modules/_an-object.js","./_is-object":"../node_modules/core-js/library/modules/_is-object.js","./_to-object":"../node_modules/core-js/library/modules/_to-object.js","./_to-iobject":"../node_modules/core-js/library/modules/_to-iobject.js","./_to-primitive":"../node_modules/core-js/library/modules/_to-primitive.js","./_property-desc":"../node_modules/core-js/library/modules/_property-desc.js","./_object-create":"../node_modules/core-js/library/modules/_object-create.js","./_object-gopn-ext":"../node_modules/core-js/library/modules/_object-gopn-ext.js","./_object-gopd":"../node_modules/core-js/library/modules/_object-gopd.js","./_object-gops":"../node_modules/core-js/library/modules/_object-gops.js","./_object-dp":"../node_modules/core-js/library/modules/_object-dp.js","./_object-keys":"../node_modules/core-js/library/modules/_object-keys.js","./_object-gopn":"../node_modules/core-js/library/modules/_object-gopn.js","./_object-pie":"../node_modules/core-js/library/modules/_object-pie.js","./_library":"../node_modules/core-js/library/modules/_library.js","./_hide":"../node_modules/core-js/library/modules/_hide.js"}],"../node_modules/core-js/library/modules/es6.object.to-string.js":[function(require,module,exports) {

},{}],"../node_modules/core-js/library/modules/es7.symbol.async-iterator.js":[function(require,module,exports) {
require('./_wks-define')('asyncIterator');

},{"./_wks-define":"../node_modules/core-js/library/modules/_wks-define.js"}],"../node_modules/core-js/library/modules/es7.symbol.observable.js":[function(require,module,exports) {
require('./_wks-define')('observable');

},{"./_wks-define":"../node_modules/core-js/library/modules/_wks-define.js"}],"../node_modules/core-js/library/fn/symbol/index.js":[function(require,module,exports) {
require('../../modules/es6.symbol');
require('../../modules/es6.object.to-string');
require('../../modules/es7.symbol.async-iterator');
require('../../modules/es7.symbol.observable');
module.exports = require('../../modules/_core').Symbol;

},{"../../modules/es6.symbol":"../node_modules/core-js/library/modules/es6.symbol.js","../../modules/es6.object.to-string":"../node_modules/core-js/library/modules/es6.object.to-string.js","../../modules/es7.symbol.async-iterator":"../node_modules/core-js/library/modules/es7.symbol.async-iterator.js","../../modules/es7.symbol.observable":"../node_modules/core-js/library/modules/es7.symbol.observable.js","../../modules/_core":"../node_modules/core-js/library/modules/_core.js"}],"../node_modules/babel-runtime/core-js/symbol.js":[function(require,module,exports) {
module.exports = { "default": require("core-js/library/fn/symbol"), __esModule: true };
},{"core-js/library/fn/symbol":"../node_modules/core-js/library/fn/symbol/index.js"}],"../node_modules/babel-runtime/helpers/typeof.js":[function(require,module,exports) {
"use strict";

exports.__esModule = true;

var _iterator = require("../core-js/symbol/iterator");

var _iterator2 = _interopRequireDefault(_iterator);

var _symbol = require("../core-js/symbol");

var _symbol2 = _interopRequireDefault(_symbol);

var _typeof = typeof _symbol2.default === "function" && typeof _iterator2.default === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj; };

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

exports.default = typeof _symbol2.default === "function" && _typeof(_iterator2.default) === "symbol" ? function (obj) {
  return typeof obj === "undefined" ? "undefined" : _typeof(obj);
} : function (obj) {
  return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof(obj);
};
},{"../core-js/symbol/iterator":"../node_modules/babel-runtime/core-js/symbol/iterator.js","../core-js/symbol":"../node_modules/babel-runtime/core-js/symbol.js"}],"../node_modules/babel-runtime/helpers/possibleConstructorReturn.js":[function(require,module,exports) {
"use strict";

exports.__esModule = true;

var _typeof2 = require("../helpers/typeof");

var _typeof3 = _interopRequireDefault(_typeof2);

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

exports.default = function (self, call) {
  if (!self) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }

  return call && ((typeof call === "undefined" ? "undefined" : (0, _typeof3.default)(call)) === "object" || typeof call === "function") ? call : self;
};
},{"../helpers/typeof":"../node_modules/babel-runtime/helpers/typeof.js"}],"../node_modules/core-js/library/modules/_set-proto.js":[function(require,module,exports) {
// Works with __proto__ only. Old v8 can't work with null proto objects.
/* eslint-disable no-proto */
var isObject = require('./_is-object');
var anObject = require('./_an-object');
var check = function (O, proto) {
  anObject(O);
  if (!isObject(proto) && proto !== null) throw TypeError(proto + ": can't set as prototype!");
};
module.exports = {
  set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line
    function (test, buggy, set) {
      try {
        set = require('./_ctx')(Function.call, require('./_object-gopd').f(Object.prototype, '__proto__').set, 2);
        set(test, []);
        buggy = !(test instanceof Array);
      } catch (e) { buggy = true; }
      return function setPrototypeOf(O, proto) {
        check(O, proto);
        if (buggy) O.__proto__ = proto;
        else set(O, proto);
        return O;
      };
    }({}, false) : undefined),
  check: check
};

},{"./_is-object":"../node_modules/core-js/library/modules/_is-object.js","./_an-object":"../node_modules/core-js/library/modules/_an-object.js","./_ctx":"../node_modules/core-js/library/modules/_ctx.js","./_object-gopd":"../node_modules/core-js/library/modules/_object-gopd.js"}],"../node_modules/core-js/library/modules/es6.object.set-prototype-of.js":[function(require,module,exports) {
// 19.1.3.19 Object.setPrototypeOf(O, proto)
var $export = require('./_export');
$export($export.S, 'Object', { setPrototypeOf: require('./_set-proto').set });

},{"./_export":"../node_modules/core-js/library/modules/_export.js","./_set-proto":"../node_modules/core-js/library/modules/_set-proto.js"}],"../node_modules/core-js/library/fn/object/set-prototype-of.js":[function(require,module,exports) {
require('../../modules/es6.object.set-prototype-of');
module.exports = require('../../modules/_core').Object.setPrototypeOf;

},{"../../modules/es6.object.set-prototype-of":"../node_modules/core-js/library/modules/es6.object.set-prototype-of.js","../../modules/_core":"../node_modules/core-js/library/modules/_core.js"}],"../node_modules/babel-runtime/core-js/object/set-prototype-of.js":[function(require,module,exports) {
module.exports = { "default": require("core-js/library/fn/object/set-prototype-of"), __esModule: true };
},{"core-js/library/fn/object/set-prototype-of":"../node_modules/core-js/library/fn/object/set-prototype-of.js"}],"../node_modules/core-js/library/modules/es6.object.create.js":[function(require,module,exports) {
var $export = require('./_export');
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
$export($export.S, 'Object', { create: require('./_object-create') });

},{"./_export":"../node_modules/core-js/library/modules/_export.js","./_object-create":"../node_modules/core-js/library/modules/_object-create.js"}],"../node_modules/core-js/library/fn/object/create.js":[function(require,module,exports) {
require('../../modules/es6.object.create');
var $Object = require('../../modules/_core').Object;
module.exports = function create(P, D) {
  return $Object.create(P, D);
};

},{"../../modules/es6.object.create":"../node_modules/core-js/library/modules/es6.object.create.js","../../modules/_core":"../node_modules/core-js/library/modules/_core.js"}],"../node_modules/babel-runtime/core-js/object/create.js":[function(require,module,exports) {
module.exports = { "default": require("core-js/library/fn/object/create"), __esModule: true };
},{"core-js/library/fn/object/create":"../node_modules/core-js/library/fn/object/create.js"}],"../node_modules/babel-runtime/helpers/inherits.js":[function(require,module,exports) {
"use strict";

exports.__esModule = true;

var _setPrototypeOf = require("../core-js/object/set-prototype-of");

var _setPrototypeOf2 = _interopRequireDefault(_setPrototypeOf);

var _create = require("../core-js/object/create");

var _create2 = _interopRequireDefault(_create);

var _typeof2 = require("../helpers/typeof");

var _typeof3 = _interopRequireDefault(_typeof2);

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

exports.default = function (subClass, superClass) {
  if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : (0, _typeof3.default)(superClass)));
  }

  subClass.prototype = (0, _create2.default)(superClass && superClass.prototype, {
    constructor: {
      value: subClass,
      enumerable: false,
      writable: true,
      configurable: true
    }
  });
  if (superClass) _setPrototypeOf2.default ? (0, _setPrototypeOf2.default)(subClass, superClass) : subClass.__proto__ = superClass;
};
},{"../core-js/object/set-prototype-of":"../node_modules/babel-runtime/core-js/object/set-prototype-of.js","../core-js/object/create":"../node_modules/babel-runtime/core-js/object/create.js","../helpers/typeof":"../node_modules/babel-runtime/helpers/typeof.js"}],"../node_modules/core-js/library/modules/_object-assign.js":[function(require,module,exports) {
'use strict';
// 19.1.2.1 Object.assign(target, source, ...)
var DESCRIPTORS = require('./_descriptors');
var getKeys = require('./_object-keys');
var gOPS = require('./_object-gops');
var pIE = require('./_object-pie');
var toObject = require('./_to-object');
var IObject = require('./_iobject');
var $assign = Object.assign;

// should work with symbols and should have deterministic property order (V8 bug)
module.exports = !$assign || require('./_fails')(function () {
  var A = {};
  var B = {};
  // eslint-disable-next-line no-undef
  var S = Symbol();
  var K = 'abcdefghijklmnopqrst';
  A[S] = 7;
  K.split('').forEach(function (k) { B[k] = k; });
  return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K;
}) ? function assign(target, source) { // eslint-disable-line no-unused-vars
  var T = toObject(target);
  var aLen = arguments.length;
  var index = 1;
  var getSymbols = gOPS.f;
  var isEnum = pIE.f;
  while (aLen > index) {
    var S = IObject(arguments[index++]);
    var keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S);
    var length = keys.length;
    var j = 0;
    var key;
    while (length > j) {
      key = keys[j++];
      if (!DESCRIPTORS || isEnum.call(S, key)) T[key] = S[key];
    }
  } return T;
} : $assign;

},{"./_descriptors":"../node_modules/core-js/library/modules/_descriptors.js","./_object-keys":"../node_modules/core-js/library/modules/_object-keys.js","./_object-gops":"../node_modules/core-js/library/modules/_object-gops.js","./_object-pie":"../node_modules/core-js/library/modules/_object-pie.js","./_to-object":"../node_modules/core-js/library/modules/_to-object.js","./_iobject":"../node_modules/core-js/library/modules/_iobject.js","./_fails":"../node_modules/core-js/library/modules/_fails.js"}],"../node_modules/core-js/library/modules/es6.object.assign.js":[function(require,module,exports) {
// 19.1.3.1 Object.assign(target, source)
var $export = require('./_export');

$export($export.S + $export.F, 'Object', { assign: require('./_object-assign') });

},{"./_export":"../node_modules/core-js/library/modules/_export.js","./_object-assign":"../node_modules/core-js/library/modules/_object-assign.js"}],"../node_modules/core-js/library/fn/object/assign.js":[function(require,module,exports) {
require('../../modules/es6.object.assign');
module.exports = require('../../modules/_core').Object.assign;

},{"../../modules/es6.object.assign":"../node_modules/core-js/library/modules/es6.object.assign.js","../../modules/_core":"../node_modules/core-js/library/modules/_core.js"}],"../node_modules/babel-runtime/core-js/object/assign.js":[function(require,module,exports) {
module.exports = { "default": require("core-js/library/fn/object/assign"), __esModule: true };
},{"core-js/library/fn/object/assign":"../node_modules/core-js/library/fn/object/assign.js"}],"../node_modules/babel-runtime/helpers/extends.js":[function(require,module,exports) {
"use strict";

exports.__esModule = true;

var _assign = require("../core-js/object/assign");

var _assign2 = _interopRequireDefault(_assign);

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

exports.default = _assign2.default || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};
},{"../core-js/object/assign":"../node_modules/babel-runtime/core-js/object/assign.js"}],"../node_modules/core-js/library/modules/_object-sap.js":[function(require,module,exports) {
// most Object methods by ES6 should accept primitives
var $export = require('./_export');
var core = require('./_core');
var fails = require('./_fails');
module.exports = function (KEY, exec) {
  var fn = (core.Object || {})[KEY] || Object[KEY];
  var exp = {};
  exp[KEY] = exec(fn);
  $export($export.S + $export.F * fails(function () { fn(1); }), 'Object', exp);
};

},{"./_export":"../node_modules/core-js/library/modules/_export.js","./_core":"../node_modules/core-js/library/modules/_core.js","./_fails":"../node_modules/core-js/library/modules/_fails.js"}],"../node_modules/core-js/library/modules/es6.object.keys.js":[function(require,module,exports) {
// 19.1.2.14 Object.keys(O)
var toObject = require('./_to-object');
var $keys = require('./_object-keys');

require('./_object-sap')('keys', function () {
  return function keys(it) {
    return $keys(toObject(it));
  };
});

},{"./_to-object":"../node_modules/core-js/library/modules/_to-object.js","./_object-keys":"../node_modules/core-js/library/modules/_object-keys.js","./_object-sap":"../node_modules/core-js/library/modules/_object-sap.js"}],"../node_modules/core-js/library/fn/object/keys.js":[function(require,module,exports) {
require('../../modules/es6.object.keys');
module.exports = require('../../modules/_core').Object.keys;

},{"../../modules/es6.object.keys":"../node_modules/core-js/library/modules/es6.object.keys.js","../../modules/_core":"../node_modules/core-js/library/modules/_core.js"}],"../node_modules/babel-runtime/core-js/object/keys.js":[function(require,module,exports) {
module.exports = { "default": require("core-js/library/fn/object/keys"), __esModule: true };
},{"core-js/library/fn/object/keys":"../node_modules/core-js/library/fn/object/keys.js"}],"../node_modules/react-json-tree/lib/objType.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;

var _iterator = require('babel-runtime/core-js/symbol/iterator');

var _iterator2 = _interopRequireDefault(_iterator);

exports['default'] = objType;

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

function objType(obj) {
  var type = Object.prototype.toString.call(obj).slice(8, -1);
  if (type === 'Object' && typeof obj[_iterator2['default']] === 'function') {
    return 'Iterable';
  }

  if (type === 'Custom' && obj.constructor !== Object && obj instanceof Object) {
    // For projects implementing objects overriding `.prototype[Symbol.toStringTag]`
    return 'Object';
  }

  return type;
}
},{"babel-runtime/core-js/symbol/iterator":"../node_modules/babel-runtime/core-js/symbol/iterator.js"}],"../node_modules/core-js/library/modules/es6.object.get-own-property-names.js":[function(require,module,exports) {
// 19.1.2.7 Object.getOwnPropertyNames(O)
require('./_object-sap')('getOwnPropertyNames', function () {
  return require('./_object-gopn-ext').f;
});

},{"./_object-sap":"../node_modules/core-js/library/modules/_object-sap.js","./_object-gopn-ext":"../node_modules/core-js/library/modules/_object-gopn-ext.js"}],"../node_modules/core-js/library/fn/object/get-own-property-names.js":[function(require,module,exports) {
require('../../modules/es6.object.get-own-property-names');
var $Object = require('../../modules/_core').Object;
module.exports = function getOwnPropertyNames(it) {
  return $Object.getOwnPropertyNames(it);
};

},{"../../modules/es6.object.get-own-property-names":"../node_modules/core-js/library/modules/es6.object.get-own-property-names.js","../../modules/_core":"../node_modules/core-js/library/modules/_core.js"}],"../node_modules/babel-runtime/core-js/object/get-own-property-names.js":[function(require,module,exports) {
module.exports = { "default": require("core-js/library/fn/object/get-own-property-names"), __esModule: true };
},{"core-js/library/fn/object/get-own-property-names":"../node_modules/core-js/library/fn/object/get-own-property-names.js"}],"../node_modules/react-json-tree/lib/JSONArrow.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;

var _extends2 = require('babel-runtime/helpers/extends');

var _extends3 = _interopRequireDefault(_extends2);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

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

var JSONArrow = function JSONArrow(_ref) {
  var styling = _ref.styling,
      arrowStyle = _ref.arrowStyle,
      expanded = _ref.expanded,
      nodeType = _ref.nodeType,
      onClick = _ref.onClick;
  return _react2['default'].createElement(
    'div',
    (0, _extends3['default'])({}, styling('arrowContainer', arrowStyle), { onClick: onClick }),
    _react2['default'].createElement(
      'div',
      styling(['arrow', 'arrowSign'], nodeType, expanded, arrowStyle),
      '\u25B6',
      arrowStyle === 'double' && _react2['default'].createElement(
        'div',
        styling(['arrowSign', 'arrowSignInner']),
        '\u25B6'
      )
    )
  );
};

JSONArrow.propTypes = {
  styling: _propTypes2['default'].func.isRequired,
  arrowStyle: _propTypes2['default'].oneOf(['single', 'double']),
  expanded: _propTypes2['default'].bool.isRequired,
  nodeType: _propTypes2['default'].string.isRequired,
  onClick: _propTypes2['default'].func.isRequired
};

JSONArrow.defaultProps = {
  arrowStyle: 'single'
};

exports['default'] = JSONArrow;
},{"babel-runtime/helpers/extends":"../node_modules/babel-runtime/helpers/extends.js","react":"../node_modules/react/index.js","prop-types":"../node_modules/prop-types/index.js"}],"../node_modules/core-js/library/modules/_classof.js":[function(require,module,exports) {
// getting tag from 19.1.3.6 Object.prototype.toString()
var cof = require('./_cof');
var TAG = require('./_wks')('toStringTag');
// ES3 wrong here
var ARG = cof(function () { return arguments; }()) == 'Arguments';

// fallback for IE11 Script Access Denied error
var tryGet = function (it, key) {
  try {
    return it[key];
  } catch (e) { /* empty */ }
};

module.exports = function (it) {
  var O, T, B;
  return it === undefined ? 'Undefined' : it === null ? 'Null'
    // @@toStringTag case
    : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T
    // builtinTag case
    : ARG ? cof(O)
    // ES3 arguments fallback
    : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B;
};

},{"./_cof":"../node_modules/core-js/library/modules/_cof.js","./_wks":"../node_modules/core-js/library/modules/_wks.js"}],"../node_modules/core-js/library/modules/core.get-iterator-method.js":[function(require,module,exports) {
var classof = require('./_classof');
var ITERATOR = require('./_wks')('iterator');
var Iterators = require('./_iterators');
module.exports = require('./_core').getIteratorMethod = function (it) {
  if (it != undefined) return it[ITERATOR]
    || it['@@iterator']
    || Iterators[classof(it)];
};

},{"./_classof":"../node_modules/core-js/library/modules/_classof.js","./_wks":"../node_modules/core-js/library/modules/_wks.js","./_iterators":"../node_modules/core-js/library/modules/_iterators.js","./_core":"../node_modules/core-js/library/modules/_core.js"}],"../node_modules/core-js/library/modules/core.get-iterator.js":[function(require,module,exports) {
var anObject = require('./_an-object');
var get = require('./core.get-iterator-method');
module.exports = require('./_core').getIterator = function (it) {
  var iterFn = get(it);
  if (typeof iterFn != 'function') throw TypeError(it + ' is not iterable!');
  return anObject(iterFn.call(it));
};

},{"./_an-object":"../node_modules/core-js/library/modules/_an-object.js","./core.get-iterator-method":"../node_modules/core-js/library/modules/core.get-iterator-method.js","./_core":"../node_modules/core-js/library/modules/_core.js"}],"../node_modules/core-js/library/fn/get-iterator.js":[function(require,module,exports) {
require('../modules/web.dom.iterable');
require('../modules/es6.string.iterator');
module.exports = require('../modules/core.get-iterator');

},{"../modules/web.dom.iterable":"../node_modules/core-js/library/modules/web.dom.iterable.js","../modules/es6.string.iterator":"../node_modules/core-js/library/modules/es6.string.iterator.js","../modules/core.get-iterator":"../node_modules/core-js/library/modules/core.get-iterator.js"}],"../node_modules/babel-runtime/core-js/get-iterator.js":[function(require,module,exports) {
module.exports = { "default": require("core-js/library/fn/get-iterator"), __esModule: true };
},{"core-js/library/fn/get-iterator":"../node_modules/core-js/library/fn/get-iterator.js"}],"../node_modules/react-json-tree/lib/getCollectionEntries.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;

var _getIterator2 = require('babel-runtime/core-js/get-iterator');

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _getOwnPropertyNames = require('babel-runtime/core-js/object/get-own-property-names');

var _getOwnPropertyNames2 = _interopRequireDefault(_getOwnPropertyNames);

var _keys = require('babel-runtime/core-js/object/keys');

var _keys2 = _interopRequireDefault(_keys);

exports['default'] = getCollectionEntries;

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

function getLength(type, collection) {
  if (type === 'Object') {
    return (0, _keys2['default'])(collection).length;
  } else if (type === 'Array') {
    return collection.length;
  }

  return Infinity;
}

function isIterableMap(collection) {
  return typeof collection.set === 'function';
}

function getEntries(type, collection, sortObjectKeys) {
  var from = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
  var to = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : Infinity;

  var res = void 0;

  if (type === 'Object') {
    var keys = (0, _getOwnPropertyNames2['default'])(collection);

    if (sortObjectKeys) {
      keys.sort(sortObjectKeys === true ? undefined : sortObjectKeys);
    }

    keys = keys.slice(from, to + 1);

    res = {
      entries: keys.map(function (key) {
        return { key: key, value: collection[key] };
      })
    };
  } else if (type === 'Array') {
    res = {
      entries: collection.slice(from, to + 1).map(function (val, idx) {
        return { key: idx + from, value: val };
      })
    };
  } else {
    var idx = 0;
    var entries = [];
    var done = true;

    var isMap = isIterableMap(collection);

    for (var _iterator = collection, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3['default'])(_iterator);;) {
      var _ref;

      if (_isArray) {
        if (_i >= _iterator.length) break;
        _ref = _iterator[_i++];
      } else {
        _i = _iterator.next();
        if (_i.done) break;
        _ref = _i.value;
      }

      var item = _ref;

      if (idx > to) {
        done = false;
        break;
      }
      if (from <= idx) {
        if (isMap && Array.isArray(item)) {
          if (typeof item[0] === 'string' || typeof item[0] === 'number') {
            entries.push({ key: item[0], value: item[1] });
          } else {
            entries.push({
              key: '[entry ' + idx + ']',
              value: {
                '[key]': item[0],
                '[value]': item[1]
              }
            });
          }
        } else {
          entries.push({ key: idx, value: item });
        }
      }
      idx++;
    }

    res = {
      hasMore: !done,
      entries: entries
    };
  }

  return res;
}

function getRanges(from, to, limit) {
  var ranges = [];
  while (to - from > limit * limit) {
    limit = limit * limit;
  }
  for (var i = from; i <= to; i += limit) {
    ranges.push({ from: i, to: Math.min(to, i + limit - 1) });
  }

  return ranges;
}

function getCollectionEntries(type, collection, sortObjectKeys, limit) {
  var from = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0;
  var to = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : Infinity;

  var getEntriesBound = getEntries.bind(null, type, collection, sortObjectKeys);

  if (!limit) {
    return getEntriesBound().entries;
  }

  var isSubset = to < Infinity;
  var length = Math.min(to - from, getLength(type, collection));

  if (type !== 'Iterable') {
    if (length <= limit || limit < 7) {
      return getEntriesBound(from, to).entries;
    }
  } else {
    if (length <= limit && !isSubset) {
      return getEntriesBound(from, to).entries;
    }
  }

  var limitedEntries = void 0;
  if (type === 'Iterable') {
    var _getEntriesBound = getEntriesBound(from, from + limit - 1),
        hasMore = _getEntriesBound.hasMore,
        entries = _getEntriesBound.entries;

    limitedEntries = hasMore ? [].concat(entries, getRanges(from + limit, from + 2 * limit - 1, limit)) : entries;
  } else {
    limitedEntries = isSubset ? getRanges(from, to, limit) : [].concat(getEntriesBound(0, limit - 5).entries, getRanges(limit - 4, length - 5, limit), getEntriesBound(length - 4, length - 1).entries);
  }

  return limitedEntries;
}
},{"babel-runtime/core-js/get-iterator":"../node_modules/babel-runtime/core-js/get-iterator.js","babel-runtime/core-js/object/get-own-property-names":"../node_modules/babel-runtime/core-js/object/get-own-property-names.js","babel-runtime/core-js/object/keys":"../node_modules/babel-runtime/core-js/object/keys.js"}],"../node_modules/react-json-tree/lib/ItemRange.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;

var _extends2 = require('babel-runtime/helpers/extends');

var _extends3 = _interopRequireDefault(_extends2);

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = require('babel-runtime/helpers/inherits');

var _inherits3 = _interopRequireDefault(_inherits2);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _JSONArrow = require('./JSONArrow');

var _JSONArrow2 = _interopRequireDefault(_JSONArrow);

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

var ItemRange = function (_React$Component) {
  (0, _inherits3['default'])(ItemRange, _React$Component);

  function ItemRange(props) {
    (0, _classCallCheck3['default'])(this, ItemRange);

    var _this = (0, _possibleConstructorReturn3['default'])(this, _React$Component.call(this, props));

    _this.state = { expanded: false };

    _this.handleClick = _this.handleClick.bind(_this);
    return _this;
  }

  ItemRange.prototype.render = function render() {
    var _props = this.props,
        styling = _props.styling,
        from = _props.from,
        to = _props.to,
        renderChildNodes = _props.renderChildNodes,
        nodeType = _props.nodeType;


    return this.state.expanded ? _react2['default'].createElement(
      'div',
      styling('itemRange', this.state.expanded),
      renderChildNodes(this.props, from, to)
    ) : _react2['default'].createElement(
      'div',
      (0, _extends3['default'])({}, styling('itemRange', this.state.expanded), {
        onClick: this.handleClick
      }),
      _react2['default'].createElement(_JSONArrow2['default'], {
        nodeType: nodeType,
        styling: styling,
        expanded: false,
        onClick: this.handleClick,
        arrowStyle: 'double'
      }),
      from + ' ... ' + to
    );
  };

  ItemRange.prototype.handleClick = function handleClick() {
    this.setState({ expanded: !this.state.expanded });
  };

  return ItemRange;
}(_react2['default'].Component);

ItemRange.propTypes = {
  styling: _propTypes2['default'].func.isRequired,
  from: _propTypes2['default'].number.isRequired,
  to: _propTypes2['default'].number.isRequired,
  renderChildNodes: _propTypes2['default'].func.isRequired,
  nodeType: _propTypes2['default'].string.isRequired
};
exports['default'] = ItemRange;
},{"babel-runtime/helpers/extends":"../node_modules/babel-runtime/helpers/extends.js","babel-runtime/helpers/classCallCheck":"../node_modules/babel-runtime/helpers/classCallCheck.js","babel-runtime/helpers/possibleConstructorReturn":"../node_modules/babel-runtime/helpers/possibleConstructorReturn.js","babel-runtime/helpers/inherits":"../node_modules/babel-runtime/helpers/inherits.js","react":"../node_modules/react/index.js","prop-types":"../node_modules/prop-types/index.js","./JSONArrow":"../node_modules/react-json-tree/lib/JSONArrow.js"}],"../node_modules/react-json-tree/lib/JSONNestedNode.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;

var _keys = require('babel-runtime/core-js/object/keys');

var _keys2 = _interopRequireDefault(_keys);

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = require('babel-runtime/helpers/inherits');

var _inherits3 = _interopRequireDefault(_inherits2);

var _extends2 = require('babel-runtime/helpers/extends');

var _extends3 = _interopRequireDefault(_extends2);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _JSONArrow = require('./JSONArrow');

var _JSONArrow2 = _interopRequireDefault(_JSONArrow);

var _getCollectionEntries = require('./getCollectionEntries');

var _getCollectionEntries2 = _interopRequireDefault(_getCollectionEntries);

var _JSONNode = require('./JSONNode');

var _JSONNode2 = _interopRequireDefault(_JSONNode);

var _ItemRange = require('./ItemRange');

var _ItemRange2 = _interopRequireDefault(_ItemRange);

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

/**
 * Renders nested values (eg. objects, arrays, lists, etc.)
 */

function renderChildNodes(props, from, to) {
  var nodeType = props.nodeType,
      data = props.data,
      collectionLimit = props.collectionLimit,
      circularCache = props.circularCache,
      keyPath = props.keyPath,
      postprocessValue = props.postprocessValue,
      sortObjectKeys = props.sortObjectKeys;

  var childNodes = [];

  (0, _getCollectionEntries2['default'])(nodeType, data, sortObjectKeys, collectionLimit, from, to).forEach(function (entry) {
    if (entry.to) {
      childNodes.push(_react2['default'].createElement(_ItemRange2['default'], (0, _extends3['default'])({}, props, {
        key: 'ItemRange--' + entry.from + '-' + entry.to,
        from: entry.from,
        to: entry.to,
        renderChildNodes: renderChildNodes
      })));
    } else {
      var key = entry.key,
          value = entry.value;

      var isCircular = circularCache.indexOf(value) !== -1;

      var node = _react2['default'].createElement(_JSONNode2['default'], (0, _extends3['default'])({}, props, { postprocessValue: postprocessValue, collectionLimit: collectionLimit }, {
        key: 'Node--' + key,
        keyPath: [key].concat(keyPath),
        value: postprocessValue(value),
        circularCache: [].concat(circularCache, [value]),
        isCircular: isCircular,
        hideRoot: false
      }));

      if (node !== false) {
        childNodes.push(node);
      }
    }
  });

  return childNodes;
}

function getStateFromProps(props) {
  // calculate individual node expansion if necessary
  var expanded = props.shouldExpandNode && !props.isCircular ? props.shouldExpandNode(props.keyPath, props.data, props.level) : false;
  return {
    expanded: expanded
  };
}

var JSONNestedNode = function (_React$Component) {
  (0, _inherits3['default'])(JSONNestedNode, _React$Component);

  function JSONNestedNode(props) {
    (0, _classCallCheck3['default'])(this, JSONNestedNode);

    var _this = (0, _possibleConstructorReturn3['default'])(this, _React$Component.call(this, props));

    _this.handleClick = function () {
      if (_this.props.expandable) {
        _this.setState({ expanded: !_this.state.expanded });
      }
    };

    _this.state = getStateFromProps(props);
    return _this;
  }

  JSONNestedNode.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
    var nextState = getStateFromProps(nextProps);
    if (getStateFromProps(this.props).expanded !== nextState.expanded) {
      this.setState(nextState);
    }
  };

  JSONNestedNode.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps, nextState) {
    var _this2 = this;

    return !!(0, _keys2['default'])(nextProps).find(function (key) {
      return key !== 'circularCache' && (key === 'keyPath' ? nextProps[key].join('/') !== _this2.props[key].join('/') : nextProps[key] !== _this2.props[key]);
    }) || nextState.expanded !== this.state.expanded;
  };

  JSONNestedNode.prototype.render = function render() {
    var _props = this.props,
        getItemString = _props.getItemString,
        nodeTypeIndicator = _props.nodeTypeIndicator,
        nodeType = _props.nodeType,
        data = _props.data,
        hideRoot = _props.hideRoot,
        createItemString = _props.createItemString,
        styling = _props.styling,
        collectionLimit = _props.collectionLimit,
        keyPath = _props.keyPath,
        labelRenderer = _props.labelRenderer,
        expandable = _props.expandable;
    var expanded = this.state.expanded;

    var renderedChildren = expanded || hideRoot && this.props.level === 0 ? renderChildNodes((0, _extends3['default'])({}, this.props, { level: this.props.level + 1 })) : null;

    var itemType = _react2['default'].createElement(
      'span',
      styling('nestedNodeItemType', expanded),
      nodeTypeIndicator
    );
    var renderedItemString = getItemString(nodeType, data, itemType, createItemString(data, collectionLimit));
    var stylingArgs = [keyPath, nodeType, expanded, expandable];

    return hideRoot ? _react2['default'].createElement(
      'li',
      styling.apply(undefined, ['rootNode'].concat(stylingArgs)),
      _react2['default'].createElement(
        'ul',
        styling.apply(undefined, ['rootNodeChildren'].concat(stylingArgs)),
        renderedChildren
      )
    ) : _react2['default'].createElement(
      'li',
      styling.apply(undefined, ['nestedNode'].concat(stylingArgs)),
      expandable && _react2['default'].createElement(_JSONArrow2['default'], {
        styling: styling,
        nodeType: nodeType,
        expanded: expanded,
        onClick: this.handleClick
      }),
      _react2['default'].createElement(
        'label',
        (0, _extends3['default'])({}, styling.apply(undefined, [['label', 'nestedNodeLabel']].concat(stylingArgs)), {
          onClick: this.handleClick
        }),
        labelRenderer.apply(undefined, stylingArgs)
      ),
      _react2['default'].createElement(
        'span',
        (0, _extends3['default'])({}, styling.apply(undefined, ['nestedNodeItemString'].concat(stylingArgs)), {
          onClick: this.handleClick
        }),
        renderedItemString
      ),
      _react2['default'].createElement(
        'ul',
        styling.apply(undefined, ['nestedNodeChildren'].concat(stylingArgs)),
        renderedChildren
      )
    );
  };

  return JSONNestedNode;
}(_react2['default'].Component);

JSONNestedNode.propTypes = {
  getItemString: _propTypes2['default'].func.isRequired,
  nodeTypeIndicator: _propTypes2['default'].any,
  nodeType: _propTypes2['default'].string.isRequired,
  data: _propTypes2['default'].any,
  hideRoot: _propTypes2['default'].bool.isRequired,
  createItemString: _propTypes2['default'].func.isRequired,
  styling: _propTypes2['default'].func.isRequired,
  collectionLimit: _propTypes2['default'].number,
  keyPath: _propTypes2['default'].arrayOf(_propTypes2['default'].oneOfType([_propTypes2['default'].string, _propTypes2['default'].number])).isRequired,
  labelRenderer: _propTypes2['default'].func.isRequired,
  shouldExpandNode: _propTypes2['default'].func,
  level: _propTypes2['default'].number.isRequired,
  sortObjectKeys: _propTypes2['default'].oneOfType([_propTypes2['default'].func, _propTypes2['default'].bool]),
  isCircular: _propTypes2['default'].bool,
  expandable: _propTypes2['default'].bool
};
JSONNestedNode.defaultProps = {
  data: [],
  circularCache: [],
  level: 0,
  expandable: true
};
exports['default'] = JSONNestedNode;
},{"babel-runtime/core-js/object/keys":"../node_modules/babel-runtime/core-js/object/keys.js","babel-runtime/helpers/classCallCheck":"../node_modules/babel-runtime/helpers/classCallCheck.js","babel-runtime/helpers/possibleConstructorReturn":"../node_modules/babel-runtime/helpers/possibleConstructorReturn.js","babel-runtime/helpers/inherits":"../node_modules/babel-runtime/helpers/inherits.js","babel-runtime/helpers/extends":"../node_modules/babel-runtime/helpers/extends.js","react":"../node_modules/react/index.js","prop-types":"../node_modules/prop-types/index.js","./JSONArrow":"../node_modules/react-json-tree/lib/JSONArrow.js","./getCollectionEntries":"../node_modules/react-json-tree/lib/getCollectionEntries.js","./JSONNode":"../node_modules/react-json-tree/lib/JSONNode.js","./ItemRange":"../node_modules/react-json-tree/lib/ItemRange.js"}],"../node_modules/react-json-tree/lib/JSONObjectNode.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;

var _extends2 = require('babel-runtime/helpers/extends');

var _extends3 = _interopRequireDefault(_extends2);

var _objectWithoutProperties2 = require('babel-runtime/helpers/objectWithoutProperties');

var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2);

var _getOwnPropertyNames = require('babel-runtime/core-js/object/get-own-property-names');

var _getOwnPropertyNames2 = _interopRequireDefault(_getOwnPropertyNames);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _JSONNestedNode = require('./JSONNestedNode');

var _JSONNestedNode2 = _interopRequireDefault(_JSONNestedNode);

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

// Returns the "n Items" string for this node,
// generating and caching it if it hasn't been created yet.
function createItemString(data) {
  var len = (0, _getOwnPropertyNames2['default'])(data).length;
  return len + ' ' + (len !== 1 ? 'keys' : 'key');
}

// Configures <JSONNestedNode> to render an Object
var JSONObjectNode = function JSONObjectNode(_ref) {
  var data = _ref.data,
      props = (0, _objectWithoutProperties3['default'])(_ref, ['data']);
  return _react2['default'].createElement(_JSONNestedNode2['default'], (0, _extends3['default'])({}, props, {
    data: data,
    nodeType: 'Object',
    nodeTypeIndicator: props.nodeType === 'Error' ? 'Error()' : '{}',
    createItemString: createItemString,
    expandable: (0, _getOwnPropertyNames2['default'])(data).length > 0
  }));
};

JSONObjectNode.propTypes = {
  data: _propTypes2['default'].object,
  nodeType: _propTypes2['default'].string
};

exports['default'] = JSONObjectNode;
},{"babel-runtime/helpers/extends":"../node_modules/babel-runtime/helpers/extends.js","babel-runtime/helpers/objectWithoutProperties":"../node_modules/babel-runtime/helpers/objectWithoutProperties.js","babel-runtime/core-js/object/get-own-property-names":"../node_modules/babel-runtime/core-js/object/get-own-property-names.js","react":"../node_modules/react/index.js","prop-types":"../node_modules/prop-types/index.js","./JSONNestedNode":"../node_modules/react-json-tree/lib/JSONNestedNode.js"}],"../node_modules/react-json-tree/lib/JSONArrayNode.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;

var _extends2 = require('babel-runtime/helpers/extends');

var _extends3 = _interopRequireDefault(_extends2);

var _objectWithoutProperties2 = require('babel-runtime/helpers/objectWithoutProperties');

var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _JSONNestedNode = require('./JSONNestedNode');

var _JSONNestedNode2 = _interopRequireDefault(_JSONNestedNode);

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

// Returns the "n Items" string for this node,
// generating and caching it if it hasn't been created yet.
function createItemString(data) {
  return data.length + ' ' + (data.length !== 1 ? 'items' : 'item');
}

// Configures <JSONNestedNode> to render an Array
var JSONArrayNode = function JSONArrayNode(_ref) {
  var data = _ref.data,
      props = (0, _objectWithoutProperties3['default'])(_ref, ['data']);
  return _react2['default'].createElement(_JSONNestedNode2['default'], (0, _extends3['default'])({}, props, {
    data: data,
    nodeType: 'Array',
    nodeTypeIndicator: '[]',
    createItemString: createItemString,
    expandable: data.length > 0
  }));
};

JSONArrayNode.propTypes = {
  data: _propTypes2['default'].array
};

exports['default'] = JSONArrayNode;
},{"babel-runtime/helpers/extends":"../node_modules/babel-runtime/helpers/extends.js","babel-runtime/helpers/objectWithoutProperties":"../node_modules/babel-runtime/helpers/objectWithoutProperties.js","react":"../node_modules/react/index.js","prop-types":"../node_modules/prop-types/index.js","./JSONNestedNode":"../node_modules/react-json-tree/lib/JSONNestedNode.js"}],"../node_modules/core-js/library/modules/_is-integer.js":[function(require,module,exports) {
// 20.1.2.3 Number.isInteger(number)
var isObject = require('./_is-object');
var floor = Math.floor;
module.exports = function isInteger(it) {
  return !isObject(it) && isFinite(it) && floor(it) === it;
};

},{"./_is-object":"../node_modules/core-js/library/modules/_is-object.js"}],"../node_modules/core-js/library/modules/es6.number.is-safe-integer.js":[function(require,module,exports) {
// 20.1.2.5 Number.isSafeInteger(number)
var $export = require('./_export');
var isInteger = require('./_is-integer');
var abs = Math.abs;

$export($export.S, 'Number', {
  isSafeInteger: function isSafeInteger(number) {
    return isInteger(number) && abs(number) <= 0x1fffffffffffff;
  }
});

},{"./_export":"../node_modules/core-js/library/modules/_export.js","./_is-integer":"../node_modules/core-js/library/modules/_is-integer.js"}],"../node_modules/core-js/library/fn/number/is-safe-integer.js":[function(require,module,exports) {
require('../../modules/es6.number.is-safe-integer');
module.exports = require('../../modules/_core').Number.isSafeInteger;

},{"../../modules/es6.number.is-safe-integer":"../node_modules/core-js/library/modules/es6.number.is-safe-integer.js","../../modules/_core":"../node_modules/core-js/library/modules/_core.js"}],"../node_modules/babel-runtime/core-js/number/is-safe-integer.js":[function(require,module,exports) {
module.exports = { "default": require("core-js/library/fn/number/is-safe-integer"), __esModule: true };
},{"core-js/library/fn/number/is-safe-integer":"../node_modules/core-js/library/fn/number/is-safe-integer.js"}],"../node_modules/react-json-tree/lib/JSONIterableNode.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;

var _extends2 = require('babel-runtime/helpers/extends');

var _extends3 = _interopRequireDefault(_extends2);

var _objectWithoutProperties2 = require('babel-runtime/helpers/objectWithoutProperties');

var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2);

var _getIterator2 = require('babel-runtime/core-js/get-iterator');

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _isSafeInteger = require('babel-runtime/core-js/number/is-safe-integer');

var _isSafeInteger2 = _interopRequireDefault(_isSafeInteger);

exports['default'] = JSONIterableNode;

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _JSONNestedNode = require('./JSONNestedNode');

var _JSONNestedNode2 = _interopRequireDefault(_JSONNestedNode);

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

// Returns the "n Items" string for this node,
// generating and caching it if it hasn't been created yet.
function createItemString(data, limit) {
  var count = 0;
  var hasMore = false;
  if ((0, _isSafeInteger2['default'])(data.size)) {
    count = data.size;
  } else {
    // eslint-disable-next-line no-unused-vars
    for (var _iterator = data, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3['default'])(_iterator);;) {
      var _ref;

      if (_isArray) {
        if (_i >= _iterator.length) break;
        _ref = _iterator[_i++];
      } else {
        _i = _iterator.next();
        if (_i.done) break;
        _ref = _i.value;
      }

      var entry = _ref;

      if (limit && count + 1 > limit) {
        hasMore = true;
        break;
      }
      count += 1;
    }
  }
  return '' + (hasMore ? '>' : '') + count + ' ' + (count !== 1 ? 'entries' : 'entry');
}

// Configures <JSONNestedNode> to render an iterable
function JSONIterableNode(_ref2) {
  var props = (0, _objectWithoutProperties3['default'])(_ref2, []);

  return _react2['default'].createElement(_JSONNestedNode2['default'], (0, _extends3['default'])({}, props, {
    nodeType: 'Iterable',
    nodeTypeIndicator: '()',
    createItemString: createItemString
  }));
}
},{"babel-runtime/helpers/extends":"../node_modules/babel-runtime/helpers/extends.js","babel-runtime/helpers/objectWithoutProperties":"../node_modules/babel-runtime/helpers/objectWithoutProperties.js","babel-runtime/core-js/get-iterator":"../node_modules/babel-runtime/core-js/get-iterator.js","babel-runtime/core-js/number/is-safe-integer":"../node_modules/babel-runtime/core-js/number/is-safe-integer.js","react":"../node_modules/react/index.js","./JSONNestedNode":"../node_modules/react-json-tree/lib/JSONNestedNode.js"}],"../node_modules/react-json-tree/lib/JSONValueNode.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

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

/**
 * Renders simple values (eg. strings, numbers, booleans, etc)
 */

var JSONValueNode = function JSONValueNode(_ref) {
  var nodeType = _ref.nodeType,
      styling = _ref.styling,
      labelRenderer = _ref.labelRenderer,
      keyPath = _ref.keyPath,
      valueRenderer = _ref.valueRenderer,
      value = _ref.value,
      valueGetter = _ref.valueGetter;
  return _react2['default'].createElement(
    'li',
    styling('value', nodeType, keyPath),
    _react2['default'].createElement(
      'label',
      styling(['label', 'valueLabel'], nodeType, keyPath),
      labelRenderer(keyPath, nodeType, false, false)
    ),
    _react2['default'].createElement(
      'span',
      styling('valueText', nodeType, keyPath),
      valueRenderer.apply(undefined, [valueGetter(value), value].concat(keyPath))
    )
  );
};

JSONValueNode.propTypes = {
  nodeType: _propTypes2['default'].string.isRequired,
  styling: _propTypes2['default'].func.isRequired,
  labelRenderer: _propTypes2['default'].func.isRequired,
  keyPath: _propTypes2['default'].arrayOf(_propTypes2['default'].oneOfType([_propTypes2['default'].string, _propTypes2['default'].number])).isRequired,
  valueRenderer: _propTypes2['default'].func.isRequired,
  value: _propTypes2['default'].any,
  valueGetter: _propTypes2['default'].func
};

JSONValueNode.defaultProps = {
  valueGetter: function valueGetter(value) {
    return value;
  }
};

exports['default'] = JSONValueNode;
},{"react":"../node_modules/react/index.js","prop-types":"../node_modules/prop-types/index.js"}],"../node_modules/react-json-tree/lib/JSONNode.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;

var _extends2 = require('babel-runtime/helpers/extends');

var _extends3 = _interopRequireDefault(_extends2);

var _objectWithoutProperties2 = require('babel-runtime/helpers/objectWithoutProperties');

var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _objType = require('./objType');

var _objType2 = _interopRequireDefault(_objType);

var _JSONObjectNode = require('./JSONObjectNode');

var _JSONObjectNode2 = _interopRequireDefault(_JSONObjectNode);

var _JSONArrayNode = require('./JSONArrayNode');

var _JSONArrayNode2 = _interopRequireDefault(_JSONArrayNode);

var _JSONIterableNode = require('./JSONIterableNode');

var _JSONIterableNode2 = _interopRequireDefault(_JSONIterableNode);

var _JSONValueNode = require('./JSONValueNode');

var _JSONValueNode2 = _interopRequireDefault(_JSONValueNode);

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

var JSONNode = function JSONNode(_ref) {
  var getItemString = _ref.getItemString,
      keyPath = _ref.keyPath,
      labelRenderer = _ref.labelRenderer,
      styling = _ref.styling,
      value = _ref.value,
      valueRenderer = _ref.valueRenderer,
      isCustomNode = _ref.isCustomNode,
      rest = (0, _objectWithoutProperties3['default'])(_ref, ['getItemString', 'keyPath', 'labelRenderer', 'styling', 'value', 'valueRenderer', 'isCustomNode']);

  var nodeType = isCustomNode(value) ? 'Custom' : (0, _objType2['default'])(value);

  var simpleNodeProps = {
    getItemString: getItemString,
    key: keyPath[0],
    keyPath: keyPath,
    labelRenderer: labelRenderer,
    nodeType: nodeType,
    styling: styling,
    value: value,
    valueRenderer: valueRenderer
  };

  var nestedNodeProps = (0, _extends3['default'])({}, rest, simpleNodeProps, {
    data: value,
    isCustomNode: isCustomNode
  });

  switch (nodeType) {
    case 'Object':
    case 'Error':
    case 'WeakMap':
    case 'WeakSet':
      return _react2['default'].createElement(_JSONObjectNode2['default'], nestedNodeProps);
    case 'Array':
      return _react2['default'].createElement(_JSONArrayNode2['default'], nestedNodeProps);
    case 'Iterable':
    case 'Map':
    case 'Set':
      return _react2['default'].createElement(_JSONIterableNode2['default'], nestedNodeProps);
    case 'String':
      return _react2['default'].createElement(_JSONValueNode2['default'], (0, _extends3['default'])({}, simpleNodeProps, { valueGetter: function valueGetter(raw) {
          return '"' + raw + '"';
        } }));
    case 'Number':
      return _react2['default'].createElement(_JSONValueNode2['default'], simpleNodeProps);
    case 'Boolean':
      return _react2['default'].createElement(_JSONValueNode2['default'], (0, _extends3['default'])({}, simpleNodeProps, {
        valueGetter: function valueGetter(raw) {
          return raw ? 'true' : 'false';
        }
      }));
    case 'Date':
      return _react2['default'].createElement(_JSONValueNode2['default'], (0, _extends3['default'])({}, simpleNodeProps, {
        valueGetter: function valueGetter(raw) {
          return raw.toISOString();
        }
      }));
    case 'Null':
      return _react2['default'].createElement(_JSONValueNode2['default'], (0, _extends3['default'])({}, simpleNodeProps, { valueGetter: function valueGetter() {
          return 'null';
        } }));
    case 'Undefined':
      return _react2['default'].createElement(_JSONValueNode2['default'], (0, _extends3['default'])({}, simpleNodeProps, { valueGetter: function valueGetter() {
          return 'undefined';
        } }));
    case 'Function':
    case 'Symbol':
      return _react2['default'].createElement(_JSONValueNode2['default'], (0, _extends3['default'])({}, simpleNodeProps, {
        valueGetter: function valueGetter(raw) {
          return raw.toString();
        }
      }));
    case 'Custom':
      return _react2['default'].createElement(_JSONValueNode2['default'], simpleNodeProps);
    default:
      return _react2['default'].createElement(_JSONValueNode2['default'], (0, _extends3['default'])({}, simpleNodeProps, { valueGetter: function valueGetter(raw) {
          return '<' + nodeType + '>';
        } }));
  }
};

JSONNode.propTypes = {
  getItemString: _propTypes2['default'].func.isRequired,
  keyPath: _propTypes2['default'].arrayOf(_propTypes2['default'].oneOfType([_propTypes2['default'].string, _propTypes2['default'].number])).isRequired,
  labelRenderer: _propTypes2['default'].func.isRequired,
  styling: _propTypes2['default'].func.isRequired,
  value: _propTypes2['default'].any,
  valueRenderer: _propTypes2['default'].func.isRequired,
  isCustomNode: _propTypes2['default'].func.isRequired
};

exports['default'] = JSONNode;
},{"babel-runtime/helpers/extends":"../node_modules/babel-runtime/helpers/extends.js","babel-runtime/helpers/objectWithoutProperties":"../node_modules/babel-runtime/helpers/objectWithoutProperties.js","react":"../node_modules/react/index.js","prop-types":"../node_modules/prop-types/index.js","./objType":"../node_modules/react-json-tree/lib/objType.js","./JSONObjectNode":"../node_modules/react-json-tree/lib/JSONObjectNode.js","./JSONArrayNode":"../node_modules/react-json-tree/lib/JSONArrayNode.js","./JSONIterableNode":"../node_modules/react-json-tree/lib/JSONIterableNode.js","./JSONValueNode":"../node_modules/react-json-tree/lib/JSONValueNode.js"}],"../node_modules/core-js/library/modules/core.is-iterable.js":[function(require,module,exports) {
var classof = require('./_classof');
var ITERATOR = require('./_wks')('iterator');
var Iterators = require('./_iterators');
module.exports = require('./_core').isIterable = function (it) {
  var O = Object(it);
  return O[ITERATOR] !== undefined
    || '@@iterator' in O
    // eslint-disable-next-line no-prototype-builtins
    || Iterators.hasOwnProperty(classof(O));
};

},{"./_classof":"../node_modules/core-js/library/modules/_classof.js","./_wks":"../node_modules/core-js/library/modules/_wks.js","./_iterators":"../node_modules/core-js/library/modules/_iterators.js","./_core":"../node_modules/core-js/library/modules/_core.js"}],"../node_modules/core-js/library/fn/is-iterable.js":[function(require,module,exports) {
require('../modules/web.dom.iterable');
require('../modules/es6.string.iterator');
module.exports = require('../modules/core.is-iterable');

},{"../modules/web.dom.iterable":"../node_modules/core-js/library/modules/web.dom.iterable.js","../modules/es6.string.iterator":"../node_modules/core-js/library/modules/es6.string.iterator.js","../modules/core.is-iterable":"../node_modules/core-js/library/modules/core.is-iterable.js"}],"../node_modules/babel-runtime/core-js/is-iterable.js":[function(require,module,exports) {
module.exports = { "default": require("core-js/library/fn/is-iterable"), __esModule: true };
},{"core-js/library/fn/is-iterable":"../node_modules/core-js/library/fn/is-iterable.js"}],"../node_modules/babel-runtime/helpers/slicedToArray.js":[function(require,module,exports) {
"use strict";

exports.__esModule = true;

var _isIterable2 = require("../core-js/is-iterable");

var _isIterable3 = _interopRequireDefault(_isIterable2);

var _getIterator2 = require("../core-js/get-iterator");

var _getIterator3 = _interopRequireDefault(_getIterator2);

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

exports.default = function () {
  function sliceIterator(arr, i) {
    var _arr = [];
    var _n = true;
    var _d = false;
    var _e = undefined;

    try {
      for (var _i = (0, _getIterator3.default)(arr), _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"]) _i["return"]();
      } finally {
        if (_d) throw _e;
      }
    }

    return _arr;
  }

  return function (arr, i) {
    if (Array.isArray(arr)) {
      return arr;
    } else if ((0, _isIterable3.default)(Object(arr))) {
      return sliceIterator(arr, i);
    } else {
      throw new TypeError("Invalid attempt to destructure non-iterable instance");
    }
  };
}();
},{"../core-js/is-iterable":"../node_modules/babel-runtime/core-js/is-iterable.js","../core-js/get-iterator":"../node_modules/babel-runtime/core-js/get-iterator.js"}],"../node_modules/lodash.curry/index.js":[function(require,module,exports) {
var global = arguments[3];
/**
 * lodash (Custom Build) <https://lodash.com/>
 * Build: `lodash modularize exports="npm" -o ./`
 * Copyright jQuery Foundation and other contributors <https://jquery.org/>
 * Released under MIT license <https://lodash.com/license>
 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 */

/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';

/** Used as the internal argument placeholder. */
var PLACEHOLDER = '__lodash_placeholder__';

/** Used to compose bitmasks for function metadata. */
var BIND_FLAG = 1,
    BIND_KEY_FLAG = 2,
    CURRY_BOUND_FLAG = 4,
    CURRY_FLAG = 8,
    CURRY_RIGHT_FLAG = 16,
    PARTIAL_FLAG = 32,
    PARTIAL_RIGHT_FLAG = 64,
    ARY_FLAG = 128,
    REARG_FLAG = 256,
    FLIP_FLAG = 512;

/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0,
    MAX_SAFE_INTEGER = 9007199254740991,
    MAX_INTEGER = 1.7976931348623157e+308,
    NAN = 0 / 0;

/** Used to associate wrap methods with their bit flags. */
var wrapFlags = [
  ['ary', ARY_FLAG],
  ['bind', BIND_FLAG],
  ['bindKey', BIND_KEY_FLAG],
  ['curry', CURRY_FLAG],
  ['curryRight', CURRY_RIGHT_FLAG],
  ['flip', FLIP_FLAG],
  ['partial', PARTIAL_FLAG],
  ['partialRight', PARTIAL_RIGHT_FLAG],
  ['rearg', REARG_FLAG]
];

/** `Object#toString` result references. */
var funcTag = '[object Function]',
    genTag = '[object GeneratorFunction]',
    symbolTag = '[object Symbol]';

/**
 * Used to match `RegExp`
 * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
 */
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;

/** Used to match leading and trailing whitespace. */
var reTrim = /^\s+|\s+$/g;

/** Used to match wrap detail comments. */
var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,
    reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/,
    reSplitDetails = /,? & /;

/** Used to detect bad signed hexadecimal string values. */
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;

/** Used to detect binary string values. */
var reIsBinary = /^0b[01]+$/i;

/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;

/** Used to detect octal string values. */
var reIsOctal = /^0o[0-7]+$/i;

/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;

/** Built-in method references without a dependency on `root`. */
var freeParseInt = parseInt;

/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;

/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;

/** Used as a reference to the global object. */
var root = freeGlobal || freeSelf || Function('return this')();

/**
 * A faster alternative to `Function#apply`, this function invokes `func`
 * with the `this` binding of `thisArg` and the arguments of `args`.
 *
 * @private
 * @param {Function} func The function to invoke.
 * @param {*} thisArg The `this` binding of `func`.
 * @param {Array} args The arguments to invoke `func` with.
 * @returns {*} Returns the result of `func`.
 */
function apply(func, thisArg, args) {
  switch (args.length) {
    case 0: return func.call(thisArg);
    case 1: return func.call(thisArg, args[0]);
    case 2: return func.call(thisArg, args[0], args[1]);
    case 3: return func.call(thisArg, args[0], args[1], args[2]);
  }
  return func.apply(thisArg, args);
}

/**
 * A specialized version of `_.forEach` for arrays without support for
 * iteratee shorthands.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array} Returns `array`.
 */
function arrayEach(array, iteratee) {
  var index = -1,
      length = array ? array.length : 0;

  while (++index < length) {
    if (iteratee(array[index], index, array) === false) {
      break;
    }
  }
  return array;
}

/**
 * A specialized version of `_.includes` for arrays without support for
 * specifying an index to search from.
 *
 * @private
 * @param {Array} [array] The array to inspect.
 * @param {*} target The value to search for.
 * @returns {boolean} Returns `true` if `target` is found, else `false`.
 */
function arrayIncludes(array, value) {
  var length = array ? array.length : 0;
  return !!length && baseIndexOf(array, value, 0) > -1;
}

/**
 * The base implementation of `_.findIndex` and `_.findLastIndex` without
 * support for iteratee shorthands.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {Function} predicate The function invoked per iteration.
 * @param {number} fromIndex The index to search from.
 * @param {boolean} [fromRight] Specify iterating from right to left.
 * @returns {number} Returns the index of the matched value, else `-1`.
 */
function baseFindIndex(array, predicate, fromIndex, fromRight) {
  var length = array.length,
      index = fromIndex + (fromRight ? 1 : -1);

  while ((fromRight ? index-- : ++index < length)) {
    if (predicate(array[index], index, array)) {
      return index;
    }
  }
  return -1;
}

/**
 * The base implementation of `_.indexOf` without `fromIndex` bounds checks.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {*} value The value to search for.
 * @param {number} fromIndex The index to search from.
 * @returns {number} Returns the index of the matched value, else `-1`.
 */
function baseIndexOf(array, value, fromIndex) {
  if (value !== value) {
    return baseFindIndex(array, baseIsNaN, fromIndex);
  }
  var index = fromIndex - 1,
      length = array.length;

  while (++index < length) {
    if (array[index] === value) {
      return index;
    }
  }
  return -1;
}

/**
 * The base implementation of `_.isNaN` without support for number objects.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
 */
function baseIsNaN(value) {
  return value !== value;
}

/**
 * Gets the number of `placeholder` occurrences in `array`.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {*} placeholder The placeholder to search for.
 * @returns {number} Returns the placeholder count.
 */
function countHolders(array, placeholder) {
  var length = array.length,
      result = 0;

  while (length--) {
    if (array[length] === placeholder) {
      result++;
    }
  }
  return result;
}

/**
 * Gets the value at `key` of `object`.
 *
 * @private
 * @param {Object} [object] The object to query.
 * @param {string} key The key of the property to get.
 * @returns {*} Returns the property value.
 */
function getValue(object, key) {
  return object == null ? undefined : object[key];
}

/**
 * Checks if `value` is a host object in IE < 9.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a host object, else `false`.
 */
function isHostObject(value) {
  // Many host objects are `Object` objects that can coerce to strings
  // despite having improperly defined `toString` methods.
  var result = false;
  if (value != null && typeof value.toString != 'function') {
    try {
      result = !!(value + '');
    } catch (e) {}
  }
  return result;
}

/**
 * Replaces all `placeholder` elements in `array` with an internal placeholder
 * and returns an array of their indexes.
 *
 * @private
 * @param {Array} array The array to modify.
 * @param {*} placeholder The placeholder to replace.
 * @returns {Array} Returns the new array of placeholder indexes.
 */
function replaceHolders(array, placeholder) {
  var index = -1,
      length = array.length,
      resIndex = 0,
      result = [];

  while (++index < length) {
    var value = array[index];
    if (value === placeholder || value === PLACEHOLDER) {
      array[index] = PLACEHOLDER;
      result[resIndex++] = index;
    }
  }
  return result;
}

/** Used for built-in method references. */
var funcProto = Function.prototype,
    objectProto = Object.prototype;

/** Used to detect overreaching core-js shims. */
var coreJsData = root['__core-js_shared__'];

/** Used to detect methods masquerading as native. */
var maskSrcKey = (function() {
  var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
  return uid ? ('Symbol(src)_1.' + uid) : '';
}());

/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * Used to resolve the
 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
 * of values.
 */
var objectToString = objectProto.toString;

/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
  funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
  .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);

/** Built-in value references. */
var objectCreate = Object.create;

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max,
    nativeMin = Math.min;

/* Used to set `toString` methods. */
var defineProperty = (function() {
  var func = getNative(Object, 'defineProperty'),
      name = getNative.name;

  return (name && name.length > 2) ? func : undefined;
}());

/**
 * The base implementation of `_.create` without support for assigning
 * properties to the created object.
 *
 * @private
 * @param {Object} prototype The object to inherit from.
 * @returns {Object} Returns the new object.
 */
function baseCreate(proto) {
  return isObject(proto) ? objectCreate(proto) : {};
}

/**
 * The base implementation of `_.isNative` without bad shim checks.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a native function,
 *  else `false`.
 */
function baseIsNative(value) {
  if (!isObject(value) || isMasked(value)) {
    return false;
  }
  var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor;
  return pattern.test(toSource(value));
}

/**
 * Creates an array that is the composition of partially applied arguments,
 * placeholders, and provided arguments into a single array of arguments.
 *
 * @private
 * @param {Array} args The provided arguments.
 * @param {Array} partials The arguments to prepend to those provided.
 * @param {Array} holders The `partials` placeholder indexes.
 * @params {boolean} [isCurried] Specify composing for a curried function.
 * @returns {Array} Returns the new array of composed arguments.
 */
function composeArgs(args, partials, holders, isCurried) {
  var argsIndex = -1,
      argsLength = args.length,
      holdersLength = holders.length,
      leftIndex = -1,
      leftLength = partials.length,
      rangeLength = nativeMax(argsLength - holdersLength, 0),
      result = Array(leftLength + rangeLength),
      isUncurried = !isCurried;

  while (++leftIndex < leftLength) {
    result[leftIndex] = partials[leftIndex];
  }
  while (++argsIndex < holdersLength) {
    if (isUncurried || argsIndex < argsLength) {
      result[holders[argsIndex]] = args[argsIndex];
    }
  }
  while (rangeLength--) {
    result[leftIndex++] = args[argsIndex++];
  }
  return result;
}

/**
 * This function is like `composeArgs` except that the arguments composition
 * is tailored for `_.partialRight`.
 *
 * @private
 * @param {Array} args The provided arguments.
 * @param {Array} partials The arguments to append to those provided.
 * @param {Array} holders The `partials` placeholder indexes.
 * @params {boolean} [isCurried] Specify composing for a curried function.
 * @returns {Array} Returns the new array of composed arguments.
 */
function composeArgsRight(args, partials, holders, isCurried) {
  var argsIndex = -1,
      argsLength = args.length,
      holdersIndex = -1,
      holdersLength = holders.length,
      rightIndex = -1,
      rightLength = partials.length,
      rangeLength = nativeMax(argsLength - holdersLength, 0),
      result = Array(rangeLength + rightLength),
      isUncurried = !isCurried;

  while (++argsIndex < rangeLength) {
    result[argsIndex] = args[argsIndex];
  }
  var offset = argsIndex;
  while (++rightIndex < rightLength) {
    result[offset + rightIndex] = partials[rightIndex];
  }
  while (++holdersIndex < holdersLength) {
    if (isUncurried || argsIndex < argsLength) {
      result[offset + holders[holdersIndex]] = args[argsIndex++];
    }
  }
  return result;
}

/**
 * Copies the values of `source` to `array`.
 *
 * @private
 * @param {Array} source The array to copy values from.
 * @param {Array} [array=[]] The array to copy values to.
 * @returns {Array} Returns `array`.
 */
function copyArray(source, array) {
  var index = -1,
      length = source.length;

  array || (array = Array(length));
  while (++index < length) {
    array[index] = source[index];
  }
  return array;
}

/**
 * Creates a function that wraps `func` to invoke it with the optional `this`
 * binding of `thisArg`.
 *
 * @private
 * @param {Function} func The function to wrap.
 * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
 * @param {*} [thisArg] The `this` binding of `func`.
 * @returns {Function} Returns the new wrapped function.
 */
function createBind(func, bitmask, thisArg) {
  var isBind = bitmask & BIND_FLAG,
      Ctor = createCtor(func);

  function wrapper() {
    var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
    return fn.apply(isBind ? thisArg : this, arguments);
  }
  return wrapper;
}

/**
 * Creates a function that produces an instance of `Ctor` regardless of
 * whether it was invoked as part of a `new` expression or by `call` or `apply`.
 *
 * @private
 * @param {Function} Ctor The constructor to wrap.
 * @returns {Function} Returns the new wrapped function.
 */
function createCtor(Ctor) {
  return function() {
    // Use a `switch` statement to work with class constructors. See
    // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
    // for more details.
    var args = arguments;
    switch (args.length) {
      case 0: return new Ctor;
      case 1: return new Ctor(args[0]);
      case 2: return new Ctor(args[0], args[1]);
      case 3: return new Ctor(args[0], args[1], args[2]);
      case 4: return new Ctor(args[0], args[1], args[2], args[3]);
      case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);
      case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);
      case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
    }
    var thisBinding = baseCreate(Ctor.prototype),
        result = Ctor.apply(thisBinding, args);

    // Mimic the constructor's `return` behavior.
    // See https://es5.github.io/#x13.2.2 for more details.
    return isObject(result) ? result : thisBinding;
  };
}

/**
 * Creates a function that wraps `func` to enable currying.
 *
 * @private
 * @param {Function} func The function to wrap.
 * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
 * @param {number} arity The arity of `func`.
 * @returns {Function} Returns the new wrapped function.
 */
function createCurry(func, bitmask, arity) {
  var Ctor = createCtor(func);

  function wrapper() {
    var length = arguments.length,
        args = Array(length),
        index = length,
        placeholder = getHolder(wrapper);

    while (index--) {
      args[index] = arguments[index];
    }
    var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder)
      ? []
      : replaceHolders(args, placeholder);

    length -= holders.length;
    if (length < arity) {
      return createRecurry(
        func, bitmask, createHybrid, wrapper.placeholder, undefined,
        args, holders, undefined, undefined, arity - length);
    }
    var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
    return apply(fn, this, args);
  }
  return wrapper;
}

/**
 * Creates a function that wraps `func` to invoke it with optional `this`
 * binding of `thisArg`, partial application, and currying.
 *
 * @private
 * @param {Function|string} func The function or method name to wrap.
 * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
 * @param {*} [thisArg] The `this` binding of `func`.
 * @param {Array} [partials] The arguments to prepend to those provided to
 *  the new function.
 * @param {Array} [holders] The `partials` placeholder indexes.
 * @param {Array} [partialsRight] The arguments to append to those provided
 *  to the new function.
 * @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
 * @param {Array} [argPos] The argument positions of the new function.
 * @param {number} [ary] The arity cap of `func`.
 * @param {number} [arity] The arity of `func`.
 * @returns {Function} Returns the new wrapped function.
 */
function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {
  var isAry = bitmask & ARY_FLAG,
      isBind = bitmask & BIND_FLAG,
      isBindKey = bitmask & BIND_KEY_FLAG,
      isCurried = bitmask & (CURRY_FLAG | CURRY_RIGHT_FLAG),
      isFlip = bitmask & FLIP_FLAG,
      Ctor = isBindKey ? undefined : createCtor(func);

  function wrapper() {
    var length = arguments.length,
        args = Array(length),
        index = length;

    while (index--) {
      args[index] = arguments[index];
    }
    if (isCurried) {
      var placeholder = getHolder(wrapper),
          holdersCount = countHolders(args, placeholder);
    }
    if (partials) {
      args = composeArgs(args, partials, holders, isCurried);
    }
    if (partialsRight) {
      args = composeArgsRight(args, partialsRight, holdersRight, isCurried);
    }
    length -= holdersCount;
    if (isCurried && length < arity) {
      var newHolders = replaceHolders(args, placeholder);
      return createRecurry(
        func, bitmask, createHybrid, wrapper.placeholder, thisArg,
        args, newHolders, argPos, ary, arity - length
      );
    }
    var thisBinding = isBind ? thisArg : this,
        fn = isBindKey ? thisBinding[func] : func;

    length = args.length;
    if (argPos) {
      args = reorder(args, argPos);
    } else if (isFlip && length > 1) {
      args.reverse();
    }
    if (isAry && ary < length) {
      args.length = ary;
    }
    if (this && this !== root && this instanceof wrapper) {
      fn = Ctor || createCtor(fn);
    }
    return fn.apply(thisBinding, args);
  }
  return wrapper;
}

/**
 * Creates a function that wraps `func` to invoke it with the `this` binding
 * of `thisArg` and `partials` prepended to the arguments it receives.
 *
 * @private
 * @param {Function} func The function to wrap.
 * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
 * @param {*} thisArg The `this` binding of `func`.
 * @param {Array} partials The arguments to prepend to those provided to
 *  the new function.
 * @returns {Function} Returns the new wrapped function.
 */
function createPartial(func, bitmask, thisArg, partials) {
  var isBind = bitmask & BIND_FLAG,
      Ctor = createCtor(func);

  function wrapper() {
    var argsIndex = -1,
        argsLength = arguments.length,
        leftIndex = -1,
        leftLength = partials.length,
        args = Array(leftLength + argsLength),
        fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;

    while (++leftIndex < leftLength) {
      args[leftIndex] = partials[leftIndex];
    }
    while (argsLength--) {
      args[leftIndex++] = arguments[++argsIndex];
    }
    return apply(fn, isBind ? thisArg : this, args);
  }
  return wrapper;
}

/**
 * Creates a function that wraps `func` to continue currying.
 *
 * @private
 * @param {Function} func The function to wrap.
 * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
 * @param {Function} wrapFunc The function to create the `func` wrapper.
 * @param {*} placeholder The placeholder value.
 * @param {*} [thisArg] The `this` binding of `func`.
 * @param {Array} [partials] The arguments to prepend to those provided to
 *  the new function.
 * @param {Array} [holders] The `partials` placeholder indexes.
 * @param {Array} [argPos] The argument positions of the new function.
 * @param {number} [ary] The arity cap of `func`.
 * @param {number} [arity] The arity of `func`.
 * @returns {Function} Returns the new wrapped function.
 */
function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) {
  var isCurry = bitmask & CURRY_FLAG,
      newHolders = isCurry ? holders : undefined,
      newHoldersRight = isCurry ? undefined : holders,
      newPartials = isCurry ? partials : undefined,
      newPartialsRight = isCurry ? undefined : partials;

  bitmask |= (isCurry ? PARTIAL_FLAG : PARTIAL_RIGHT_FLAG);
  bitmask &= ~(isCurry ? PARTIAL_RIGHT_FLAG : PARTIAL_FLAG);

  if (!(bitmask & CURRY_BOUND_FLAG)) {
    bitmask &= ~(BIND_FLAG | BIND_KEY_FLAG);
  }

  var result = wrapFunc(func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, newHoldersRight, argPos, ary, arity);
  result.placeholder = placeholder;
  return setWrapToString(result, func, bitmask);
}

/**
 * Creates a function that either curries or invokes `func` with optional
 * `this` binding and partially applied arguments.
 *
 * @private
 * @param {Function|string} func The function or method name to wrap.
 * @param {number} bitmask The bitmask flags.
 *  The bitmask may be composed of the following flags:
 *     1 - `_.bind`
 *     2 - `_.bindKey`
 *     4 - `_.curry` or `_.curryRight` of a bound function
 *     8 - `_.curry`
 *    16 - `_.curryRight`
 *    32 - `_.partial`
 *    64 - `_.partialRight`
 *   128 - `_.rearg`
 *   256 - `_.ary`
 *   512 - `_.flip`
 * @param {*} [thisArg] The `this` binding of `func`.
 * @param {Array} [partials] The arguments to be partially applied.
 * @param {Array} [holders] The `partials` placeholder indexes.
 * @param {Array} [argPos] The argument positions of the new function.
 * @param {number} [ary] The arity cap of `func`.
 * @param {number} [arity] The arity of `func`.
 * @returns {Function} Returns the new wrapped function.
 */
function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
  var isBindKey = bitmask & BIND_KEY_FLAG;
  if (!isBindKey && typeof func != 'function') {
    throw new TypeError(FUNC_ERROR_TEXT);
  }
  var length = partials ? partials.length : 0;
  if (!length) {
    bitmask &= ~(PARTIAL_FLAG | PARTIAL_RIGHT_FLAG);
    partials = holders = undefined;
  }
  ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0);
  arity = arity === undefined ? arity : toInteger(arity);
  length -= holders ? holders.length : 0;

  if (bitmask & PARTIAL_RIGHT_FLAG) {
    var partialsRight = partials,
        holdersRight = holders;

    partials = holders = undefined;
  }

  var newData = [
    func, bitmask, thisArg, partials, holders, partialsRight, holdersRight,
    argPos, ary, arity
  ];

  func = newData[0];
  bitmask = newData[1];
  thisArg = newData[2];
  partials = newData[3];
  holders = newData[4];
  arity = newData[9] = newData[9] == null
    ? (isBindKey ? 0 : func.length)
    : nativeMax(newData[9] - length, 0);

  if (!arity && bitmask & (CURRY_FLAG | CURRY_RIGHT_FLAG)) {
    bitmask &= ~(CURRY_FLAG | CURRY_RIGHT_FLAG);
  }
  if (!bitmask || bitmask == BIND_FLAG) {
    var result = createBind(func, bitmask, thisArg);
  } else if (bitmask == CURRY_FLAG || bitmask == CURRY_RIGHT_FLAG) {
    result = createCurry(func, bitmask, arity);
  } else if ((bitmask == PARTIAL_FLAG || bitmask == (BIND_FLAG | PARTIAL_FLAG)) && !holders.length) {
    result = createPartial(func, bitmask, thisArg, partials);
  } else {
    result = createHybrid.apply(undefined, newData);
  }
  return setWrapToString(result, func, bitmask);
}

/**
 * Gets the argument placeholder value for `func`.
 *
 * @private
 * @param {Function} func The function to inspect.
 * @returns {*} Returns the placeholder value.
 */
function getHolder(func) {
  var object = func;
  return object.placeholder;
}

/**
 * Gets the native function at `key` of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {string} key The key of the method to get.
 * @returns {*} Returns the function if it's native, else `undefined`.
 */
function getNative(object, key) {
  var value = getValue(object, key);
  return baseIsNative(value) ? value : undefined;
}

/**
 * Extracts wrapper details from the `source` body comment.
 *
 * @private
 * @param {string} source The source to inspect.
 * @returns {Array} Returns the wrapper details.
 */
function getWrapDetails(source) {
  var match = source.match(reWrapDetails);
  return match ? match[1].split(reSplitDetails) : [];
}

/**
 * Inserts wrapper `details` in a comment at the top of the `source` body.
 *
 * @private
 * @param {string} source The source to modify.
 * @returns {Array} details The details to insert.
 * @returns {string} Returns the modified source.
 */
function insertWrapDetails(source, details) {
  var length = details.length,
      lastIndex = length - 1;

  details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex];
  details = details.join(length > 2 ? ', ' : ' ');
  return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n');
}

/**
 * Checks if `value` is a valid array-like index.
 *
 * @private
 * @param {*} value The value to check.
 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
 */
function isIndex(value, length) {
  length = length == null ? MAX_SAFE_INTEGER : length;
  return !!length &&
    (typeof value == 'number' || reIsUint.test(value)) &&
    (value > -1 && value % 1 == 0 && value < length);
}

/**
 * Checks if `func` has its source masked.
 *
 * @private
 * @param {Function} func The function to check.
 * @returns {boolean} Returns `true` if `func` is masked, else `false`.
 */
function isMasked(func) {
  return !!maskSrcKey && (maskSrcKey in func);
}

/**
 * Reorder `array` according to the specified indexes where the element at
 * the first index is assigned as the first element, the element at
 * the second index is assigned as the second element, and so on.
 *
 * @private
 * @param {Array} array The array to reorder.
 * @param {Array} indexes The arranged array indexes.
 * @returns {Array} Returns `array`.
 */
function reorder(array, indexes) {
  var arrLength = array.length,
      length = nativeMin(indexes.length, arrLength),
      oldArray = copyArray(array);

  while (length--) {
    var index = indexes[length];
    array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;
  }
  return array;
}

/**
 * Sets the `toString` method of `wrapper` to mimic the source of `reference`
 * with wrapper details in a comment at the top of the source body.
 *
 * @private
 * @param {Function} wrapper The function to modify.
 * @param {Function} reference The reference function.
 * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
 * @returns {Function} Returns `wrapper`.
 */
var setWrapToString = !defineProperty ? identity : function(wrapper, reference, bitmask) {
  var source = (reference + '');
  return defineProperty(wrapper, 'toString', {
    'configurable': true,
    'enumerable': false,
    'value': constant(insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask)))
  });
};

/**
 * Converts `func` to its source code.
 *
 * @private
 * @param {Function} func The function to process.
 * @returns {string} Returns the source code.
 */
function toSource(func) {
  if (func != null) {
    try {
      return funcToString.call(func);
    } catch (e) {}
    try {
      return (func + '');
    } catch (e) {}
  }
  return '';
}

/**
 * Updates wrapper `details` based on `bitmask` flags.
 *
 * @private
 * @returns {Array} details The details to modify.
 * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
 * @returns {Array} Returns `details`.
 */
function updateWrapDetails(details, bitmask) {
  arrayEach(wrapFlags, function(pair) {
    var value = '_.' + pair[0];
    if ((bitmask & pair[1]) && !arrayIncludes(details, value)) {
      details.push(value);
    }
  });
  return details.sort();
}

/**
 * Creates a function that accepts arguments of `func` and either invokes
 * `func` returning its result, if at least `arity` number of arguments have
 * been provided, or returns a function that accepts the remaining `func`
 * arguments, and so on. The arity of `func` may be specified if `func.length`
 * is not sufficient.
 *
 * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,
 * may be used as a placeholder for provided arguments.
 *
 * **Note:** This method doesn't set the "length" property of curried functions.
 *
 * @static
 * @memberOf _
 * @since 2.0.0
 * @category Function
 * @param {Function} func The function to curry.
 * @param {number} [arity=func.length] The arity of `func`.
 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
 * @returns {Function} Returns the new curried function.
 * @example
 *
 * var abc = function(a, b, c) {
 *   return [a, b, c];
 * };
 *
 * var curried = _.curry(abc);
 *
 * curried(1)(2)(3);
 * // => [1, 2, 3]
 *
 * curried(1, 2)(3);
 * // => [1, 2, 3]
 *
 * curried(1, 2, 3);
 * // => [1, 2, 3]
 *
 * // Curried with placeholders.
 * curried(1)(_, 3)(2);
 * // => [1, 2, 3]
 */
function curry(func, arity, guard) {
  arity = guard ? undefined : arity;
  var result = createWrap(func, CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
  result.placeholder = curry.placeholder;
  return result;
}

/**
 * Checks if `value` is classified as a `Function` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a function, else `false`.
 * @example
 *
 * _.isFunction(_);
 * // => true
 *
 * _.isFunction(/abc/);
 * // => false
 */
function isFunction(value) {
  // The use of `Object#toString` avoids issues with the `typeof` operator
  // in Safari 8-9 which returns 'object' for typed array and other constructors.
  var tag = isObject(value) ? objectToString.call(value) : '';
  return tag == funcTag || tag == genTag;
}

/**
 * Checks if `value` is the
 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
 * @example
 *
 * _.isObject({});
 * // => true
 *
 * _.isObject([1, 2, 3]);
 * // => true
 *
 * _.isObject(_.noop);
 * // => true
 *
 * _.isObject(null);
 * // => false
 */
function isObject(value) {
  var type = typeof value;
  return !!value && (type == 'object' || type == 'function');
}

/**
 * Checks if `value` is object-like. A value is object-like if it's not `null`
 * and has a `typeof` result of "object".
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
 * @example
 *
 * _.isObjectLike({});
 * // => true
 *
 * _.isObjectLike([1, 2, 3]);
 * // => true
 *
 * _.isObjectLike(_.noop);
 * // => false
 *
 * _.isObjectLike(null);
 * // => false
 */
function isObjectLike(value) {
  return !!value && typeof value == 'object';
}

/**
 * Checks if `value` is classified as a `Symbol` primitive or object.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
 * @example
 *
 * _.isSymbol(Symbol.iterator);
 * // => true
 *
 * _.isSymbol('abc');
 * // => false
 */
function isSymbol(value) {
  return typeof value == 'symbol' ||
    (isObjectLike(value) && objectToString.call(value) == symbolTag);
}

/**
 * Converts `value` to a finite number.
 *
 * @static
 * @memberOf _
 * @since 4.12.0
 * @category Lang
 * @param {*} value The value to convert.
 * @returns {number} Returns the converted number.
 * @example
 *
 * _.toFinite(3.2);
 * // => 3.2
 *
 * _.toFinite(Number.MIN_VALUE);
 * // => 5e-324
 *
 * _.toFinite(Infinity);
 * // => 1.7976931348623157e+308
 *
 * _.toFinite('3.2');
 * // => 3.2
 */
function toFinite(value) {
  if (!value) {
    return value === 0 ? value : 0;
  }
  value = toNumber(value);
  if (value === INFINITY || value === -INFINITY) {
    var sign = (value < 0 ? -1 : 1);
    return sign * MAX_INTEGER;
  }
  return value === value ? value : 0;
}

/**
 * Converts `value` to an integer.
 *
 * **Note:** This method is loosely based on
 * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to convert.
 * @returns {number} Returns the converted integer.
 * @example
 *
 * _.toInteger(3.2);
 * // => 3
 *
 * _.toInteger(Number.MIN_VALUE);
 * // => 0
 *
 * _.toInteger(Infinity);
 * // => 1.7976931348623157e+308
 *
 * _.toInteger('3.2');
 * // => 3
 */
function toInteger(value) {
  var result = toFinite(value),
      remainder = result % 1;

  return result === result ? (remainder ? result - remainder : result) : 0;
}

/**
 * Converts `value` to a number.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to process.
 * @returns {number} Returns the number.
 * @example
 *
 * _.toNumber(3.2);
 * // => 3.2
 *
 * _.toNumber(Number.MIN_VALUE);
 * // => 5e-324
 *
 * _.toNumber(Infinity);
 * // => Infinity
 *
 * _.toNumber('3.2');
 * // => 3.2
 */
function toNumber(value) {
  if (typeof value == 'number') {
    return value;
  }
  if (isSymbol(value)) {
    return NAN;
  }
  if (isObject(value)) {
    var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
    value = isObject(other) ? (other + '') : other;
  }
  if (typeof value != 'string') {
    return value === 0 ? value : +value;
  }
  value = value.replace(reTrim, '');
  var isBinary = reIsBinary.test(value);
  return (isBinary || reIsOctal.test(value))
    ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
    : (reIsBadHex.test(value) ? NAN : +value);
}

/**
 * Creates a function that returns `value`.
 *
 * @static
 * @memberOf _
 * @since 2.4.0
 * @category Util
 * @param {*} value The value to return from the new function.
 * @returns {Function} Returns the new constant function.
 * @example
 *
 * var objects = _.times(2, _.constant({ 'a': 1 }));
 *
 * console.log(objects);
 * // => [{ 'a': 1 }, { 'a': 1 }]
 *
 * console.log(objects[0] === objects[1]);
 * // => true
 */
function constant(value) {
  return function() {
    return value;
  };
}

/**
 * This method returns the first argument it receives.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Util
 * @param {*} value Any value.
 * @returns {*} Returns `value`.
 * @example
 *
 * var object = { 'a': 1 };
 *
 * console.log(_.identity(object) === object);
 * // => true
 */
function identity(value) {
  return value;
}

// Assign default placeholders.
curry.placeholder = {};

module.exports = curry;

},{}],"../node_modules/base16/lib/threezerotwofour.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;
exports['default'] = {
  scheme: 'threezerotwofour',
  author: 'jan t. sott (http://github.com/idleberg)',
  base00: '#090300',
  base01: '#3a3432',
  base02: '#4a4543',
  base03: '#5c5855',
  base04: '#807d7c',
  base05: '#a5a2a2',
  base06: '#d6d5d4',
  base07: '#f7f7f7',
  base08: '#db2d20',
  base09: '#e8bbd0',
  base0A: '#fded02',
  base0B: '#01a252',
  base0C: '#b5e4f4',
  base0D: '#01a0e4',
  base0E: '#a16a94',
  base0F: '#cdab53'
};
module.exports = exports['default'];
},{}],"../node_modules/base16/lib/apathy.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;
exports['default'] = {
  scheme: 'apathy',
  author: 'jannik siebert (https://github.com/janniks)',
  base00: '#031A16',
  base01: '#0B342D',
  base02: '#184E45',
  base03: '#2B685E',
  base04: '#5F9C92',
  base05: '#81B5AC',
  base06: '#A7CEC8',
  base07: '#D2E7E4',
  base08: '#3E9688',
  base09: '#3E7996',
  base0A: '#3E4C96',
  base0B: '#883E96',
  base0C: '#963E4C',
  base0D: '#96883E',
  base0E: '#4C963E',
  base0F: '#3E965B'
};
module.exports = exports['default'];
},{}],"../node_modules/base16/lib/ashes.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;
exports['default'] = {
  scheme: 'ashes',
  author: 'jannik siebert (https://github.com/janniks)',
  base00: '#1C2023',
  base01: '#393F45',
  base02: '#565E65',
  base03: '#747C84',
  base04: '#ADB3BA',
  base05: '#C7CCD1',
  base06: '#DFE2E5',
  base07: '#F3F4F5',
  base08: '#C7AE95',
  base09: '#C7C795',
  base0A: '#AEC795',
  base0B: '#95C7AE',
  base0C: '#95AEC7',
  base0D: '#AE95C7',
  base0E: '#C795AE',
  base0F: '#C79595'
};
module.exports = exports['default'];
},{}],"../node_modules/base16/lib/atelier-dune.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;
exports['default'] = {
  scheme: 'atelier dune',
  author: 'bram de haan (http://atelierbram.github.io/syntax-highlighting/atelier-schemes/dune)',
  base00: '#20201d',
  base01: '#292824',
  base02: '#6e6b5e',
  base03: '#7d7a68',
  base04: '#999580',
  base05: '#a6a28c',
  base06: '#e8e4cf',
  base07: '#fefbec',
  base08: '#d73737',
  base09: '#b65611',
  base0A: '#cfb017',
  base0B: '#60ac39',
  base0C: '#1fad83',
  base0D: '#6684e1',
  base0E: '#b854d4',
  base0F: '#d43552'
};
module.exports = exports['default'];
},{}],"../node_modules/base16/lib/atelier-forest.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;
exports['default'] = {
  scheme: 'atelier forest',
  author: 'bram de haan (http://atelierbram.github.io/syntax-highlighting/atelier-schemes/forest)',
  base00: '#1b1918',
  base01: '#2c2421',
  base02: '#68615e',
  base03: '#766e6b',
  base04: '#9c9491',
  base05: '#a8a19f',
  base06: '#e6e2e0',
  base07: '#f1efee',
  base08: '#f22c40',
  base09: '#df5320',
  base0A: '#d5911a',
  base0B: '#5ab738',
  base0C: '#00ad9c',
  base0D: '#407ee7',
  base0E: '#6666ea',
  base0F: '#c33ff3'
};
module.exports = exports['default'];
},{}],"../node_modules/base16/lib/atelier-heath.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;
exports['default'] = {
  scheme: 'atelier heath',
  author: 'bram de haan (http://atelierbram.github.io/syntax-highlighting/atelier-schemes/heath)',
  base00: '#1b181b',
  base01: '#292329',
  base02: '#695d69',
  base03: '#776977',
  base04: '#9e8f9e',
  base05: '#ab9bab',
  base06: '#d8cad8',
  base07: '#f7f3f7',
  base08: '#ca402b',
  base09: '#a65926',
  base0A: '#bb8a35',
  base0B: '#379a37',
  base0C: '#159393',
  base0D: '#516aec',
  base0E: '#7b59c0',
  base0F: '#cc33cc'
};
module.exports = exports['default'];
},{}],"../node_modules/base16/lib/atelier-lakeside.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;
exports['default'] = {
  scheme: 'atelier lakeside',
  author: 'bram de haan (http://atelierbram.github.io/syntax-highlighting/atelier-schemes/lakeside/)',
  base00: '#161b1d',
  base01: '#1f292e',
  base02: '#516d7b',
  base03: '#5a7b8c',
  base04: '#7195a8',
  base05: '#7ea2b4',
  base06: '#c1e4f6',
  base07: '#ebf8ff',
  base08: '#d22d72',
  base09: '#935c25',
  base0A: '#8a8a0f',
  base0B: '#568c3b',
  base0C: '#2d8f6f',
  base0D: '#257fad',
  base0E: '#5d5db1',
  base0F: '#b72dd2'
};
module.exports = exports['default'];
},{}],"../node_modules/base16/lib/atelier-seaside.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;
exports['default'] = {
  scheme: 'atelier seaside',
  author: 'bram de haan (http://atelierbram.github.io/syntax-highlighting/atelier-schemes/seaside/)',
  base00: '#131513',
  base01: '#242924',
  base02: '#5e6e5e',
  base03: '#687d68',
  base04: '#809980',
  base05: '#8ca68c',
  base06: '#cfe8cf',
  base07: '#f0fff0',
  base08: '#e6193c',
  base09: '#87711d',
  base0A: '#c3c322',
  base0B: '#29a329',
  base0C: '#1999b3',
  base0D: '#3d62f5',
  base0E: '#ad2bee',
  base0F: '#e619c3'
};
module.exports = exports['default'];
},{}],"../node_modules/base16/lib/bespin.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;
exports['default'] = {
  scheme: 'bespin',
  author: 'jan t. sott',
  base00: '#28211c',
  base01: '#36312e',
  base02: '#5e5d5c',
  base03: '#666666',
  base04: '#797977',
  base05: '#8a8986',
  base06: '#9d9b97',
  base07: '#baae9e',
  base08: '#cf6a4c',
  base09: '#cf7d34',
  base0A: '#f9ee98',
  base0B: '#54be0d',
  base0C: '#afc4db',
  base0D: '#5ea6ea',
  base0E: '#9b859d',
  base0F: '#937121'
};
module.exports = exports['default'];
},{}],"../node_modules/base16/lib/brewer.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;
exports['default'] = {
  scheme: 'brewer',
  author: 'timothée poisot (http://github.com/tpoisot)',
  base00: '#0c0d0e',
  base01: '#2e2f30',
  base02: '#515253',
  base03: '#737475',
  base04: '#959697',
  base05: '#b7b8b9',
  base06: '#dadbdc',
  base07: '#fcfdfe',
  base08: '#e31a1c',
  base09: '#e6550d',
  base0A: '#dca060',
  base0B: '#31a354',
  base0C: '#80b1d3',
  base0D: '#3182bd',
  base0E: '#756bb1',
  base0F: '#b15928'
};
module.exports = exports['default'];
},{}],"../node_modules/base16/lib/bright.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;
exports['default'] = {
  scheme: 'bright',
  author: 'chris kempson (http://chriskempson.com)',
  base00: '#000000',
  base01: '#303030',
  base02: '#505050',
  base03: '#b0b0b0',
  base04: '#d0d0d0',
  base05: '#e0e0e0',
  base06: '#f5f5f5',
  base07: '#ffffff',
  base08: '#fb0120',
  base09: '#fc6d24',
  base0A: '#fda331',
  base0B: '#a1c659',
  base0C: '#76c7b7',
  base0D: '#6fb3d2',
  base0E: '#d381c3',
  base0F: '#be643c'
};
module.exports = exports['default'];
},{}],"../node_modules/base16/lib/chalk.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;
exports['default'] = {
  scheme: 'chalk',
  author: 'chris kempson (http://chriskempson.com)',
  base00: '#151515',
  base01: '#202020',
  base02: '#303030',
  base03: '#505050',
  base04: '#b0b0b0',
  base05: '#d0d0d0',
  base06: '#e0e0e0',
  base07: '#f5f5f5',
  base08: '#fb9fb1',
  base09: '#eda987',
  base0A: '#ddb26f',
  base0B: '#acc267',
  base0C: '#12cfc0',
  base0D: '#6fc2ef',
  base0E: '#e1a3ee',
  base0F: '#deaf8f'
};
module.exports = exports['default'];
},{}],"../node_modules/base16/lib/codeschool.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;
exports['default'] = {
  scheme: 'codeschool',
  author: 'brettof86',
  base00: '#232c31',
  base01: '#1c3657',
  base02: '#2a343a',
  base03: '#3f4944',
  base04: '#84898c',
  base05: '#9ea7a6',
  base06: '#a7cfa3',
  base07: '#b5d8f6',
  base08: '#2a5491',
  base09: '#43820d',
  base0A: '#a03b1e',
  base0B: '#237986',
  base0C: '#b02f30',
  base0D: '#484d79',
  base0E: '#c59820',
  base0F: '#c98344'
};
module.exports = exports['default'];
},{}],"../node_modules/base16/lib/colors.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;
exports['default'] = {
  scheme: 'colors',
  author: 'mrmrs (http://clrs.cc)',
  base00: '#111111',
  base01: '#333333',
  base02: '#555555',
  base03: '#777777',
  base04: '#999999',
  base05: '#bbbbbb',
  base06: '#dddddd',
  base07: '#ffffff',
  base08: '#ff4136',
  base09: '#ff851b',
  base0A: '#ffdc00',
  base0B: '#2ecc40',
  base0C: '#7fdbff',
  base0D: '#0074d9',
  base0E: '#b10dc9',
  base0F: '#85144b'
};
module.exports = exports['default'];
},{}],"../node_modules/base16/lib/default.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;
exports['default'] = {
  scheme: 'default',
  author: 'chris kempson (http://chriskempson.com)',
  base00: '#181818',
  base01: '#282828',
  base02: '#383838',
  base03: '#585858',
  base04: '#b8b8b8',
  base05: '#d8d8d8',
  base06: '#e8e8e8',
  base07: '#f8f8f8',
  base08: '#ab4642',
  base09: '#dc9656',
  base0A: '#f7ca88',
  base0B: '#a1b56c',
  base0C: '#86c1b9',
  base0D: '#7cafc2',
  base0E: '#ba8baf',
  base0F: '#a16946'
};
module.exports = exports['default'];
},{}],"../node_modules/base16/lib/eighties.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;
exports['default'] = {
  scheme: 'eighties',
  author: 'chris kempson (http://chriskempson.com)',
  base00: '#2d2d2d',
  base01: '#393939',
  base02: '#515151',
  base03: '#747369',
  base04: '#a09f93',
  base05: '#d3d0c8',
  base06: '#e8e6df',
  base07: '#f2f0ec',
  base08: '#f2777a',
  base09: '#f99157',
  base0A: '#ffcc66',
  base0B: '#99cc99',
  base0C: '#66cccc',
  base0D: '#6699cc',
  base0E: '#cc99cc',
  base0F: '#d27b53'
};
module.exports = exports['default'];
},{}],"../node_modules/base16/lib/embers.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;
exports['default'] = {
  scheme: 'embers',
  author: 'jannik siebert (https://github.com/janniks)',
  base00: '#16130F',
  base01: '#2C2620',
  base02: '#433B32',
  base03: '#5A5047',
  base04: '#8A8075',
  base05: '#A39A90',
  base06: '#BEB6AE',
  base07: '#DBD6D1',
  base08: '#826D57',
  base09: '#828257',
  base0A: '#6D8257',
  base0B: '#57826D',
  base0C: '#576D82',
  base0D: '#6D5782',
  base0E: '#82576D',
  base0F: '#825757'
};
module.exports = exports['default'];
},{}],"../node_modules/base16/lib/flat.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;
exports['default'] = {
  scheme: 'flat',
  author: 'chris kempson (http://chriskempson.com)',
  base00: '#2C3E50',
  base01: '#34495E',
  base02: '#7F8C8D',
  base03: '#95A5A6',
  base04: '#BDC3C7',
  base05: '#e0e0e0',
  base06: '#f5f5f5',
  base07: '#ECF0F1',
  base08: '#E74C3C',
  base09: '#E67E22',
  base0A: '#F1C40F',
  base0B: '#2ECC71',
  base0C: '#1ABC9C',
  base0D: '#3498DB',
  base0E: '#9B59B6',
  base0F: '#be643c'
};
module.exports = exports['default'];
},{}],"../node_modules/base16/lib/google.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;
exports['default'] = {
  scheme: 'google',
  author: 'seth wright (http://sethawright.com)',
  base00: '#1d1f21',
  base01: '#282a2e',
  base02: '#373b41',
  base03: '#969896',
  base04: '#b4b7b4',
  base05: '#c5c8c6',
  base06: '#e0e0e0',
  base07: '#ffffff',
  base08: '#CC342B',
  base09: '#F96A38',
  base0A: '#FBA922',
  base0B: '#198844',
  base0C: '#3971ED',
  base0D: '#3971ED',
  base0E: '#A36AC7',
  base0F: '#3971ED'
};
module.exports = exports['default'];
},{}],"../node_modules/base16/lib/grayscale.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;
exports['default'] = {
  scheme: 'grayscale',
  author: 'alexandre gavioli (https://github.com/alexx2/)',
  base00: '#101010',
  base01: '#252525',
  base02: '#464646',
  base03: '#525252',
  base04: '#ababab',
  base05: '#b9b9b9',
  base06: '#e3e3e3',
  base07: '#f7f7f7',
  base08: '#7c7c7c',
  base09: '#999999',
  base0A: '#a0a0a0',
  base0B: '#8e8e8e',
  base0C: '#868686',
  base0D: '#686868',
  base0E: '#747474',
  base0F: '#5e5e5e'
};
module.exports = exports['default'];
},{}],"../node_modules/base16/lib/greenscreen.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;
exports['default'] = {
  scheme: 'green screen',
  author: 'chris kempson (http://chriskempson.com)',
  base00: '#001100',
  base01: '#003300',
  base02: '#005500',
  base03: '#007700',
  base04: '#009900',
  base05: '#00bb00',
  base06: '#00dd00',
  base07: '#00ff00',
  base08: '#007700',
  base09: '#009900',
  base0A: '#007700',
  base0B: '#00bb00',
  base0C: '#005500',
  base0D: '#009900',
  base0E: '#00bb00',
  base0F: '#005500'
};
module.exports = exports['default'];
},{}],"../node_modules/base16/lib/harmonic.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;
exports['default'] = {
  scheme: 'harmonic16',
  author: 'jannik siebert (https://github.com/janniks)',
  base00: '#0b1c2c',
  base01: '#223b54',
  base02: '#405c79',
  base03: '#627e99',
  base04: '#aabcce',
  base05: '#cbd6e2',
  base06: '#e5ebf1',
  base07: '#f7f9fb',
  base08: '#bf8b56',
  base09: '#bfbf56',
  base0A: '#8bbf56',
  base0B: '#56bf8b',
  base0C: '#568bbf',
  base0D: '#8b56bf',
  base0E: '#bf568b',
  base0F: '#bf5656'
};
module.exports = exports['default'];
},{}],"../node_modules/base16/lib/hopscotch.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;
exports['default'] = {
  scheme: 'hopscotch',
  author: 'jan t. sott',
  base00: '#322931',
  base01: '#433b42',
  base02: '#5c545b',
  base03: '#797379',
  base04: '#989498',
  base05: '#b9b5b8',
  base06: '#d5d3d5',
  base07: '#ffffff',
  base08: '#dd464c',
  base09: '#fd8b19',
  base0A: '#fdcc59',
  base0B: '#8fc13e',
  base0C: '#149b93',
  base0D: '#1290bf',
  base0E: '#c85e7c',
  base0F: '#b33508'
};
module.exports = exports['default'];
},{}],"../node_modules/base16/lib/isotope.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;
exports['default'] = {
  scheme: 'isotope',
  author: 'jan t. sott',
  base00: '#000000',
  base01: '#404040',
  base02: '#606060',
  base03: '#808080',
  base04: '#c0c0c0',
  base05: '#d0d0d0',
  base06: '#e0e0e0',
  base07: '#ffffff',
  base08: '#ff0000',
  base09: '#ff9900',
  base0A: '#ff0099',
  base0B: '#33ff00',
  base0C: '#00ffff',
  base0D: '#0066ff',
  base0E: '#cc00ff',
  base0F: '#3300ff'
};
module.exports = exports['default'];
},{}],"../node_modules/base16/lib/marrakesh.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;
exports['default'] = {
  scheme: 'marrakesh',
  author: 'alexandre gavioli (http://github.com/alexx2/)',
  base00: '#201602',
  base01: '#302e00',
  base02: '#5f5b17',
  base03: '#6c6823',
  base04: '#86813b',
  base05: '#948e48',
  base06: '#ccc37a',
  base07: '#faf0a5',
  base08: '#c35359',
  base09: '#b36144',
  base0A: '#a88339',
  base0B: '#18974e',
  base0C: '#75a738',
  base0D: '#477ca1',
  base0E: '#8868b3',
  base0F: '#b3588e'
};
module.exports = exports['default'];
},{}],"../node_modules/base16/lib/mocha.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;
exports['default'] = {
  scheme: 'mocha',
  author: 'chris kempson (http://chriskempson.com)',
  base00: '#3B3228',
  base01: '#534636',
  base02: '#645240',
  base03: '#7e705a',
  base04: '#b8afad',
  base05: '#d0c8c6',
  base06: '#e9e1dd',
  base07: '#f5eeeb',
  base08: '#cb6077',
  base09: '#d28b71',
  base0A: '#f4bc87',
  base0B: '#beb55b',
  base0C: '#7bbda4',
  base0D: '#8ab3b5',
  base0E: '#a89bb9',
  base0F: '#bb9584'
};
module.exports = exports['default'];
},{}],"../node_modules/base16/lib/monokai.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;
exports['default'] = {
  scheme: 'monokai',
  author: 'wimer hazenberg (http://www.monokai.nl)',
  base00: '#272822',
  base01: '#383830',
  base02: '#49483e',
  base03: '#75715e',
  base04: '#a59f85',
  base05: '#f8f8f2',
  base06: '#f5f4f1',
  base07: '#f9f8f5',
  base08: '#f92672',
  base09: '#fd971f',
  base0A: '#f4bf75',
  base0B: '#a6e22e',
  base0C: '#a1efe4',
  base0D: '#66d9ef',
  base0E: '#ae81ff',
  base0F: '#cc6633'
};
module.exports = exports['default'];
},{}],"../node_modules/base16/lib/ocean.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;
exports['default'] = {
  scheme: 'ocean',
  author: 'chris kempson (http://chriskempson.com)',
  base00: '#2b303b',
  base01: '#343d46',
  base02: '#4f5b66',
  base03: '#65737e',
  base04: '#a7adba',
  base05: '#c0c5ce',
  base06: '#dfe1e8',
  base07: '#eff1f5',
  base08: '#bf616a',
  base09: '#d08770',
  base0A: '#ebcb8b',
  base0B: '#a3be8c',
  base0C: '#96b5b4',
  base0D: '#8fa1b3',
  base0E: '#b48ead',
  base0F: '#ab7967'
};
module.exports = exports['default'];
},{}],"../node_modules/base16/lib/paraiso.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;
exports['default'] = {
  scheme: 'paraiso',
  author: 'jan t. sott',
  base00: '#2f1e2e',
  base01: '#41323f',
  base02: '#4f424c',
  base03: '#776e71',
  base04: '#8d8687',
  base05: '#a39e9b',
  base06: '#b9b6b0',
  base07: '#e7e9db',
  base08: '#ef6155',
  base09: '#f99b15',
  base0A: '#fec418',
  base0B: '#48b685',
  base0C: '#5bc4bf',
  base0D: '#06b6ef',
  base0E: '#815ba4',
  base0F: '#e96ba8'
};
module.exports = exports['default'];
},{}],"../node_modules/base16/lib/pop.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;
exports['default'] = {
  scheme: 'pop',
  author: 'chris kempson (http://chriskempson.com)',
  base00: '#000000',
  base01: '#202020',
  base02: '#303030',
  base03: '#505050',
  base04: '#b0b0b0',
  base05: '#d0d0d0',
  base06: '#e0e0e0',
  base07: '#ffffff',
  base08: '#eb008a',
  base09: '#f29333',
  base0A: '#f8ca12',
  base0B: '#37b349',
  base0C: '#00aabb',
  base0D: '#0e5a94',
  base0E: '#b31e8d',
  base0F: '#7a2d00'
};
module.exports = exports['default'];
},{}],"../node_modules/base16/lib/railscasts.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;
exports['default'] = {
  scheme: 'railscasts',
  author: 'ryan bates (http://railscasts.com)',
  base00: '#2b2b2b',
  base01: '#272935',
  base02: '#3a4055',
  base03: '#5a647e',
  base04: '#d4cfc9',
  base05: '#e6e1dc',
  base06: '#f4f1ed',
  base07: '#f9f7f3',
  base08: '#da4939',
  base09: '#cc7833',
  base0A: '#ffc66d',
  base0B: '#a5c261',
  base0C: '#519f50',
  base0D: '#6d9cbe',
  base0E: '#b6b3eb',
  base0F: '#bc9458'
};
module.exports = exports['default'];
},{}],"../node_modules/base16/lib/shapeshifter.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;
exports['default'] = {
  scheme: 'shapeshifter',
  author: 'tyler benziger (http://tybenz.com)',
  base00: '#000000',
  base01: '#040404',
  base02: '#102015',
  base03: '#343434',
  base04: '#555555',
  base05: '#ababab',
  base06: '#e0e0e0',
  base07: '#f9f9f9',
  base08: '#e92f2f',
  base09: '#e09448',
  base0A: '#dddd13',
  base0B: '#0ed839',
  base0C: '#23edda',
  base0D: '#3b48e3',
  base0E: '#f996e2',
  base0F: '#69542d'
};
module.exports = exports['default'];
},{}],"../node_modules/base16/lib/solarized.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;
exports['default'] = {
  scheme: 'solarized',
  author: 'ethan schoonover (http://ethanschoonover.com/solarized)',
  base00: '#002b36',
  base01: '#073642',
  base02: '#586e75',
  base03: '#657b83',
  base04: '#839496',
  base05: '#93a1a1',
  base06: '#eee8d5',
  base07: '#fdf6e3',
  base08: '#dc322f',
  base09: '#cb4b16',
  base0A: '#b58900',
  base0B: '#859900',
  base0C: '#2aa198',
  base0D: '#268bd2',
  base0E: '#6c71c4',
  base0F: '#d33682'
};
module.exports = exports['default'];
},{}],"../node_modules/base16/lib/summerfruit.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;
exports['default'] = {
  scheme: 'summerfruit',
  author: 'christopher corley (http://cscorley.github.io/)',
  base00: '#151515',
  base01: '#202020',
  base02: '#303030',
  base03: '#505050',
  base04: '#B0B0B0',
  base05: '#D0D0D0',
  base06: '#E0E0E0',
  base07: '#FFFFFF',
  base08: '#FF0086',
  base09: '#FD8900',
  base0A: '#ABA800',
  base0B: '#00C918',
  base0C: '#1faaaa',
  base0D: '#3777E6',
  base0E: '#AD00A1',
  base0F: '#cc6633'
};
module.exports = exports['default'];
},{}],"../node_modules/base16/lib/tomorrow.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;
exports['default'] = {
  scheme: 'tomorrow',
  author: 'chris kempson (http://chriskempson.com)',
  base00: '#1d1f21',
  base01: '#282a2e',
  base02: '#373b41',
  base03: '#969896',
  base04: '#b4b7b4',
  base05: '#c5c8c6',
  base06: '#e0e0e0',
  base07: '#ffffff',
  base08: '#cc6666',
  base09: '#de935f',
  base0A: '#f0c674',
  base0B: '#b5bd68',
  base0C: '#8abeb7',
  base0D: '#81a2be',
  base0E: '#b294bb',
  base0F: '#a3685a'
};
module.exports = exports['default'];
},{}],"../node_modules/base16/lib/tube.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;
exports['default'] = {
  scheme: 'london tube',
  author: 'jan t. sott',
  base00: '#231f20',
  base01: '#1c3f95',
  base02: '#5a5758',
  base03: '#737171',
  base04: '#959ca1',
  base05: '#d9d8d8',
  base06: '#e7e7e8',
  base07: '#ffffff',
  base08: '#ee2e24',
  base09: '#f386a1',
  base0A: '#ffd204',
  base0B: '#00853e',
  base0C: '#85cebc',
  base0D: '#009ddc',
  base0E: '#98005d',
  base0F: '#b06110'
};
module.exports = exports['default'];
},{}],"../node_modules/base16/lib/twilight.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;
exports['default'] = {
  scheme: 'twilight',
  author: 'david hart (http://hart-dev.com)',
  base00: '#1e1e1e',
  base01: '#323537',
  base02: '#464b50',
  base03: '#5f5a60',
  base04: '#838184',
  base05: '#a7a7a7',
  base06: '#c3c3c3',
  base07: '#ffffff',
  base08: '#cf6a4c',
  base09: '#cda869',
  base0A: '#f9ee98',
  base0B: '#8f9d6a',
  base0C: '#afc4db',
  base0D: '#7587a6',
  base0E: '#9b859d',
  base0F: '#9b703f'
};
module.exports = exports['default'];
},{}],"../node_modules/base16/lib/index.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;

function _interopRequire(obj) { return obj && obj.__esModule ? obj['default'] : obj; }

var _threezerotwofour = require('./threezerotwofour');

exports.threezerotwofour = _interopRequire(_threezerotwofour);

var _apathy = require('./apathy');

exports.apathy = _interopRequire(_apathy);

var _ashes = require('./ashes');

exports.ashes = _interopRequire(_ashes);

var _atelierDune = require('./atelier-dune');

exports.atelierDune = _interopRequire(_atelierDune);

var _atelierForest = require('./atelier-forest');

exports.atelierForest = _interopRequire(_atelierForest);

var _atelierHeath = require('./atelier-heath');

exports.atelierHeath = _interopRequire(_atelierHeath);

var _atelierLakeside = require('./atelier-lakeside');

exports.atelierLakeside = _interopRequire(_atelierLakeside);

var _atelierSeaside = require('./atelier-seaside');

exports.atelierSeaside = _interopRequire(_atelierSeaside);

var _bespin = require('./bespin');

exports.bespin = _interopRequire(_bespin);

var _brewer = require('./brewer');

exports.brewer = _interopRequire(_brewer);

var _bright = require('./bright');

exports.bright = _interopRequire(_bright);

var _chalk = require('./chalk');

exports.chalk = _interopRequire(_chalk);

var _codeschool = require('./codeschool');

exports.codeschool = _interopRequire(_codeschool);

var _colors = require('./colors');

exports.colors = _interopRequire(_colors);

var _default = require('./default');

exports['default'] = _interopRequire(_default);

var _eighties = require('./eighties');

exports.eighties = _interopRequire(_eighties);

var _embers = require('./embers');

exports.embers = _interopRequire(_embers);

var _flat = require('./flat');

exports.flat = _interopRequire(_flat);

var _google = require('./google');

exports.google = _interopRequire(_google);

var _grayscale = require('./grayscale');

exports.grayscale = _interopRequire(_grayscale);

var _greenscreen = require('./greenscreen');

exports.greenscreen = _interopRequire(_greenscreen);

var _harmonic = require('./harmonic');

exports.harmonic = _interopRequire(_harmonic);

var _hopscotch = require('./hopscotch');

exports.hopscotch = _interopRequire(_hopscotch);

var _isotope = require('./isotope');

exports.isotope = _interopRequire(_isotope);

var _marrakesh = require('./marrakesh');

exports.marrakesh = _interopRequire(_marrakesh);

var _mocha = require('./mocha');

exports.mocha = _interopRequire(_mocha);

var _monokai = require('./monokai');

exports.monokai = _interopRequire(_monokai);

var _ocean = require('./ocean');

exports.ocean = _interopRequire(_ocean);

var _paraiso = require('./paraiso');

exports.paraiso = _interopRequire(_paraiso);

var _pop = require('./pop');

exports.pop = _interopRequire(_pop);

var _railscasts = require('./railscasts');

exports.railscasts = _interopRequire(_railscasts);

var _shapeshifter = require('./shapeshifter');

exports.shapeshifter = _interopRequire(_shapeshifter);

var _solarized = require('./solarized');

exports.solarized = _interopRequire(_solarized);

var _summerfruit = require('./summerfruit');

exports.summerfruit = _interopRequire(_summerfruit);

var _tomorrow = require('./tomorrow');

exports.tomorrow = _interopRequire(_tomorrow);

var _tube = require('./tube');

exports.tube = _interopRequire(_tube);

var _twilight = require('./twilight');

exports.twilight = _interopRequire(_twilight);
},{"./threezerotwofour":"../node_modules/base16/lib/threezerotwofour.js","./apathy":"../node_modules/base16/lib/apathy.js","./ashes":"../node_modules/base16/lib/ashes.js","./atelier-dune":"../node_modules/base16/lib/atelier-dune.js","./atelier-forest":"../node_modules/base16/lib/atelier-forest.js","./atelier-heath":"../node_modules/base16/lib/atelier-heath.js","./atelier-lakeside":"../node_modules/base16/lib/atelier-lakeside.js","./atelier-seaside":"../node_modules/base16/lib/atelier-seaside.js","./bespin":"../node_modules/base16/lib/bespin.js","./brewer":"../node_modules/base16/lib/brewer.js","./bright":"../node_modules/base16/lib/bright.js","./chalk":"../node_modules/base16/lib/chalk.js","./codeschool":"../node_modules/base16/lib/codeschool.js","./colors":"../node_modules/base16/lib/colors.js","./default":"../node_modules/base16/lib/default.js","./eighties":"../node_modules/base16/lib/eighties.js","./embers":"../node_modules/base16/lib/embers.js","./flat":"../node_modules/base16/lib/flat.js","./google":"../node_modules/base16/lib/google.js","./grayscale":"../node_modules/base16/lib/grayscale.js","./greenscreen":"../node_modules/base16/lib/greenscreen.js","./harmonic":"../node_modules/base16/lib/harmonic.js","./hopscotch":"../node_modules/base16/lib/hopscotch.js","./isotope":"../node_modules/base16/lib/isotope.js","./marrakesh":"../node_modules/base16/lib/marrakesh.js","./mocha":"../node_modules/base16/lib/mocha.js","./monokai":"../node_modules/base16/lib/monokai.js","./ocean":"../node_modules/base16/lib/ocean.js","./paraiso":"../node_modules/base16/lib/paraiso.js","./pop":"../node_modules/base16/lib/pop.js","./railscasts":"../node_modules/base16/lib/railscasts.js","./shapeshifter":"../node_modules/base16/lib/shapeshifter.js","./solarized":"../node_modules/base16/lib/solarized.js","./summerfruit":"../node_modules/base16/lib/summerfruit.js","./tomorrow":"../node_modules/base16/lib/tomorrow.js","./tube":"../node_modules/base16/lib/tube.js","./twilight":"../node_modules/base16/lib/twilight.js"}],"../node_modules/pure-color/util/clamp.js":[function(require,module,exports) {
function clamp(val, min, max) {
  return Math.min(Math.max(val, min), max);
}

module.exports = clamp;
},{}],"../node_modules/pure-color/convert/rgb2hex.js":[function(require,module,exports) {
var clamp = require("../util/clamp");

function componentToHex(c) {
  var value = Math.round(clamp(c, 0, 255));
  var hex   = value.toString(16);

  return hex.length == 1 ? "0" + hex : hex;
}

function rgb2hex(rgb) {
  var alpha = rgb.length === 4 ? componentToHex(rgb[3] * 255) : "";

  return "#" + componentToHex(rgb[0]) + componentToHex(rgb[1]) + componentToHex(rgb[2]) + alpha;
}

module.exports = rgb2hex;
},{"../util/clamp":"../node_modules/pure-color/util/clamp.js"}],"../node_modules/pure-color/parse/extractComponents.js":[function(require,module,exports) {
var component = /-?\d+(\.\d+)?%?/g;
function extractComponents(color) {
  return color.match(component);
}

module.exports = extractComponents;
},{}],"../node_modules/pure-color/parse/hsl.js":[function(require,module,exports) {
var extractComponents = require("./extractComponents");
var clamp = require("../util/clamp");

function parseHslComponent(component, i) {
  component = parseFloat(component);

  switch(i) {
    case 0:
      return clamp(component, 0, 360);
    case 1:
    case 2:
      return clamp(component, 0, 100);
    case 3:
      return clamp(component, 0, 1);
  }
}

function hsl(color) {
  return extractComponents(color).map(parseHslComponent);
}

module.exports = hsl;
},{"./extractComponents":"../node_modules/pure-color/parse/extractComponents.js","../util/clamp":"../node_modules/pure-color/util/clamp.js"}],"../node_modules/pure-color/parse/hex.js":[function(require,module,exports) {
function expand(hex) {
  var result = "#";

  for (var i = 1; i < hex.length; i++) {
    var val = hex.charAt(i);
    result += val + val;
  }

  return result;
}

function hex(hex) {
  // #RGB or #RGBA
  if(hex.length === 4 || hex.length === 5) {
    hex = expand(hex);
  }

  var rgb = [
    parseInt(hex.substring(1,3), 16),
    parseInt(hex.substring(3,5), 16),
    parseInt(hex.substring(5,7), 16)
  ];

  // #RRGGBBAA
  if (hex.length === 9) {
    var alpha = parseFloat((parseInt(hex.substring(7,9), 16) / 255).toFixed(2));
    rgb.push(alpha);
  }

  return rgb;
}

module.exports = hex;
},{}],"../node_modules/pure-color/parse/rgb.js":[function(require,module,exports) {
var extractComponents = require("./extractComponents");
var clamp = require("../util/clamp");

function parseRgbComponent(component, i) {
  if (i < 3) {
    if (component.indexOf('%') != -1) {
      return Math.round(255 * clamp(parseInt(component, 10), 0, 100)/100);
    } else {
      return clamp(parseInt(component, 10), 0, 255);
    }
  } else {
    return clamp(parseFloat(component), 0, 1);
  } 
}

function rgb(color) {
  return extractComponents(color).map(parseRgbComponent);
}

module.exports = rgb;
},{"./extractComponents":"../node_modules/pure-color/parse/extractComponents.js","../util/clamp":"../node_modules/pure-color/util/clamp.js"}],"../node_modules/pure-color/convert/hsl2rgb.js":[function(require,module,exports) {
function hsl2rgb(hsl) {
  var h = hsl[0] / 360,
      s = hsl[1] / 100,
      l = hsl[2] / 100,
      t1, t2, t3, rgb, val;

  if (s == 0) {
    val = l * 255;
    return [val, val, val];
  }

  if (l < 0.5)
    t2 = l * (1 + s);
  else
    t2 = l + s - l * s;
  t1 = 2 * l - t2;

  rgb = [0, 0, 0];
  for (var i = 0; i < 3; i++) {
    t3 = h + 1 / 3 * - (i - 1);
    t3 < 0 && t3++;
    t3 > 1 && t3--;

    if (6 * t3 < 1)
      val = t1 + (t2 - t1) * 6 * t3;
    else if (2 * t3 < 1)
      val = t2;
    else if (3 * t3 < 2)
      val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
    else
      val = t1;

    rgb[i] = val * 255;
  }

  return rgb;
}

module.exports = hsl2rgb;
},{}],"../node_modules/pure-color/parse/index.js":[function(require,module,exports) {
var hsl = require("./hsl");
var hex = require("./hex");
var rgb = require("./rgb");
var hsl2rgb = require("../convert/hsl2rgb");

function hsl2rgbParse(color) {
  var h = hsl(color);
  var r = hsl2rgb(h);

  // handle alpha since hsl2rgb doesn't know (or care!) about it
  if(h.length === 4) {
    r.push(h[3]);
  }

  return r;
}

var space2parser = {
  "#" : hex,
  "hsl" : hsl2rgbParse,
  "rgb" : rgb
};

function parse(color) {
  for(var scheme in space2parser) {
    if(color.indexOf(scheme) === 0) {
      return space2parser[scheme](color);
    }
  }
}

parse.rgb = rgb;
parse.hsl = hsl;
parse.hex = hex;

module.exports = parse;
},{"./hsl":"../node_modules/pure-color/parse/hsl.js","./hex":"../node_modules/pure-color/parse/hex.js","./rgb":"../node_modules/pure-color/parse/rgb.js","../convert/hsl2rgb":"../node_modules/pure-color/convert/hsl2rgb.js"}],"../node_modules/lodash.flow/index.js":[function(require,module,exports) {
var global = arguments[3];
/**
 * lodash (Custom Build) <https://lodash.com/>
 * Build: `lodash modularize exports="npm" -o ./`
 * Copyright jQuery Foundation and other contributors <https://jquery.org/>
 * Released under MIT license <https://lodash.com/license>
 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 */

/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';

/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;

/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
    funcTag = '[object Function]',
    genTag = '[object GeneratorFunction]';

/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;

/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;

/** Used as a reference to the global object. */
var root = freeGlobal || freeSelf || Function('return this')();

/**
 * A faster alternative to `Function#apply`, this function invokes `func`
 * with the `this` binding of `thisArg` and the arguments of `args`.
 *
 * @private
 * @param {Function} func The function to invoke.
 * @param {*} thisArg The `this` binding of `func`.
 * @param {Array} args The arguments to invoke `func` with.
 * @returns {*} Returns the result of `func`.
 */
function apply(func, thisArg, args) {
  switch (args.length) {
    case 0: return func.call(thisArg);
    case 1: return func.call(thisArg, args[0]);
    case 2: return func.call(thisArg, args[0], args[1]);
    case 3: return func.call(thisArg, args[0], args[1], args[2]);
  }
  return func.apply(thisArg, args);
}

/**
 * Appends the elements of `values` to `array`.
 *
 * @private
 * @param {Array} array The array to modify.
 * @param {Array} values The values to append.
 * @returns {Array} Returns `array`.
 */
function arrayPush(array, values) {
  var index = -1,
      length = values.length,
      offset = array.length;

  while (++index < length) {
    array[offset + index] = values[index];
  }
  return array;
}

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * Used to resolve the
 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
 * of values.
 */
var objectToString = objectProto.toString;

/** Built-in value references. */
var Symbol = root.Symbol,
    propertyIsEnumerable = objectProto.propertyIsEnumerable,
    spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined;

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;

/**
 * The base implementation of `_.flatten` with support for restricting flattening.
 *
 * @private
 * @param {Array} array The array to flatten.
 * @param {number} depth The maximum recursion depth.
 * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
 * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
 * @param {Array} [result=[]] The initial result value.
 * @returns {Array} Returns the new flattened array.
 */
function baseFlatten(array, depth, predicate, isStrict, result) {
  var index = -1,
      length = array.length;

  predicate || (predicate = isFlattenable);
  result || (result = []);

  while (++index < length) {
    var value = array[index];
    if (depth > 0 && predicate(value)) {
      if (depth > 1) {
        // Recursively flatten arrays (susceptible to call stack limits).
        baseFlatten(value, depth - 1, predicate, isStrict, result);
      } else {
        arrayPush(result, value);
      }
    } else if (!isStrict) {
      result[result.length] = value;
    }
  }
  return result;
}

/**
 * The base implementation of `_.rest` which doesn't validate or coerce arguments.
 *
 * @private
 * @param {Function} func The function to apply a rest parameter to.
 * @param {number} [start=func.length-1] The start position of the rest parameter.
 * @returns {Function} Returns the new function.
 */
function baseRest(func, start) {
  start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
  return function() {
    var args = arguments,
        index = -1,
        length = nativeMax(args.length - start, 0),
        array = Array(length);

    while (++index < length) {
      array[index] = args[start + index];
    }
    index = -1;
    var otherArgs = Array(start + 1);
    while (++index < start) {
      otherArgs[index] = args[index];
    }
    otherArgs[start] = array;
    return apply(func, this, otherArgs);
  };
}

/**
 * Creates a `_.flow` or `_.flowRight` function.
 *
 * @private
 * @param {boolean} [fromRight] Specify iterating from right to left.
 * @returns {Function} Returns the new flow function.
 */
function createFlow(fromRight) {
  return baseRest(function(funcs) {
    funcs = baseFlatten(funcs, 1);

    var length = funcs.length,
        index = length;

    if (fromRight) {
      funcs.reverse();
    }
    while (index--) {
      if (typeof funcs[index] != 'function') {
        throw new TypeError(FUNC_ERROR_TEXT);
      }
    }
    return function() {
      var index = 0,
          result = length ? funcs[index].apply(this, arguments) : arguments[0];

      while (++index < length) {
        result = funcs[index].call(this, result);
      }
      return result;
    };
  });
}

/**
 * Checks if `value` is a flattenable `arguments` object or array.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
 */
function isFlattenable(value) {
  return isArray(value) || isArguments(value) ||
    !!(spreadableSymbol && value && value[spreadableSymbol]);
}

/**
 * Checks if `value` is likely an `arguments` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
 *  else `false`.
 * @example
 *
 * _.isArguments(function() { return arguments; }());
 * // => true
 *
 * _.isArguments([1, 2, 3]);
 * // => false
 */
function isArguments(value) {
  // Safari 8.1 makes `arguments.callee` enumerable in strict mode.
  return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') &&
    (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);
}

/**
 * Checks if `value` is classified as an `Array` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an array, else `false`.
 * @example
 *
 * _.isArray([1, 2, 3]);
 * // => true
 *
 * _.isArray(document.body.children);
 * // => false
 *
 * _.isArray('abc');
 * // => false
 *
 * _.isArray(_.noop);
 * // => false
 */
var isArray = Array.isArray;

/**
 * Checks if `value` is array-like. A value is considered array-like if it's
 * not a function and has a `value.length` that's an integer greater than or
 * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
 * @example
 *
 * _.isArrayLike([1, 2, 3]);
 * // => true
 *
 * _.isArrayLike(document.body.children);
 * // => true
 *
 * _.isArrayLike('abc');
 * // => true
 *
 * _.isArrayLike(_.noop);
 * // => false
 */
function isArrayLike(value) {
  return value != null && isLength(value.length) && !isFunction(value);
}

/**
 * This method is like `_.isArrayLike` except that it also checks if `value`
 * is an object.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an array-like object,
 *  else `false`.
 * @example
 *
 * _.isArrayLikeObject([1, 2, 3]);
 * // => true
 *
 * _.isArrayLikeObject(document.body.children);
 * // => true
 *
 * _.isArrayLikeObject('abc');
 * // => false
 *
 * _.isArrayLikeObject(_.noop);
 * // => false
 */
function isArrayLikeObject(value) {
  return isObjectLike(value) && isArrayLike(value);
}

/**
 * Checks if `value` is classified as a `Function` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a function, else `false`.
 * @example
 *
 * _.isFunction(_);
 * // => true
 *
 * _.isFunction(/abc/);
 * // => false
 */
function isFunction(value) {
  // The use of `Object#toString` avoids issues with the `typeof` operator
  // in Safari 8-9 which returns 'object' for typed array and other constructors.
  var tag = isObject(value) ? objectToString.call(value) : '';
  return tag == funcTag || tag == genTag;
}

/**
 * Checks if `value` is a valid array-like length.
 *
 * **Note:** This method is loosely based on
 * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
 * @example
 *
 * _.isLength(3);
 * // => true
 *
 * _.isLength(Number.MIN_VALUE);
 * // => false
 *
 * _.isLength(Infinity);
 * // => false
 *
 * _.isLength('3');
 * // => false
 */
function isLength(value) {
  return typeof value == 'number' &&
    value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}

/**
 * Checks if `value` is the
 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
 * @example
 *
 * _.isObject({});
 * // => true
 *
 * _.isObject([1, 2, 3]);
 * // => true
 *
 * _.isObject(_.noop);
 * // => true
 *
 * _.isObject(null);
 * // => false
 */
function isObject(value) {
  var type = typeof value;
  return !!value && (type == 'object' || type == 'function');
}

/**
 * Checks if `value` is object-like. A value is object-like if it's not `null`
 * and has a `typeof` result of "object".
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
 * @example
 *
 * _.isObjectLike({});
 * // => true
 *
 * _.isObjectLike([1, 2, 3]);
 * // => true
 *
 * _.isObjectLike(_.noop);
 * // => false
 *
 * _.isObjectLike(null);
 * // => false
 */
function isObjectLike(value) {
  return !!value && typeof value == 'object';
}

/**
 * Creates a function that returns the result of invoking the given functions
 * with the `this` binding of the created function, where each successive
 * invocation is supplied the return value of the previous.
 *
 * @static
 * @memberOf _
 * @since 3.0.0
 * @category Util
 * @param {...(Function|Function[])} [funcs] The functions to invoke.
 * @returns {Function} Returns the new composite function.
 * @see _.flowRight
 * @example
 *
 * function square(n) {
 *   return n * n;
 * }
 *
 * var addSquare = _.flow([_.add, square]);
 * addSquare(1, 2);
 * // => 9
 */
var flow = createFlow();

module.exports = flow;

},{}],"../node_modules/react-base16-styling/lib/colorConverters.js":[function(require,module,exports) {
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.yuv2rgb = yuv2rgb;
exports.rgb2yuv = rgb2yuv;
function yuv2rgb(yuv) {
  var y = yuv[0],
      u = yuv[1],
      v = yuv[2],
      r,
      g,
      b;

  r = y * 1 + u * 0 + v * 1.13983;
  g = y * 1 + u * -0.39465 + v * -0.58060;
  b = y * 1 + u * 2.02311 + v * 0;

  r = Math.min(Math.max(0, r), 1);
  g = Math.min(Math.max(0, g), 1);
  b = Math.min(Math.max(0, b), 1);

  return [r * 255, g * 255, b * 255];
}

function rgb2yuv(rgb) {
  var r = rgb[0] / 255,
      g = rgb[1] / 255,
      b = rgb[2] / 255;

  var y = r * 0.299 + g * 0.587 + b * 0.114;
  var u = r * -0.14713 + g * -0.28886 + b * 0.436;
  var v = r * 0.615 + g * -0.51499 + b * -0.10001;

  return [y, u, v];
};
},{}],"../node_modules/react-base16-styling/lib/index.js":[function(require,module,exports) {
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getBase16Theme = exports.createStyling = exports.invertTheme = undefined;

var _typeof2 = require('babel-runtime/helpers/typeof');

var _typeof3 = _interopRequireDefault(_typeof2);

var _extends2 = require('babel-runtime/helpers/extends');

var _extends3 = _interopRequireDefault(_extends2);

var _slicedToArray2 = require('babel-runtime/helpers/slicedToArray');

var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);

var _keys = require('babel-runtime/core-js/object/keys');

var _keys2 = _interopRequireDefault(_keys);

var _lodash = require('lodash.curry');

var _lodash2 = _interopRequireDefault(_lodash);

var _base = require('base16');

var base16 = _interopRequireWildcard(_base);

var _rgb2hex = require('pure-color/convert/rgb2hex');

var _rgb2hex2 = _interopRequireDefault(_rgb2hex);

var _parse = require('pure-color/parse');

var _parse2 = _interopRequireDefault(_parse);

var _lodash3 = require('lodash.flow');

var _lodash4 = _interopRequireDefault(_lodash3);

var _colorConverters = require('./colorConverters');

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

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

var DEFAULT_BASE16 = base16.default;

var BASE16_KEYS = (0, _keys2.default)(DEFAULT_BASE16);

// we need a correcting factor, so that a dark, but not black background color
// converts to bright enough inversed color
var flip = function flip(x) {
  return x < 0.25 ? 1 : x < 0.5 ? 0.9 - x : 1.1 - x;
};

var invertColor = (0, _lodash4.default)(_parse2.default, _colorConverters.rgb2yuv, function (_ref) {
  var _ref2 = (0, _slicedToArray3.default)(_ref, 3),
      y = _ref2[0],
      u = _ref2[1],
      v = _ref2[2];

  return [flip(y), u, v];
}, _colorConverters.yuv2rgb, _rgb2hex2.default);

var merger = function merger(styling) {
  return function (prevStyling) {
    return {
      className: [prevStyling.className, styling.className].filter(Boolean).join(' '),
      style: (0, _extends3.default)({}, prevStyling.style || {}, styling.style || {})
    };
  };
};

var mergeStyling = function mergeStyling(customStyling, defaultStyling) {
  if (customStyling === undefined) {
    return defaultStyling;
  }
  if (defaultStyling === undefined) {
    return customStyling;
  }

  var customType = typeof customStyling === 'undefined' ? 'undefined' : (0, _typeof3.default)(customStyling);
  var defaultType = typeof defaultStyling === 'undefined' ? 'undefined' : (0, _typeof3.default)(defaultStyling);

  switch (customType) {
    case 'string':
      switch (defaultType) {
        case 'string':
          return [defaultStyling, customStyling].filter(Boolean).join(' ');
        case 'object':
          return merger({ className: customStyling, style: defaultStyling });
        case 'function':
          return function (styling) {
            for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
              args[_key - 1] = arguments[_key];
            }

            return merger({
              className: customStyling
            })(defaultStyling.apply(undefined, [styling].concat(args)));
          };
      }
    case 'object':
      switch (defaultType) {
        case 'string':
          return merger({ className: defaultStyling, style: customStyling });
        case 'object':
          return (0, _extends3.default)({}, defaultStyling, customStyling);
        case 'function':
          return function (styling) {
            for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
              args[_key2 - 1] = arguments[_key2];
            }

            return merger({
              style: customStyling
            })(defaultStyling.apply(undefined, [styling].concat(args)));
          };
      }
    case 'function':
      switch (defaultType) {
        case 'string':
          return function (styling) {
            for (var _len3 = arguments.length, args = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
              args[_key3 - 1] = arguments[_key3];
            }

            return customStyling.apply(undefined, [merger(styling)({
              className: defaultStyling
            })].concat(args));
          };
        case 'object':
          return function (styling) {
            for (var _len4 = arguments.length, args = Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
              args[_key4 - 1] = arguments[_key4];
            }

            return customStyling.apply(undefined, [merger(styling)({
              style: defaultStyling
            })].concat(args));
          };
        case 'function':
          return function (styling) {
            for (var _len5 = arguments.length, args = Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) {
              args[_key5 - 1] = arguments[_key5];
            }

            return customStyling.apply(undefined, [defaultStyling.apply(undefined, [styling].concat(args))].concat(args));
          };
      }
  }
};

var mergeStylings = function mergeStylings(customStylings, defaultStylings) {
  var keys = (0, _keys2.default)(defaultStylings);
  for (var key in customStylings) {
    if (keys.indexOf(key) === -1) keys.push(key);
  }

  return keys.reduce(function (mergedStyling, key) {
    return mergedStyling[key] = mergeStyling(customStylings[key], defaultStylings[key]), mergedStyling;
  }, {});
};

var getStylingByKeys = function getStylingByKeys(mergedStyling, keys) {
  for (var _len6 = arguments.length, args = Array(_len6 > 2 ? _len6 - 2 : 0), _key6 = 2; _key6 < _len6; _key6++) {
    args[_key6 - 2] = arguments[_key6];
  }

  if (keys === null) {
    return mergedStyling;
  }

  if (!Array.isArray(keys)) {
    keys = [keys];
  }

  var styles = keys.map(function (key) {
    return mergedStyling[key];
  }).filter(Boolean);

  var props = styles.reduce(function (obj, s) {
    if (typeof s === 'string') {
      obj.className = [obj.className, s].filter(Boolean).join(' ');
    } else if ((typeof s === 'undefined' ? 'undefined' : (0, _typeof3.default)(s)) === 'object') {
      obj.style = (0, _extends3.default)({}, obj.style, s);
    } else if (typeof s === 'function') {
      obj = (0, _extends3.default)({}, obj, s.apply(undefined, [obj].concat(args)));
    }

    return obj;
  }, { className: '', style: {} });

  if (!props.className) {
    delete props.className;
  }

  if ((0, _keys2.default)(props.style).length === 0) {
    delete props.style;
  }

  return props;
};

var invertTheme = exports.invertTheme = function invertTheme(theme) {
  return (0, _keys2.default)(theme).reduce(function (t, key) {
    return t[key] = /^base/.test(key) ? invertColor(theme[key]) : key === 'scheme' ? theme[key] + ':inverted' : theme[key], t;
  }, {});
};

var createStyling = exports.createStyling = (0, _lodash2.default)(function (getStylingFromBase16) {
  for (var _len7 = arguments.length, args = Array(_len7 > 3 ? _len7 - 3 : 0), _key7 = 3; _key7 < _len7; _key7++) {
    args[_key7 - 3] = arguments[_key7];
  }

  var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var themeOrStyling = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  var _options$defaultBase = options.defaultBase16,
      defaultBase16 = _options$defaultBase === undefined ? DEFAULT_BASE16 : _options$defaultBase,
      _options$base16Themes = options.base16Themes,
      base16Themes = _options$base16Themes === undefined ? null : _options$base16Themes;


  var base16Theme = getBase16Theme(themeOrStyling, base16Themes);
  if (base16Theme) {
    themeOrStyling = (0, _extends3.default)({}, base16Theme, themeOrStyling);
  }

  var theme = BASE16_KEYS.reduce(function (t, key) {
    return t[key] = themeOrStyling[key] || defaultBase16[key], t;
  }, {});

  var customStyling = (0, _keys2.default)(themeOrStyling).reduce(function (s, key) {
    return BASE16_KEYS.indexOf(key) === -1 ? (s[key] = themeOrStyling[key], s) : s;
  }, {});

  var defaultStyling = getStylingFromBase16(theme);

  var mergedStyling = mergeStylings(customStyling, defaultStyling);

  return (0, _lodash2.default)(getStylingByKeys, 2).apply(undefined, [mergedStyling].concat(args));
}, 3);

var getBase16Theme = exports.getBase16Theme = function getBase16Theme(theme, base16Themes) {
  if (theme && theme.extend) {
    theme = theme.extend;
  }

  if (typeof theme === 'string') {
    var _theme$split = theme.split(':'),
        _theme$split2 = (0, _slicedToArray3.default)(_theme$split, 2),
        themeName = _theme$split2[0],
        modifier = _theme$split2[1];

    theme = (base16Themes || {})[themeName] || base16[themeName];
    if (modifier === 'inverted') {
      theme = invertTheme(theme);
    }
  }

  return theme && theme.hasOwnProperty('base00') ? theme : undefined;
};
},{"babel-runtime/helpers/typeof":"../node_modules/babel-runtime/helpers/typeof.js","babel-runtime/helpers/extends":"../node_modules/babel-runtime/helpers/extends.js","babel-runtime/helpers/slicedToArray":"../node_modules/babel-runtime/helpers/slicedToArray.js","babel-runtime/core-js/object/keys":"../node_modules/babel-runtime/core-js/object/keys.js","lodash.curry":"../node_modules/lodash.curry/index.js","base16":"../node_modules/base16/lib/index.js","pure-color/convert/rgb2hex":"../node_modules/pure-color/convert/rgb2hex.js","pure-color/parse":"../node_modules/pure-color/parse/index.js","lodash.flow":"../node_modules/lodash.flow/index.js","./colorConverters":"../node_modules/react-base16-styling/lib/colorConverters.js"}],"../node_modules/react-json-tree/lib/themes/solarized.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;
exports['default'] = {
  scheme: 'solarized',
  author: 'ethan schoonover (http://ethanschoonover.com/solarized)',
  base00: '#002b36',
  base01: '#073642',
  base02: '#586e75',
  base03: '#657b83',
  base04: '#839496',
  base05: '#93a1a1',
  base06: '#eee8d5',
  base07: '#fdf6e3',
  base08: '#dc322f',
  base09: '#cb4b16',
  base0A: '#b58900',
  base0B: '#859900',
  base0C: '#2aa198',
  base0D: '#268bd2',
  base0E: '#6c71c4',
  base0F: '#d33682'
};
},{}],"../node_modules/react-json-tree/lib/createStylingFromTheme.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;

var _extends2 = require('babel-runtime/helpers/extends');

var _extends3 = _interopRequireDefault(_extends2);

var _reactBase16Styling = require('react-base16-styling');

var _solarized = require('./themes/solarized');

var _solarized2 = _interopRequireDefault(_solarized);

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

var colorMap = function colorMap(theme) {
  return {
    BACKGROUND_COLOR: theme.base00,
    TEXT_COLOR: theme.base07,
    STRING_COLOR: theme.base0B,
    DATE_COLOR: theme.base0B,
    NUMBER_COLOR: theme.base09,
    BOOLEAN_COLOR: theme.base09,
    NULL_COLOR: theme.base08,
    UNDEFINED_COLOR: theme.base08,
    FUNCTION_COLOR: theme.base08,
    SYMBOL_COLOR: theme.base08,
    LABEL_COLOR: theme.base0D,
    ARROW_COLOR: theme.base0D,
    ITEM_STRING_COLOR: theme.base0B,
    ITEM_STRING_EXPANDED_COLOR: theme.base03
  };
};

var valueColorMap = function valueColorMap(colors) {
  return {
    String: colors.STRING_COLOR,
    Date: colors.DATE_COLOR,
    Number: colors.NUMBER_COLOR,
    Boolean: colors.BOOLEAN_COLOR,
    Null: colors.NULL_COLOR,
    Undefined: colors.UNDEFINED_COLOR,
    Function: colors.FUNCTION_COLOR,
    Symbol: colors.SYMBOL_COLOR
  };
};

var getDefaultThemeStyling = function getDefaultThemeStyling(theme) {
  var colors = colorMap(theme);

  return {
    tree: {
      border: 0,
      padding: 0,
      marginTop: '0.5em',
      marginBottom: '0.5em',
      marginLeft: '0.125em',
      marginRight: 0,
      listStyle: 'none',
      MozUserSelect: 'none',
      WebkitUserSelect: 'none',
      backgroundColor: colors.BACKGROUND_COLOR
    },

    value: function value(_ref, nodeType, keyPath) {
      var style = _ref.style;
      return {
        style: (0, _extends3['default'])({}, style, {
          paddingTop: '0.25em',
          paddingRight: 0,
          marginLeft: '0.875em',
          WebkitUserSelect: 'text',
          MozUserSelect: 'text',
          wordWrap: 'break-word',
          paddingLeft: keyPath.length > 1 ? '2.125em' : '1.25em',
          textIndent: '-0.5em',
          wordBreak: 'break-all'
        })
      };
    },

    label: {
      display: 'inline-block',
      color: colors.LABEL_COLOR
    },

    valueLabel: {
      margin: '0 0.5em 0 0'
    },

    valueText: function valueText(_ref2, nodeType) {
      var style = _ref2.style;
      return {
        style: (0, _extends3['default'])({}, style, {
          color: valueColorMap(colors)[nodeType]
        })
      };
    },

    itemRange: function itemRange(styling, expanded) {
      return {
        style: {
          paddingTop: expanded ? 0 : '0.25em',
          cursor: 'pointer',
          color: colors.LABEL_COLOR
        }
      };
    },

    arrow: function arrow(_ref3, nodeType, expanded) {
      var style = _ref3.style;
      return {
        style: (0, _extends3['default'])({}, style, {
          marginLeft: 0,
          transition: '150ms',
          WebkitTransition: '150ms',
          MozTransition: '150ms',
          WebkitTransform: expanded ? 'rotateZ(90deg)' : 'rotateZ(0deg)',
          MozTransform: expanded ? 'rotateZ(90deg)' : 'rotateZ(0deg)',
          transform: expanded ? 'rotateZ(90deg)' : 'rotateZ(0deg)',
          transformOrigin: '45% 50%',
          WebkitTransformOrigin: '45% 50%',
          MozTransformOrigin: '45% 50%',
          position: 'relative',
          lineHeight: '1.1em',
          fontSize: '0.75em'
        })
      };
    },

    arrowContainer: function arrowContainer(_ref4, arrowStyle) {
      var style = _ref4.style;
      return {
        style: (0, _extends3['default'])({}, style, {
          display: 'inline-block',
          paddingRight: '0.5em',
          paddingLeft: arrowStyle === 'double' ? '1em' : 0,
          cursor: 'pointer'
        })
      };
    },

    arrowSign: {
      color: colors.ARROW_COLOR
    },

    arrowSignInner: {
      position: 'absolute',
      top: 0,
      left: '-0.4em'
    },

    nestedNode: function nestedNode(_ref5, keyPath, nodeType, expanded, expandable) {
      var style = _ref5.style;
      return {
        style: (0, _extends3['default'])({}, style, {
          position: 'relative',
          paddingTop: '0.25em',
          marginLeft: keyPath.length > 1 ? '0.875em' : 0,
          paddingLeft: !expandable ? '1.125em' : 0
        })
      };
    },

    rootNode: {
      padding: 0,
      margin: 0
    },

    nestedNodeLabel: function nestedNodeLabel(_ref6, keyPath, nodeType, expanded, expandable) {
      var style = _ref6.style;
      return {
        style: (0, _extends3['default'])({}, style, {
          margin: 0,
          padding: 0,
          WebkitUserSelect: expandable ? 'inherit' : 'text',
          MozUserSelect: expandable ? 'inherit' : 'text',
          cursor: expandable ? 'pointer' : 'default'
        })
      };
    },

    nestedNodeItemString: function nestedNodeItemString(_ref7, keyPath, nodeType, expanded) {
      var style = _ref7.style;
      return {
        style: (0, _extends3['default'])({}, style, {
          paddingLeft: '0.5em',
          cursor: 'default',
          color: expanded ? colors.ITEM_STRING_EXPANDED_COLOR : colors.ITEM_STRING_COLOR
        })
      };
    },

    nestedNodeItemType: {
      marginLeft: '0.3em',
      marginRight: '0.3em'
    },

    nestedNodeChildren: function nestedNodeChildren(_ref8, nodeType, expanded) {
      var style = _ref8.style;
      return {
        style: (0, _extends3['default'])({}, style, {
          padding: 0,
          margin: 0,
          listStyle: 'none',
          display: expanded ? 'block' : 'none'
        })
      };
    },

    rootNodeChildren: {
      padding: 0,
      margin: 0,
      listStyle: 'none'
    }
  };
};

exports['default'] = (0, _reactBase16Styling.createStyling)(getDefaultThemeStyling, {
  defaultBase16: _solarized2['default']
});
},{"babel-runtime/helpers/extends":"../node_modules/babel-runtime/helpers/extends.js","react-base16-styling":"../node_modules/react-base16-styling/lib/index.js","./themes/solarized":"../node_modules/react-json-tree/lib/themes/solarized.js"}],"../node_modules/react-json-tree/lib/index.js":[function(require,module,exports) {
'use strict';

exports.__esModule = true;

var _objectWithoutProperties2 = require('babel-runtime/helpers/objectWithoutProperties');

var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2);

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = require('babel-runtime/helpers/inherits');

var _inherits3 = _interopRequireDefault(_inherits2);

var _extends2 = require('babel-runtime/helpers/extends');

var _extends3 = _interopRequireDefault(_extends2);

var _keys = require('babel-runtime/core-js/object/keys');

var _keys2 = _interopRequireDefault(_keys);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _JSONNode = require('./JSONNode');

var _JSONNode2 = _interopRequireDefault(_JSONNode);

var _createStylingFromTheme = require('./createStylingFromTheme');

var _createStylingFromTheme2 = _interopRequireDefault(_createStylingFromTheme);

var _reactBase16Styling = require('react-base16-styling');

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

var identity = function identity(value) {
  return value;
}; // ES6 + inline style port of JSONViewer https://bitbucket.org/davevedder/react-json-viewer/
// all credits and original code to the author
// Dave Vedder <veddermatic@gmail.com> http://www.eskimospy.com/
// port by Daniele Zannotti http://www.github.com/dzannotti <dzannotti@me.com>

var expandRootNode = function expandRootNode(keyName, data, level) {
  return level === 0;
};
var defaultItemString = function defaultItemString(type, data, itemType, itemString) {
  return _react2['default'].createElement(
    'span',
    null,
    itemType,
    ' ',
    itemString
  );
};
var defaultLabelRenderer = function defaultLabelRenderer(_ref) {
  var label = _ref[0];
  return _react2['default'].createElement(
    'span',
    null,
    label,
    ':'
  );
};
var noCustomNode = function noCustomNode() {
  return false;
};

function checkLegacyTheming(theme, props) {
  var deprecatedStylingMethodsMap = {
    getArrowStyle: 'arrow',
    getListStyle: 'nestedNodeChildren',
    getItemStringStyle: 'nestedNodeItemString',
    getLabelStyle: 'label',
    getValueStyle: 'valueText'
  };

  var deprecatedStylingMethods = (0, _keys2['default'])(deprecatedStylingMethodsMap).filter(function (name) {
    return props[name];
  });

  if (deprecatedStylingMethods.length > 0) {
    if (typeof theme === 'string') {
      theme = {
        extend: theme
      };
    } else {
      theme = (0, _extends3['default'])({}, theme);
    }

    deprecatedStylingMethods.forEach(function (name) {
      // eslint-disable-next-line no-console
      console.error('Styling method "' + name + '" is deprecated, use "theme" property instead');

      theme[deprecatedStylingMethodsMap[name]] = function (_ref2) {
        for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
          args[_key - 1] = arguments[_key];
        }

        var style = _ref2.style;
        return {
          style: (0, _extends3['default'])({}, style, props[name].apply(props, args))
        };
      };
    });
  }

  return theme;
}

function getStateFromProps(props) {
  var theme = checkLegacyTheming(props.theme, props);
  if (props.invertTheme) {
    if (typeof theme === 'string') {
      theme = theme + ':inverted';
    } else if (theme && theme.extend) {
      if (typeof theme === 'string') {
        theme = (0, _extends3['default'])({}, theme, { extend: theme.extend + ':inverted' });
      } else {
        theme = (0, _extends3['default'])({}, theme, { extend: (0, _reactBase16Styling.invertTheme)(theme.extend) });
      }
    } else if (theme) {
      theme = (0, _reactBase16Styling.invertTheme)(theme);
    }
  }
  return {
    styling: (0, _createStylingFromTheme2['default'])(theme)
  };
}

var JSONTree = function (_React$Component) {
  (0, _inherits3['default'])(JSONTree, _React$Component);

  function JSONTree(props) {
    (0, _classCallCheck3['default'])(this, JSONTree);

    var _this = (0, _possibleConstructorReturn3['default'])(this, _React$Component.call(this, props));

    _this.state = getStateFromProps(props);
    return _this;
  }

  JSONTree.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
    var _this2 = this;

    if (['theme', 'invertTheme'].find(function (k) {
      return nextProps[k] !== _this2.props[k];
    })) {
      this.setState(getStateFromProps(nextProps));
    }
  };

  JSONTree.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps) {
    var _this3 = this;

    return !!(0, _keys2['default'])(nextProps).find(function (k) {
      return k === 'keyPath' ? nextProps[k].join('/') !== _this3.props[k].join('/') : nextProps[k] !== _this3.props[k];
    });
  };

  JSONTree.prototype.render = function render() {
    var _props = this.props,
        value = _props.data,
        keyPath = _props.keyPath,
        postprocessValue = _props.postprocessValue,
        hideRoot = _props.hideRoot,
        theme = _props.theme,
        _ = _props.invertTheme,
        rest = (0, _objectWithoutProperties3['default'])(_props, ['data', 'keyPath', 'postprocessValue', 'hideRoot', 'theme', 'invertTheme']);
    var styling = this.state.styling;


    return _react2['default'].createElement(
      'ul',
      styling('tree'),
      _react2['default'].createElement(_JSONNode2['default'], (0, _extends3['default'])({}, (0, _extends3['default'])({ postprocessValue: postprocessValue, hideRoot: hideRoot, styling: styling }, rest), {
        keyPath: hideRoot ? [] : keyPath,
        value: postprocessValue(value)
      }))
    );
  };

  return JSONTree;
}(_react2['default'].Component);

JSONTree.propTypes = {
  data: _propTypes2['default'].oneOfType([_propTypes2['default'].array, _propTypes2['default'].object]).isRequired,
  hideRoot: _propTypes2['default'].bool,
  theme: _propTypes2['default'].oneOfType([_propTypes2['default'].object, _propTypes2['default'].string]),
  invertTheme: _propTypes2['default'].bool,
  keyPath: _propTypes2['default'].arrayOf(_propTypes2['default'].oneOfType([_propTypes2['default'].string, _propTypes2['default'].number])),
  postprocessValue: _propTypes2['default'].func,
  sortObjectKeys: _propTypes2['default'].oneOfType([_propTypes2['default'].func, _propTypes2['default'].bool])
};
JSONTree.defaultProps = {
  shouldExpandNode: expandRootNode,
  hideRoot: false,
  keyPath: ['root'],
  getItemString: defaultItemString,
  labelRenderer: defaultLabelRenderer,
  valueRenderer: identity,
  postprocessValue: identity,
  isCustomNode: noCustomNode,
  collectionLimit: 50,
  invertTheme: true
};
exports['default'] = JSONTree;
},{"babel-runtime/helpers/objectWithoutProperties":"../node_modules/babel-runtime/helpers/objectWithoutProperties.js","babel-runtime/helpers/classCallCheck":"../node_modules/babel-runtime/helpers/classCallCheck.js","babel-runtime/helpers/possibleConstructorReturn":"../node_modules/babel-runtime/helpers/possibleConstructorReturn.js","babel-runtime/helpers/inherits":"../node_modules/babel-runtime/helpers/inherits.js","babel-runtime/helpers/extends":"../node_modules/babel-runtime/helpers/extends.js","babel-runtime/core-js/object/keys":"../node_modules/babel-runtime/core-js/object/keys.js","react":"../node_modules/react/index.js","prop-types":"../node_modules/prop-types/index.js","./JSONNode":"../node_modules/react-json-tree/lib/JSONNode.js","./createStylingFromTheme":"../node_modules/react-json-tree/lib/createStylingFromTheme.js","react-base16-styling":"../node_modules/react-base16-styling/lib/index.js"}],"../src/components/json-tree.js":[function(require,module,exports) {
"use strict";

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

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

var _reactJsonTree = _interopRequireDefault(require("react-json-tree"));

var _theme = require("./../theme");

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

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function JSONTree(props) {
  return /*#__PURE__*/_react.default.createElement(_reactJsonTree.default, _extends({
    invertTheme: false,
    theme: _theme.jsonTreeTheme,
    hideRoot: true
  }, props));
}
},{"react":"../node_modules/react/index.js","react-json-tree":"../node_modules/react-json-tree/lib/index.js","./../theme":"../src/theme.js"}],"../src/components/heading.js":[function(require,module,exports) {
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.HeadingButton = exports.HeadingWithButton = exports.Heading = void 0;

var _styled = _interopRequireDefault(require("@emotion/styled"));

var _theme = _interopRequireDefault(require("../theme"));

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

var Heading = (0, _styled.default)("h2")({
  color: _theme.default.softerMain,
  padding: 0,
  margin: 0,
  fontWeight: 400,
  letterSpacing: "1px",
  fontSize: "13px",
  textTransform: "uppercase",
  flexGrow: 1
});
exports.Heading = Heading;
Heading.displayName = "Heading";
var HeadingWithButton = (0, _styled.default)("div")({
  display: "flex"
});
exports.HeadingWithButton = HeadingWithButton;
HeadingWithButton.displayName = "HeadingWithButton";
var HeadingButton = (0, _styled.default)("button")({
  padding: "6px 10px",
  margin: "-6px -10px 0 8px",
  fontWeight: 400,
  letterSpacing: "1px",
  fontSize: "11px",
  color: _theme.default.white80,
  textTransform: "uppercase",
  transition: "background 0.3s, color 0.3s",
  borderRadius: "2px",
  border: "none",
  background: "transparent",
  "&:hover": {
    background: _theme.default.main40,
    color: _theme.default.white,
    cursor: "pointer"
  },
  "&:focus": {
    outline: "none"
  },
  "&:active": {
    background: _theme.default.main60
  }
});
exports.HeadingButton = HeadingButton;
HeadingButton.displayName = "HeadingButton";
},{"@emotion/styled":"../node_modules/@emotion/styled/dist/styled.browser.esm.js","../theme":"../src/theme.js"}],"../src/tabs/state.js":[function(require,module,exports) {
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getItemString = getItemString;
exports.shouldExpandNode = _shouldExpandNode;
exports.default = StateTab;

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

var _styled = _interopRequireDefault(require("@emotion/styled"));

var _unstated = require("unstated");

var _editor = _interopRequireDefault(require("../state/editor"));

var _stateTab = _interopRequireDefault(require("../state/state-tab"));

var _formatSelectionObject = require("./../utils/format-selection-object");

var _splitView = require("../components/split-view");

var _jsonTree = _interopRequireDefault(require("../components/json-tree"));

var _heading = require("./../components/heading");

var _theme = _interopRequireDefault(require("../theme"));

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

var JSONTreeWrapper = (0, _styled.default)("div")({
  padding: "0 0 9px 0",
  overflow: "hidden"
});
JSONTreeWrapper.displayName = "JSONTreeWrapper";
var Section = (0, _styled.default)("div")({
  minWidth: "180px",
  boxSizing: "border-box",
  "& + &": {
    paddingTop: "9px"
  }
});
Section.displayName = "Section";
var Group = (0, _styled.default)("div")({
  margin: "0.5em 0px 0.5em 1em"
});
Group.displayName = "Group";
var GroupRow = (0, _styled.default)("div")({
  paddingTop: "0.25em"
});
GroupRow.displayName = "GroupRow";
var Key = (0, _styled.default)("span")({
  display: "inline-block",
  color: _theme.default.syntax.base0D,
  margin: "0px 0.5em 0px 0px"
});
Key.displayName = "Key";
var ValueNum = (0, _styled.default)("span")({
  color: _theme.default.syntax.base09
});
ValueNum.displayName = "ValueNum";
var LogNodeButton = (0, _styled.default)("button")({
  color: _theme.default.white60,
  background: "none",
  border: "none",
  transition: "background 0.3s, color 0.3s",
  borderRadius: "3px",
  "&:hover": {
    cursor: "pointer",
    background: _theme.default.main40,
    color: _theme.default.white
  },
  "&:focus": {
    outline: "none"
  }
});
LogNodeButton.displayName = "LogNodeButton";

function getItemString(doc, action) {
  return function getItemStringWithBindedDoc(type, value, defaultView, keysCount) {
    var logButton = /*#__PURE__*/_react.default.createElement(LogNodeButton, {
      onClick: function onClick(e) {
        e.preventDefault();
        e.stopPropagation();
        action({
          doc: doc,
          node: value
        });
      }
    }, "log");

    if (type === "Object" && value.type) {
      return /*#__PURE__*/_react.default.createElement("span", null, "{} ", value.type, " ", logButton);
    }

    return /*#__PURE__*/_react.default.createElement("span", null, defaultView, " ", keysCount, " ", logButton);
  };
}

function getItemStringForMark(type, value, defaultView, keysCount) {
  if (type === "Object" && value.type) {
    return /*#__PURE__*/_react.default.createElement("span", null, "{} ", value.type);
  }

  return /*#__PURE__*/_react.default.createElement("span", null, defaultView, " ", keysCount);
}

function _shouldExpandNode(expandPath, nodePath) {
  var path = [].concat(nodePath).reverse();
  if (!expandPath) return false; // Expand attrs if node has them.

  expandPath.push("attrs");
  if (path.length > expandPath.length) return false;
  if (path.join(".") === expandPath.join(".")) return true;
  if (path.every(function (el, idx) {
    return el === expandPath[idx];
  })) return true;
  return false;
}

function StateTab() {
  return /*#__PURE__*/_react.default.createElement(_unstated.Subscribe, {
    to: [_editor.default, _stateTab.default]
  }, function (editorState, stateTab) {
    var logNodeFromJSON = editorState.logNodeFromJSON;
    var _editorState$state = editorState.state,
        state = _editorState$state.state,
        activeMarks = _editorState$state.activeMarks,
        expandPath = _editorState$state.expandPath;
    var toggleSelection = stateTab.toggleSelection;
    var selectionExpanded = stateTab.state.selectionExpanded;
    var doc = state.doc.toJSON();
    return /*#__PURE__*/_react.default.createElement(_splitView.SplitView, null, /*#__PURE__*/_react.default.createElement(_splitView.SplitViewCol, {
      grow: true
    }, /*#__PURE__*/_react.default.createElement(_heading.HeadingWithButton, null, /*#__PURE__*/_react.default.createElement(_heading.Heading, null, "Current Doc"), /*#__PURE__*/_react.default.createElement(_heading.HeadingButton, {
      onClick: function onClick() {
        return console.log(state);
      }
    }, "Log State")), /*#__PURE__*/_react.default.createElement(_jsonTree.default, {
      data: doc,
      hideRoot: true,
      getItemString: getItemString(doc, logNodeFromJSON),
      shouldExpandNode: function shouldExpandNode(nodePath) {
        return _shouldExpandNode(expandPath, nodePath);
      }
    })), /*#__PURE__*/_react.default.createElement(_splitView.SplitViewCol, {
      sep: true,
      minWidth: 220
    }, /*#__PURE__*/_react.default.createElement(Section, null, /*#__PURE__*/_react.default.createElement(_heading.HeadingWithButton, null, /*#__PURE__*/_react.default.createElement(_heading.Heading, null, "Selection"), /*#__PURE__*/_react.default.createElement(_heading.HeadingButton, {
      onClick: function onClick() {
        return toggleSelection();
      }
    }, selectionExpanded ? "▼" : "▶")), /*#__PURE__*/_react.default.createElement(JSONTreeWrapper, null, /*#__PURE__*/_react.default.createElement(_jsonTree.default, {
      data: selectionExpanded ? (0, _formatSelectionObject.expandedStateFormatSelection)(state.selection) : (0, _formatSelectionObject.collapsedStateFormatSelection)(state.selection),
      hideRoot: true
    }))), /*#__PURE__*/_react.default.createElement(Section, null, /*#__PURE__*/_react.default.createElement(_heading.Heading, null, "Active Marks"), /*#__PURE__*/_react.default.createElement(JSONTreeWrapper, null, activeMarks.length ? /*#__PURE__*/_react.default.createElement(_jsonTree.default, {
      data: activeMarks,
      hideRoot: true,
      getItemString: getItemStringForMark
    }) : /*#__PURE__*/_react.default.createElement(Group, null, /*#__PURE__*/_react.default.createElement(GroupRow, null, /*#__PURE__*/_react.default.createElement(Key, null, "no active marks"))))), /*#__PURE__*/_react.default.createElement(Section, null, /*#__PURE__*/_react.default.createElement(_heading.Heading, null, "Document Stats"), /*#__PURE__*/_react.default.createElement(Group, null, /*#__PURE__*/_react.default.createElement(GroupRow, null, /*#__PURE__*/_react.default.createElement(Key, null, "nodeSize:"), /*#__PURE__*/_react.default.createElement(ValueNum, null, state.doc.nodeSize)), /*#__PURE__*/_react.default.createElement(GroupRow, null, /*#__PURE__*/_react.default.createElement(Key, null, "childCount:"), /*#__PURE__*/_react.default.createElement(ValueNum, null, state.doc.childCount))))));
  });
}
},{"react":"../node_modules/react/index.js","@emotion/styled":"../node_modules/@emotion/styled/dist/styled.browser.esm.js","unstated":"../node_modules/unstated/lib/unstated.es.js","../state/editor":"../src/state/editor.js","../state/state-tab":"../src/state/state-tab.js","./../utils/format-selection-object":"../src/utils/format-selection-object.js","../components/split-view":"../src/components/split-view.js","../components/json-tree":"../src/components/json-tree.js","./../components/heading":"../src/components/heading.js","../theme":"../src/theme.js"}],"../src/components/info-panel.js":[function(require,module,exports) {
"use strict";

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

var _styled = _interopRequireDefault(require("@emotion/styled"));

var _theme = _interopRequireDefault(require("../theme"));

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

var InfoPanel = (0, _styled.default)("div")({
  position: "relative",
  top: "50%",
  transform: "translateY(-50%)",
  textAlign: "center",
  color: _theme.default.main,
  fontSize: "14px"
});
exports.InfoPanel = InfoPanel;
InfoPanel.displayName = "InfoPanel";
},{"@emotion/styled":"../node_modules/@emotion/styled/dist/styled.browser.esm.js","../theme":"../src/theme.js"}],"../src/components/list.js":[function(require,module,exports) {
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.List = List;
exports.ListItem = void 0;

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

var _styled = _interopRequireDefault(require("@emotion/styled"));

var _theme = _interopRequireDefault(require("../theme"));

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

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (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; }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function () { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

var noop = function noop() {};

var ListItem = (0, _styled.default)("div")({
  minWidth: "190px",
  width: "100%",
  display: "flex",
  boxSizing: "border-box",
  fontWeight: 400,
  letterSpacing: "1px",
  fontSize: "11px",
  color: _theme.default.white80,
  textTransform: "uppercase",
  transition: "background .3s",
  textAlign: "left",
  fontFamily: "monospace",
  border: "none",
  borderTop: "1px solid ".concat(_theme.default.main20),
  margin: 0,
  "&:first-child": {
    borderTop: "none"
  },
  "&:hover": {
    background: _theme.default.main40,
    color: _theme.default.white,
    cursor: "pointer"
  },
  "&:focus": {
    outline: "none"
  },
  "&:active": {
    background: _theme.default.main60
  }
}, function (props) {
  return {
    opacity: props.isDimmed ? 0.3 : 1,
    padding: props.nested ? "6px 18px 6px 36px" : "6px 18px",
    background: props.background ? props.background(props) : props.isSelected ? _theme.default.main40 : "transparent"
  };
});
exports.ListItem = ListItem;
ListItem.displayName = "ListItem";
var ListItemGroupContent = (0, _styled.default)("div")({
  display: "block"
}, function (props) {
  return {
    display: props.collapsed ? "none" : "block"
  };
});
ListItemGroupContent.displayName = "ListItemGroupContent";

var ListItemGroup = /*#__PURE__*/function (_PureComponent) {
  _inherits(ListItemGroup, _PureComponent);

  var _super = _createSuper(ListItemGroup);

  function ListItemGroup(props) {
    var _this;

    _classCallCheck(this, ListItemGroup);

    _this = _super.call(this, props);
    _this.state = {
      collapsed: true
    };
    return _this;
  }

  _createClass(ListItemGroup, [{
    key: "toggle",
    value: function toggle() {
      this.setState({
        collapsed: !this.state.collapsed
      });
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$props = this.props,
          items = _this$props.items,
          groupTitle = _this$props.groupTitle,
          title = _this$props.title,
          _this$props$isSelecte = _this$props.isSelected,
          isSelected = _this$props$isSelecte === void 0 ? noop : _this$props$isSelecte,
          _this$props$isPreviou = _this$props.isPrevious,
          isPrevious = _this$props$isPreviou === void 0 ? noop : _this$props$isPreviou,
          _this$props$isDimmed = _this$props.isDimmed,
          isDimmed = _this$props$isDimmed === void 0 ? noop : _this$props$isDimmed,
          _this$props$getKey = _this$props.getKey,
          getKey = _this$props$getKey === void 0 ? noop : _this$props$getKey,
          _this$props$onListIte = _this$props.onListItemClick,
          onListItemClick = _this$props$onListIte === void 0 ? noop : _this$props$onListIte,
          _this$props$onListIte2 = _this$props.onListItemDoubleClick,
          onListItemDoubleClick = _this$props$onListIte2 === void 0 ? noop : _this$props$onListIte2,
          customItemBackground = _this$props.customItemBackground;
      return /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement(ListItem, {
        key: getKey(items[0]),
        onClick: function onClick() {
          return _this2.toggle();
        },
        isSelected: items.some(isSelected) && this.state.collapsed,
        isPrevious: isPrevious(items[0], 0) && this.state.collapsed,
        isDimmed: items.every(isDimmed),
        background: customItemBackground
      }, /*#__PURE__*/_react.default.createElement("div", {
        style: {
          flexGrow: 1
        }
      }, groupTitle(items, 0)), /*#__PURE__*/_react.default.createElement("div", null, this.state.collapsed ? "▶" : "▼")), /*#__PURE__*/_react.default.createElement(ListItemGroupContent, {
        collapsed: this.state.collapsed
      }, (items || []).map(function (item, index) {
        return /*#__PURE__*/_react.default.createElement(ListItem, {
          key: getKey(item),
          nested: true,
          isSelected: isSelected(item, index),
          isPrevious: isPrevious(item, index),
          isDimmed: isDimmed(item, index),
          background: customItemBackground,
          onClick: function onClick() {
            return onListItemClick(item, index);
          },
          onDoubleClick: function onDoubleClick() {
            return onListItemDoubleClick(item, index);
          }
        }, title(item, index));
      })));
    }
  }]);

  return ListItemGroup;
}(_react.PureComponent);

function List(props) {
  var _props$isSelected = props.isSelected,
      isSelected = _props$isSelected === void 0 ? noop : _props$isSelected,
      _props$isPrevious = props.isPrevious,
      isPrevious = _props$isPrevious === void 0 ? noop : _props$isPrevious,
      _props$isDimmed = props.isDimmed,
      isDimmed = _props$isDimmed === void 0 ? noop : _props$isDimmed,
      _props$getKey = props.getKey,
      getKey = _props$getKey === void 0 ? noop : _props$getKey,
      _props$onListItemClic = props.onListItemClick,
      onListItemClick = _props$onListItemClic === void 0 ? noop : _props$onListItemClic,
      _props$onListItemDoub = props.onListItemDoubleClick,
      onListItemDoubleClick = _props$onListItemDoub === void 0 ? noop : _props$onListItemDoub;
  return /*#__PURE__*/_react.default.createElement("div", null, (props.items || []).map(function (item, index) {
    if (Array.isArray(item)) {
      return /*#__PURE__*/_react.default.createElement(ListItemGroup, _extends({}, props, {
        items: item,
        key: item[0].timestamp
      }), props.groupTitle(item, index));
    }

    return /*#__PURE__*/_react.default.createElement(ListItem, {
      key: getKey(item),
      isSelected: isSelected(item, index),
      isPrevious: isPrevious(item, index),
      isDimmed: isDimmed(item, index),
      background: props.customItemBackground,
      onClick: function onClick() {
        return onListItemClick(item, index);
      },
      onDoubleClick: function onDoubleClick() {
        return onListItemDoubleClick(item, index);
      }
    }, props.title(item, index));
  }));
}
},{"react":"../node_modules/react/index.js","@emotion/styled":"../node_modules/@emotion/styled/dist/styled.browser.esm.js","../theme":"../src/theme.js"}],"../src/components/json-diff.js":[function(require,module,exports) {
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.itemsCountString = itemsCountString;
exports.getItemString = getItemString;
exports.default = JSONDiff;

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

var _jsonTree = _interopRequireDefault(require("./json-tree"));

var _styled = _interopRequireDefault(require("@emotion/styled"));

var _theme = _interopRequireDefault(require("../theme"));

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

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; }

var Updated = (0, _styled.default)("span")({
  color: _theme.default.main
});
Updated.displayName = "Updated";
var White = (0, _styled.default)("span")({
  color: _theme.default.white
});
White.displayName = "White";
var Deleted = (0, _styled.default)("span")({
  display: "inline-block",
  background: _theme.default.lightYellow,
  color: _theme.default.lightPink,
  padding: "1px 3px 2px",
  textIndent: 0,
  textDecoration: "line-through",
  minHeight: "1ex"
});
Deleted.displayName = "Deleted";
var Added = (0, _styled.default)("span")({
  display: "inline-block",
  background: _theme.default.lightYellow,
  color: _theme.default.darkGreen,
  padding: "1px 3px 2px",
  textIndent: 0,
  minHeight: "1ex"
});
Added.displayName = "Added";

function postprocessValue(value) {
  if (value && value._t === "a") {
    var res = {};

    for (var key in value) {
      if (key !== "_t") {
        if (key[0] === "_" && !value[key.substr(1)]) {
          res[key.substr(1)] = value[key];
        } else if (value["_" + key]) {
          res[key] = [value["_" + key][0], value[key][0]];
        } else if (!value["_" + key] && key[0] !== "_") {
          res[key] = value[key];
        }
      }
    }

    return res;
  }

  return value;
}

function labelRenderer(raw) {
  return raw[0];
}

function stringifyAndShrink(val) {
  if (val === null) {
    return "null";
  }

  var str = JSON.stringify(val);

  if (typeof str === "undefined") {
    return "undefined";
  }

  return str.length > 22 ? "".concat(str.substr(0, 15), "\u2026").concat(str.substr(-5)) : str;
}

function getValueString(raw) {
  if (typeof raw === "string") {
    return raw;
  }

  return stringifyAndShrink(raw);
}

function replaceSpacesWithNonBreakingSpace(value) {
  return value.replace(/\s/gm, " ");
}

function parseTextDiff(textDiff) {
  var diffByLines = textDiff.split(/\n/gm).slice(1);
  return diffByLines.map(function (line) {
    var type = line.startsWith("-") ? "delete" : line.startsWith("+") ? "add" : "raw";
    return _defineProperty({}, type, replaceSpacesWithNonBreakingSpace(line.substr(1)));
  });
}

function valueRenderer(raw) {
  if (Array.isArray(raw)) {
    if (raw.length === 1) {
      return /*#__PURE__*/_react.default.createElement(Added, null, getValueString(raw[0]));
    }

    if (raw.length === 2) {
      return /*#__PURE__*/_react.default.createElement(Updated, null, /*#__PURE__*/_react.default.createElement(Deleted, null, getValueString(raw[0])), " =>", " ", /*#__PURE__*/_react.default.createElement(Added, null, getValueString(raw[1])));
    }

    if (raw.length === 3 && raw[1] === 0 && raw[2] === 0) {
      return /*#__PURE__*/_react.default.createElement(Deleted, null, getValueString(raw[0]));
    }

    if (raw.length === 3 && raw[2] === 2) {
      return /*#__PURE__*/_react.default.createElement(Updated, null, "\"", parseTextDiff(raw[0]).map(function (item) {
        if (item.delete) {
          return /*#__PURE__*/_react.default.createElement(Deleted, {
            key: item.delete + "delete"
          }, item.delete);
        }

        if (item.add) {
          return /*#__PURE__*/_react.default.createElement(Added, {
            key: item.add + "add"
          }, item.add);
        }

        return /*#__PURE__*/_react.default.createElement(White, {
          key: item.raw + "raw"
        }, item.raw);
      }), "\"");
    }
  }

  return "" + raw;
}

function itemsCountString(count) {
  return "".concat(count);
}

function getItemString(type, value, defaultView, keysCount) {
  switch (type) {
    case "Object":
      return /*#__PURE__*/_react.default.createElement("span", null, "{…}");

    default:
      return /*#__PURE__*/_react.default.createElement("span", null, defaultView, " ", keysCount);
  }
}

function JSONDiff(props) {
  if (!props.delta) return null;
  return /*#__PURE__*/_react.default.createElement(_jsonTree.default, {
    data: props.delta,
    hideRoot: true,
    postprocessValue: postprocessValue,
    labelRenderer: labelRenderer,
    valueRenderer: valueRenderer,
    isCustomNode: Array.isArray,
    getItemString: getItemString,
    shouldExpandNode: function shouldExpandNode() {
      return true;
    }
  });
}
},{"react":"../node_modules/react/index.js","./json-tree":"../src/components/json-tree.js","@emotion/styled":"../node_modules/@emotion/styled/dist/styled.browser.esm.js","../theme":"../src/theme.js"}],"../src/components/highlighter.js":[function(require,module,exports) {
"use strict";

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

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

var _styled = _interopRequireDefault(require("@emotion/styled"));

var _theme = _interopRequireDefault(require("../theme"));

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

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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function () { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

var CustomPre = (0, _styled.default)("pre")({
  padding: "9px 0 18px 0 !important",
  margin: 0,
  color: _theme.default.white80,
  "& .prosemirror-dev-tools-highlighter-tag": {
    color: _theme.default.main
  }
});
CustomPre.displayName = "CustomPre";
var regexp = /(&lt;\/?[\w\d\s="']+&gt;)/gim;

var highlight = function highlight(str) {
  return str.replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(regexp, "<span class='prosemirror-dev-tools-highlighter-tag'>$&</span>");
};

var Highlighter = /*#__PURE__*/function (_React$Component) {
  _inherits(Highlighter, _React$Component);

  var _super = _createSuper(Highlighter);

  function Highlighter() {
    _classCallCheck(this, Highlighter);

    return _super.apply(this, arguments);
  }

  _createClass(Highlighter, [{
    key: "render",
    value: function render() {
      if (!this.props.children) return null;
      return /*#__PURE__*/_react.default.createElement(CustomPre, {
        dangerouslySetInnerHTML: {
          __html: highlight(this.props.children)
        }
      });
    }
  }]);

  return Highlighter;
}(_react.default.Component);

exports.Highlighter = Highlighter;
},{"react":"../node_modules/react/index.js","@emotion/styled":"../node_modules/@emotion/styled/dist/styled.browser.esm.js","../theme":"../src/theme.js"}],"../src/tabs/history.js":[function(require,module,exports) {
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SelectionContentSection = SelectionContentSection;
exports.DocDiffSection = DocDiffSection;
exports.SelectionSection = SelectionSection;
exports.default = HistoryView;

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

var _styled = _interopRequireDefault(require("@emotion/styled"));

var _unstated = require("unstated");

var _editor = _interopRequireDefault(require("../state/editor"));

var _infoPanel = require("../components/info-panel");

var _heading = require("./../components/heading");

var _list = require("../components/list");

var _jsonDiff = _interopRequireDefault(require("../components/json-diff"));

var _splitView = require("../components/split-view");

var _highlighter = require("../components/highlighter");

var _theme = _interopRequireDefault(require("../theme"));

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

var Section = (0, _styled.default)("div")({
  minWidth: "180px",
  boxSizing: "border-box",
  "& + &": {
    paddingTop: "9px"
  }
});
Section.displayName = "Section";

function pad(num) {
  return ("00" + num).slice(-2);
}

function pad3(num) {
  return ("000" + num).slice(-3);
}

var formatTimestamp = function formatTimestamp(timestamp) {
  var date = new Date(timestamp);
  return [pad(date.getHours()), pad(date.getMinutes()), pad(date.getSeconds()), pad3(date.getMilliseconds())].join(":");
};

function SelectionContentSection(props) {
  if (!props.selectionContent) return null;
  return /*#__PURE__*/_react.default.createElement(Section, null, /*#__PURE__*/_react.default.createElement(_heading.Heading, null, "Selection Content"), /*#__PURE__*/_react.default.createElement(_highlighter.Highlighter, null, props.selectionContent));
}

function DocDiffSection(props) {
  if (!props.diff) return null;
  return /*#__PURE__*/_react.default.createElement(Section, null, /*#__PURE__*/_react.default.createElement(_heading.Heading, null, "Doc diff"), /*#__PURE__*/_react.default.createElement(_jsonDiff.default, {
    delta: props.diff
  }));
}

function SelectionSection(props) {
  if (!props.selection) return null;
  return /*#__PURE__*/_react.default.createElement(Section, null, /*#__PURE__*/_react.default.createElement(_heading.Heading, null, "Selection diff"), /*#__PURE__*/_react.default.createElement(_jsonDiff.default, {
    delta: props.selection
  }));
}

function HistoryView() {
  return /*#__PURE__*/_react.default.createElement(_unstated.Subscribe, {
    to: [_editor.default]
  }, function (editorState) {
    var selectHistoryItem = editorState.selectHistoryItem,
        rollbackHistory = editorState.rollbackHistory;
    var _editorState$state = editorState.state,
        history = _editorState$state.history,
        selectedHistoryItem = _editorState$state.selectedHistoryItem,
        historyRolledBackTo = _editorState$state.historyRolledBackTo;
    var prevItem = history[selectedHistoryItem + 1];
    var selectedItem = history[selectedHistoryItem];
    var historyRolledBackToItem = history[historyRolledBackTo];
    var historyList = history.reduce(function (h, item, index) {
      var prev = h[h.length - 1];
      item.index = index;

      if (!item.diff) {
        if (!prev || !Array.isArray(prev)) {
          h.push([item]);
        } else {
          prev.push(item);
        }
      } else {
        h.push(item);
      }

      return h;
    }, []).reduce(function (h, item) {
      if (Array.isArray(item) && item.length === 1) {
        h.push(item[0]);
      } else {
        h.push(item);
      }

      return h;
    }, []);

    var isSelected = function isSelected(item) {
      return item.timestamp === selectedItem.timestamp;
    };

    var isPrevious = function isPrevious(item) {
      return prevItem && item.timestamp === prevItem.timestamp;
    };

    var isDimmed = function isDimmed(item) {
      return historyRolledBackToItem && item.timestamp > historyRolledBackToItem.timestamp;
    };

    return /*#__PURE__*/_react.default.createElement(_splitView.SplitView, null, /*#__PURE__*/_react.default.createElement(_splitView.SplitViewCol, {
      noPaddings: true,
      minWidth: 190
    }, /*#__PURE__*/_react.default.createElement(_list.List, {
      items: historyList,
      getKey: function getKey(item) {
        return item.timestamp;
      },
      title: function title(item) {
        return formatTimestamp(item.timestamp);
      },
      groupTitle: function groupTitle(item) {
        return formatTimestamp(item[0].timestamp) + " [".concat(item.length, "]");
      },
      isSelected: isSelected,
      isPrevious: isPrevious,
      isDimmed: isDimmed,
      customItemBackground: function customItemBackground(props) {
        return props.isSelected ? _theme.default.main40 : props.isPrevious ? _theme.default.main20 : "transparent";
      },
      onListItemClick: function onListItemClick(item) {
        return selectHistoryItem(item.index);
      },
      onListItemDoubleClick: function onListItemDoubleClick(item) {
        return rollbackHistory(item.index);
      }
    })), /*#__PURE__*/_react.default.createElement(_splitView.SplitViewCol, {
      grow: true,
      sep: true
    }, /*#__PURE__*/_react.default.createElement(DocDiffSection, {
      diff: selectedItem.diff
    }), /*#__PURE__*/_react.default.createElement(SelectionSection, {
      selection: selectedItem.selection
    }), /*#__PURE__*/_react.default.createElement(SelectionContentSection, {
      selectionContent: selectedItem.selectionContent
    }), !selectedItem.diff && !selectedItem.selectionContent && !selectedItem.diffPending && /*#__PURE__*/_react.default.createElement(_infoPanel.InfoPanel, null, "Docs are equal.")));
  });
}
},{"react":"../node_modules/react/index.js","@emotion/styled":"../node_modules/@emotion/styled/dist/styled.browser.esm.js","unstated":"../node_modules/unstated/lib/unstated.es.js","../state/editor":"../src/state/editor.js","../components/info-panel":"../src/components/info-panel.js","./../components/heading":"../src/components/heading.js","../components/list":"../src/components/list.js","../components/json-diff":"../src/components/json-diff.js","../components/split-view":"../src/components/split-view.js","../components/highlighter":"../src/components/highlighter.js","../theme":"../src/theme.js"}],"../src/tabs/schema.js":[function(require,module,exports) {
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.postprocessValue = postprocessValue;
exports.default = SchemaTabContainer;
exports.SchemaTab = void 0;

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

var _unstated = require("unstated");

var _editor = _interopRequireDefault(require("../state/editor"));

var _splitView = require("../components/split-view");

var _jsonTree = _interopRequireDefault(require("../components/json-tree"));

var _heading = require("./../components/heading");

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

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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function () { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

var ignoreFields = ["schema", "contentExpr", "schema", "parseDOM", "toDOM"];

function postprocessValue(ignore, data) {
  if (!data || Object.prototype.toString.call(data) !== "[object Object]") {
    return data;
  }

  return Object.keys(data).filter(function (key) {
    return ignore.indexOf(key) === -1;
  }).reduce(function (res, key) {
    res[key] = data[key];
    return res;
  }, {});
}

var SchemaTab = /*#__PURE__*/function (_React$Component) {
  _inherits(SchemaTab, _React$Component);

  var _super = _createSuper(SchemaTab);

  function SchemaTab() {
    _classCallCheck(this, SchemaTab);

    return _super.apply(this, arguments);
  }

  _createClass(SchemaTab, [{
    key: "shouldComponentUpdate",
    value: function shouldComponentUpdate(nextProps) {
      return this.props.schema !== nextProps.schema;
    }
  }, {
    key: "render",
    value: function render() {
      var schema = this.props.schema;
      return /*#__PURE__*/_react.default.createElement(_splitView.SplitView, null, /*#__PURE__*/_react.default.createElement(_splitView.SplitViewCol, {
        grow: true
      }, /*#__PURE__*/_react.default.createElement(_heading.Heading, null, "Nodes"), /*#__PURE__*/_react.default.createElement(_jsonTree.default, {
        data: schema.nodes,
        postprocessValue: postprocessValue.bind(null, ignoreFields)
      })), /*#__PURE__*/_react.default.createElement(_splitView.SplitViewCol, {
        grow: true,
        sep: true
      }, /*#__PURE__*/_react.default.createElement(_heading.Heading, null, "Marks"), /*#__PURE__*/_react.default.createElement(_jsonTree.default, {
        data: schema.marks,
        postprocessValue: postprocessValue.bind(null, ignoreFields)
      })));
    }
  }]);

  return SchemaTab;
}(_react.default.Component);

exports.SchemaTab = SchemaTab;

function SchemaTabContainer() {
  return /*#__PURE__*/_react.default.createElement(_unstated.Subscribe, {
    to: [_editor.default]
  }, function (_ref) {
    var schema = _ref.state.state.schema;
    return /*#__PURE__*/_react.default.createElement(SchemaTab, {
      schema: schema
    });
  });
}
},{"react":"../node_modules/react/index.js","unstated":"../node_modules/unstated/lib/unstated.es.js","../state/editor":"../src/state/editor.js","../components/split-view":"../src/components/split-view.js","../components/json-tree":"../src/components/json-tree.js","./../components/heading":"../src/components/heading.js"}],"../src/state/plugins-tab.js":[function(require,module,exports) {
"use strict";

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

var _unstated = require("unstated");

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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function () { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

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; }

var PluginsTabStateContainer = /*#__PURE__*/function (_Container) {
  _inherits(PluginsTabStateContainer, _Container);

  var _super = _createSuper(PluginsTabStateContainer);

  function PluginsTabStateContainer() {
    var _this;

    _classCallCheck(this, PluginsTabStateContainer);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _super.call.apply(_super, [this].concat(args));

    _defineProperty(_assertThisInitialized(_this), "state", {
      selected: 0
    });

    _defineProperty(_assertThisInitialized(_this), "selectPlugin", function (index) {
      _this.setState({
        selected: index
      });
    });

    return _this;
  }

  return PluginsTabStateContainer;
}(_unstated.Container);

exports.default = PluginsTabStateContainer;
},{"unstated":"../node_modules/unstated/lib/unstated.es.js"}],"../src/tabs/plugins.js":[function(require,module,exports) {
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.valueRenderer = valueRenderer;
exports.PluginState = PluginState;
exports.default = PluginsTab;

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

var _unstated = require("unstated");

var _editor = _interopRequireDefault(require("../state/editor"));

var _pluginsTab = _interopRequireDefault(require("../state/plugins-tab"));

var _infoPanel = require("../components/info-panel");

var _heading = require("./../components/heading");

var _jsonTree = _interopRequireDefault(require("../components/json-tree"));

var _list = require("../components/list");

var _splitView = require("../components/split-view");

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

function valueRenderer(raw) {
  if (typeof (arguments.length <= 1 ? undefined : arguments[1]) === "function") {
    return "func";
  }

  return raw;
}

function PluginState(props) {
  return /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement(_heading.Heading, null, "Plugin State"), /*#__PURE__*/_react.default.createElement(_jsonTree.default, {
    data: props.pluginState,
    valueRenderer: valueRenderer
  }));
}

function PluginsTab() {
  return /*#__PURE__*/_react.default.createElement(_unstated.Subscribe, {
    to: [_editor.default, _pluginsTab.default]
  }, function (editorState, pluginsTabState) {
    var state = editorState.state.state;
    var plugins = state.plugins;
    var selectedPlugin = plugins[pluginsTabState.state.selected];
    var selectedPluginState = selectedPlugin.getState(state);
    return /*#__PURE__*/_react.default.createElement(_splitView.SplitView, null, /*#__PURE__*/_react.default.createElement(_splitView.SplitViewCol, {
      noPaddings: true
    }, /*#__PURE__*/_react.default.createElement(_list.List, {
      items: plugins,
      getKey: function getKey(plugin) {
        return plugin.key;
      },
      title: function title(plugin) {
        return plugin.key;
      },
      isSelected: function isSelected(plugin, index) {
        return pluginsTabState.state.selected === index;
      },
      isDimmed: function isDimmed(plugin) {
        return !plugin.getState(state);
      },
      onListItemClick: function onListItemClick(plugin, index) {
        return pluginsTabState.selectPlugin(index);
      }
    })), /*#__PURE__*/_react.default.createElement(_splitView.SplitViewCol, {
      grow: true,
      sep: true
    }, selectedPluginState ? /*#__PURE__*/_react.default.createElement(PluginState, {
      pluginState: selectedPluginState
    }) : /*#__PURE__*/_react.default.createElement(_infoPanel.InfoPanel, null, "Plugin doesn't have any state")));
  });
}
},{"react":"../node_modules/react/index.js","unstated":"../node_modules/unstated/lib/unstated.es.js","../state/editor":"../src/state/editor.js","../state/plugins-tab":"../src/state/plugins-tab.js","../components/info-panel":"../src/components/info-panel.js","./../components/heading":"../src/components/heading.js","../components/json-tree":"../src/components/json-tree.js","../components/list":"../src/components/list.js","../components/split-view":"../src/components/split-view.js"}],"../src/state/structure-tab.js":[function(require,module,exports) {
"use strict";

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

var _unstated = require("unstated");

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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function () { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

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; }

var StructureTabStateContainer = /*#__PURE__*/function (_Container) {
  _inherits(StructureTabStateContainer, _Container);

  var _super = _createSuper(StructureTabStateContainer);

  function StructureTabStateContainer() {
    var _this;

    _classCallCheck(this, StructureTabStateContainer);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _super.call.apply(_super, [this].concat(args));

    _defineProperty(_assertThisInitialized(_this), "state", {
      selectedNode: null
    });

    _defineProperty(_assertThisInitialized(_this), "selectNode", function (_ref) {
      var node = _ref.node;

      _this.setState({
        selectedNode: node
      });
    });

    return _this;
  }

  return StructureTabStateContainer;
}(_unstated.Container);

exports.default = StructureTabStateContainer;
},{"unstated":"../node_modules/unstated/lib/unstated.es.js"}],"../src/tabs/structure.js":[function(require,module,exports) {
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.BlockNodeContent = BlockNodeContent;
exports.BlockNode = BlockNode;
exports.InlineNode = InlineNode;
exports.default = GraphTab;

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

var _styled = _interopRequireDefault(require("@emotion/styled"));

var _unstated = require("unstated");

var _theme = _interopRequireDefault(require("../theme"));

var _editor = _interopRequireDefault(require("../state/editor"));

var _structureTab = _interopRequireDefault(require("../state/structure-tab"));

var _splitView = require("../components/split-view");

var _jsonTree = _interopRequireDefault(require("../components/json-tree"));

var _heading = require("./../components/heading");

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

var GraphWrapper = (0, _styled.default)("div")({
  marginTop: "12px"
});
GraphWrapper.displayName = "GraphWrapper";
var BlockNodeWrapper = (0, _styled.default)("div")({});
BlockNodeWrapper.displayName = "BlockNodeWrapper";
var BlockNodeContentView = (0, _styled.default)("div")({
  padding: "0 12px",
  boxSizing: "border-box",
  borderLeft: "1px solid ".concat(_theme.default.white20),
  borderRight: "1px solid ".concat(_theme.default.white20)
});
BlockNodeContentView.displayName = "BlockNodeContentView";
var BlockNodeContentViewWithInline = (0, _styled.default)("div")({
  padding: "0 12px",
  display: "flex",
  width: "100%",
  boxSizing: "border-box",
  borderLeft: "1px solid ".concat(_theme.default.white20),
  borderRight: "1px solid ".concat(_theme.default.white20),
  flexWrap: "wrap"
});
BlockNodeContentViewWithInline.displayName = "BlockNodeContentViewWithInline";
var BlockNodeView = (0, _styled.default)("div")({
  width: "100%",
  marginBottom: "3px",
  boxSizing: "border-box",
  display: "flex",
  "&:hover": {
    cursor: "pointer"
  }
}, function (_ref) {
  var bg = _ref.bg;
  return {
    background: bg
  };
});
BlockNodeView.displayName = "BlockNodeView";
var Side = (0, _styled.default)("div")({
  padding: "3px 6px",
  background: "rgba(255, 255, 255, 0.3)"
});
Side.displayName = "Side";
var Center = (0, _styled.default)("div")({
  flexGrow: 1,
  padding: "3px 9px",
  whiteSpace: "pre"
});
Center.displayName = "Center";
var InlineNodeView = (0, _styled.default)("div")({
  flexGrow: 1,
  marginBottom: "3px",
  display: "flex",
  boxSizing: "border-box",
  "&:hover": {
    cursor: "pointer"
  }
}, function (_ref2) {
  var bg = _ref2.bg;
  return {
    background: bg
  };
});
InlineNodeView.displayName = "InlineNodeView";

function BlockNodeContent(props) {
  if (!props.content || !props.content.content || !props.content.content.length) return null;
  var content = props.content.content;

  if (content[0].isBlock) {
    var _startPos = props.startPos + 1;

    return /*#__PURE__*/_react.default.createElement(BlockNodeContentView, null, content.map(function (childNode, index) {
      var pos = _startPos;
      _startPos += childNode.nodeSize;
      return /*#__PURE__*/_react.default.createElement(BlockNode, {
        key: index,
        node: childNode,
        colors: props.colors,
        onNodeSelected: props.onNodeSelected,
        startPos: pos
      });
    }));
  }

  var startPos = props.startPos;
  return /*#__PURE__*/_react.default.createElement(BlockNodeContentViewWithInline, null, content.map(function (childNode, index) {
    var pos = startPos;
    startPos += childNode.nodeSize;
    return /*#__PURE__*/_react.default.createElement(InlineNode, {
      key: index,
      index: index,
      node: childNode,
      bg: props.colors[childNode.type.name],
      onNodeSelected: props.onNodeSelected,
      startPos: pos
    });
  }));
}

function BlockNode(props) {
  var colors = props.colors,
      node = props.node,
      startPos = props.startPos;
  var color = colors[node.type.name];
  return /*#__PURE__*/_react.default.createElement(BlockNodeWrapper, null, /*#__PURE__*/_react.default.createElement(BlockNodeView, {
    bg: color,
    onClick: function onClick() {
      return props.onNodeSelected({
        node: node
      });
    }
  }, /*#__PURE__*/_react.default.createElement(Side, null, startPos), /*#__PURE__*/_react.default.createElement(Center, null, node.type.name), /*#__PURE__*/_react.default.createElement(Side, null, startPos + node.nodeSize - 1)), /*#__PURE__*/_react.default.createElement(BlockNodeContent, {
    content: node.content,
    colors: colors,
    onNodeSelected: props.onNodeSelected,
    startPos: startPos
  }));
}

function InlineNode(props) {
  var node = props.node,
      bg = props.bg,
      startPos = props.startPos,
      index = props.index;
  var marks = node.marks.length === 1 ? " - [".concat(node.marks[0].type.name, "]") : node.marks.length > 1 ? " - [".concat(node.marks.length, " marks]") : "";
  return /*#__PURE__*/_react.default.createElement(InlineNodeView, {
    onClick: function onClick() {
      return props.onNodeSelected({
        node: node
      });
    },
    bg: bg
  }, index === 0 ? /*#__PURE__*/_react.default.createElement(Side, null, startPos) : null, /*#__PURE__*/_react.default.createElement(Center, null, node.type.name, " ", marks), /*#__PURE__*/_react.default.createElement(Side, null, startPos + node.nodeSize));
}

function GraphTab() {
  return /*#__PURE__*/_react.default.createElement(_unstated.Subscribe, {
    to: [_editor.default, _structureTab.default]
  }, function (editorState, structureTabState) {
    var _editorState$state = editorState.state,
        state = _editorState$state.state,
        nodeColors = _editorState$state.nodeColors;
    var selectedNode = structureTabState.state.selectedNode;
    var selected = selectedNode ? selectedNode : state.doc;
    return /*#__PURE__*/_react.default.createElement(_splitView.SplitView, null, /*#__PURE__*/_react.default.createElement(_splitView.SplitViewCol, {
      grow: true
    }, /*#__PURE__*/_react.default.createElement(_heading.Heading, null, "Current Doc"), /*#__PURE__*/_react.default.createElement(GraphWrapper, null, /*#__PURE__*/_react.default.createElement(BlockNode, {
      colors: nodeColors,
      node: state.doc,
      startPos: 0,
      onNodeSelected: structureTabState.selectNode
    }))), /*#__PURE__*/_react.default.createElement(_splitView.SplitViewCol, {
      sep: true,
      minWidth: 200,
      maxWidth: 300
    }, /*#__PURE__*/_react.default.createElement(_heading.HeadingWithButton, null, /*#__PURE__*/_react.default.createElement(_heading.Heading, null, "Node Info"), /*#__PURE__*/_react.default.createElement(_heading.HeadingButton, {
      onClick: function onClick() {
        return console.log(selected);
      }
    }, "Log Node")), /*#__PURE__*/_react.default.createElement(_jsonTree.default, {
      data: selected.toJSON(),
      hideRoot: true,
      shouldExpandNode: function shouldExpandNode() {
        return selected.type.name !== "doc" ? true : false;
      }
    })));
  });
}
},{"react":"../node_modules/react/index.js","@emotion/styled":"../node_modules/@emotion/styled/dist/styled.browser.esm.js","unstated":"../node_modules/unstated/lib/unstated.es.js","../theme":"../src/theme.js","../state/editor":"../src/state/editor.js","../state/structure-tab":"../src/state/structure-tab.js","../components/split-view":"../src/components/split-view.js","../components/json-tree":"../src/components/json-tree.js","./../components/heading":"../src/components/heading.js"}],"../src/tabs/snapshots.js":[function(require,module,exports) {
"use strict";

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

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

var _styled = _interopRequireDefault(require("@emotion/styled"));

var _unstated = require("unstated");

var _editor = _interopRequireDefault(require("../state/editor"));

var _splitView = require("../components/split-view");

var _list = require("../components/list");

var _infoPanel = require("../components/info-panel");

var _theme = _interopRequireDefault(require("../theme"));

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

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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function () { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

var ActionButton = (0, _styled.default)("button")({
  padding: "6px 10px",
  fontWeight: 400,
  letterSpacing: "1px",
  fontSize: "11px",
  color: _theme.default.white80,
  background: _theme.default.white10,
  textTransform: "uppercase",
  transition: "background 0.3s, color 0.3s",
  borderRadius: "2px",
  border: "none",
  "& + &": {
    marginLeft: "4px"
  },
  "&:hover": {
    background: _theme.default.main40,
    color: _theme.default.white,
    cursor: "pointer"
  },
  "&:focus": {
    outline: "none"
  },
  "&:active": {
    background: _theme.default.main60
  }
});
ActionButton.displayName = "ActionButton";
var ListItem = (0, _styled.default)("div")({
  height: "24px",
  lineHeight: "24px",
  display: "flex",
  width: "100%"
});
ListItem.displayName = "ListItem";
var ListItemTitle = (0, _styled.default)("div")({
  flexGrow: 1
});
ListItemTitle.displayName = "ListItemTitle";

function SnapshotsList(_ref) {
  var snapshots = _ref.snapshots,
      deleteSnapshot = _ref.deleteSnapshot,
      loadSnapshot = _ref.loadSnapshot;
  return /*#__PURE__*/_react.default.createElement(_list.List, {
    getKey: function getKey(item) {
      return item.name + item.timestamp;
    },
    items: snapshots,
    title: function title(item) {
      return /*#__PURE__*/_react.default.createElement(ListItem, null, /*#__PURE__*/_react.default.createElement(ListItemTitle, null, item.name), /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement(ActionButton, {
        onClick: function onClick() {
          return deleteSnapshot(item);
        }
      }, "delete"), /*#__PURE__*/_react.default.createElement(ActionButton, {
        onClick: function onClick() {
          return loadSnapshot(item);
        }
      }, "restore")));
    }
  });
}

var SnapshotTab = /*#__PURE__*/function (_React$Component) {
  _inherits(SnapshotTab, _React$Component);

  var _super = _createSuper(SnapshotTab);

  function SnapshotTab() {
    _classCallCheck(this, SnapshotTab);

    return _super.apply(this, arguments);
  }

  _createClass(SnapshotTab, [{
    key: "shouldComponentUpdate",
    value: function shouldComponentUpdate(nextProps) {
      return this.props.snapshots !== nextProps.snapshots;
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props = this.props,
          snapshots = _this$props.snapshots,
          loadSnapshot = _this$props.loadSnapshot,
          deleteSnapshot = _this$props.deleteSnapshot;
      return /*#__PURE__*/_react.default.createElement(_splitView.SplitView, null, /*#__PURE__*/_react.default.createElement(_splitView.SplitViewCol, {
        noPaddings: true,
        grow: true
      }, snapshots && snapshots.length ? /*#__PURE__*/_react.default.createElement(SnapshotsList, {
        snapshots: snapshots,
        loadSnapshot: loadSnapshot,
        deleteSnapshot: deleteSnapshot
      }) : /*#__PURE__*/_react.default.createElement(_infoPanel.InfoPanel, null, "No saved snapshots yet. Press \"Save Snapshot\" button to add one.")));
    }
  }]);

  return SnapshotTab;
}(_react.default.Component);

function SnapshotsTabContainer() {
  return /*#__PURE__*/_react.default.createElement(_unstated.Subscribe, {
    to: [_editor.default]
  }, function (_ref2) {
    var snapshots = _ref2.state.snapshots,
        loadSnapshot = _ref2.loadSnapshot,
        deleteSnapshot = _ref2.deleteSnapshot;
    return /*#__PURE__*/_react.default.createElement(SnapshotTab, {
      snapshots: snapshots,
      loadSnapshot: loadSnapshot,
      deleteSnapshot: deleteSnapshot
    });
  });
}
},{"react":"../node_modules/react/index.js","@emotion/styled":"../node_modules/@emotion/styled/dist/styled.browser.esm.js","unstated":"../node_modules/unstated/lib/unstated.es.js","../state/editor":"../src/state/editor.js","../components/split-view":"../src/components/split-view.js","../components/list":"../src/components/list.js","../components/info-panel":"../src/components/info-panel.js","../theme":"../src/theme.js"}],"../src/components/css-reset.js":[function(require,module,exports) {
"use strict";

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

var _styled = _interopRequireDefault(require("@emotion/styled"));

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

var CSSReset = (0, _styled.default)("div")({
  fontSize: "100%",
  lineHeight: 1,
  "& li + li": {
    margin: 0
  }
});
CSSReset.displayName = "CSSReset";
var _default = CSSReset;
exports.default = _default;
},{"@emotion/styled":"../node_modules/@emotion/styled/dist/styled.browser.esm.js"}],"../src/components/node-picker/index.js":[function(require,module,exports) {
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.NodePickerTrigger = exports.NodePicker = void 0;

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

var _styled = _interopRequireDefault(require("@emotion/styled"));

var _theme = _interopRequireDefault(require("../../theme"));

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

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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function () { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

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; }

var icon = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACYAAAAmCAQAAAACNCElAAAAxklEQVRIx+2Vuw3DMAxEXWUD9VrKvTYJRzAygWpPkSVcBlDtJS6Fg8AQqQ+lAEECXU08iid+pmnoTwWDKzbU6IEbLnkYQaMlD9uA6iqAUArQwDBgX4T1Z+uF4Q4PB/sZmH/1e1BCRZiLhqgWKsJsYjJLUPkDEJKjvmPWwnwCtcKoW4O5VnpTFmaVb8o3LXONOiZAcI3aYe5UIFXiUmv77doOc7oUpDoozLU5iiPFqYtcW4W01LJP3FEiwzXBLG9SUBNq6Ef0BJ8IApq+rItIAAAAAElFTkSuQmCC";
var NodePickerStyled = (0, _styled.default)("div")({
  position: "absolute",
  pointerEvents: "none",
  top: 0,
  left: 0,
  background: "rgba(0, 0, 255, 0.3)",
  zIndex: 99999,
  cursor: "pointer"
}, function (_ref) {
  var nodePicker = _ref.nodePicker;
  return {
    transform: "translateX(".concat(nodePicker.left, "px) translateY(").concat(nodePicker.top, "px)"),
    display: nodePicker.top && nodePicker.left ? "block" : "none",
    width: "".concat(nodePicker.width, "px"),
    height: "".concat(nodePicker.height, "px")
  };
});
NodePickerStyled.displayName = "NodePickerStyled";

var NodePicker = /*#__PURE__*/function (_React$Component) {
  _inherits(NodePicker, _React$Component);

  var _super = _createSuper(NodePicker);

  function NodePicker() {
    var _this;

    _classCallCheck(this, NodePicker);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _super.call.apply(_super, [this].concat(args));

    _defineProperty(_assertThisInitialized(_this), "handleMouseMove", function (e) {
      if (!_this.props.nodePicker.active) return;

      _this.props.onMouseMove(e.target);
    });

    _defineProperty(_assertThisInitialized(_this), "handleNodeClick", function (e) {
      if (!_this.props.nodePicker.active) return;
      e.preventDefault();

      _this.props.onSelect(e.target);
    });

    _defineProperty(_assertThisInitialized(_this), "closePicker", function () {
      if (!_this.props.nodePicker.active) return;

      _this.props.onClose();
    });

    return _this;
  }

  _createClass(NodePicker, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      if (this.props.nodePicker.active) {
        this.initEventHandlers();
      }
    }
  }, {
    key: "componentWillReceiveProps",
    value: function componentWillReceiveProps(nextProps) {
      this.destroyEventHandlers();

      if (nextProps.nodePicker.active) {
        this.initEventHandlers();
      }
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      this.destroyEventHandlers();
    }
  }, {
    key: "initEventHandlers",
    value: function initEventHandlers() {
      document.addEventListener("mousemove", this.handleMouseMove);
      document.addEventListener("click", this.handleNodeClick);
      document.addEventListener("keydown", this.closePicker);
    }
  }, {
    key: "destroyEventHandlers",
    value: function destroyEventHandlers() {
      document.removeEventListener("mousemove", this.handleMouseMove);
      document.removeEventListener("click", this.handleNodeClick);
      document.removeEventListener("keydown", this.closePicker);
    }
  }, {
    key: "render",
    value: function render() {
      return /*#__PURE__*/_react.default.createElement(NodePickerStyled, {
        nodePicker: this.props.nodePicker
      });
    }
  }]);

  return NodePicker;
}(_react.default.Component);

exports.NodePicker = NodePicker;
var NodePickerTrigger = (0, _styled.default)("div")({
  position: "absolute",
  right: "4px",
  top: "-28px",
  width: "24px",
  height: "24px",
  borderRadius: "3px",
  "&:hover": {
    backgroundColor: _theme.default.main80,
    cursor: "pointer"
  }
}, function (_ref2) {
  var isActive = _ref2.isActive;
  return {
    background: "".concat(isActive ? _theme.default.main : _theme.default.main60, " url(\"").concat(icon, "\")"),
    backgroundSize: "20px 20px",
    backgroundRepeat: "none",
    backgroundPosition: "50% 50%"
  };
});
exports.NodePickerTrigger = NodePickerTrigger;
NodePickerTrigger.displayName = "NodePickerTrigger";
},{"react":"../node_modules/react/index.js","@emotion/styled":"../node_modules/@emotion/styled/dist/styled.browser.esm.js","../../theme":"../src/theme.js"}],"../src/components/save-snapshot-button.js":[function(require,module,exports) {
"use strict";

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

var _styled = _interopRequireDefault(require("@emotion/styled"));

var _theme = _interopRequireDefault(require("../theme"));

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

var SaveSnapshotButton = (0, _styled.default)("div")({
  position: "absolute",
  right: "32px",
  top: "-28px",
  color: _theme.default.white,
  background: _theme.default.main60,
  fontSize: "12px",
  lineHeight: "25px",
  padding: "0 6px",
  height: "24px",
  backgroundSize: "20px 20px",
  backgroundRepeat: "none",
  backgroundPosition: "50% 50%",
  borderRadius: "3px",
  "&:hover": {
    backgroundColor: _theme.default.main80,
    cursor: "pointer"
  }
});
SaveSnapshotButton.displayName = "SaveSnapshotButton";
var _default = SaveSnapshotButton;
exports.default = _default;
},{"@emotion/styled":"../node_modules/@emotion/styled/dist/styled.browser.esm.js","../theme":"../src/theme.js"}],"../src/dev-tools-expanded.js":[function(require,module,exports) {
"use strict";

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

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

var _reactDock = _interopRequireDefault(require("react-dock"));

var _styled = _interopRequireDefault(require("@emotion/styled"));

var _tabs = require("./components/tabs");

var _unstated = require("unstated");

var _global = _interopRequireDefault(require("./state/global"));

var _editor = _interopRequireDefault(require("./state/editor"));

var _state = _interopRequireDefault(require("./tabs/state"));

var _history = _interopRequireDefault(require("./tabs/history"));

var _schema = _interopRequireDefault(require("./tabs/schema"));

var _plugins = _interopRequireDefault(require("./tabs/plugins"));

var _structure = _interopRequireDefault(require("./tabs/structure"));

var _snapshots = _interopRequireDefault(require("./tabs/snapshots"));

var _cssReset = _interopRequireDefault(require("./components/css-reset"));

var _nodePicker = require("./components/node-picker");

var _saveSnapshotButton = _interopRequireDefault(require("./components/save-snapshot-button"));

var _theme = _interopRequireDefault(require("./theme"));

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

var DockContainer = (0, _styled.default)("div")({
  width: "100%",
  height: "100%",
  overflow: "hidden",
  background: _theme.default.mainBg,
  fontFamily: "Helvetica Neue, Calibri Light, Roboto, sans-serif",
  fontSize: "13px"
});
DockContainer.displayName = "DockContainer";
var CloseButton = (0, _styled.default)("button")({
  background: "none",
  border: "none",
  position: "absolute",
  right: 0,
  color: _theme.default.white60,
  fontSize: "18px",
  "&:hover": {
    cursor: "pointer",
    background: _theme.default.white05,
    color: _theme.default.white
  },
  "&:focus": {
    outline: "none"
  }
});
CloseButton.displayName = "CloseButton";

function DevToolsExpanded() {
  return /*#__PURE__*/_react.default.createElement(_unstated.Subscribe, {
    to: [_global.default]
  }, function (globalState) {
    var _globalState$state = globalState.state,
        defaultSize = _globalState$state.defaultSize,
        tabIndex = _globalState$state.tabIndex;
    var toggleDevTools = globalState.toggleDevTools,
        updateBodyMargin = globalState.updateBodyMargin,
        selectTab = globalState.selectTab;
    return /*#__PURE__*/_react.default.createElement(_cssReset.default, null, /*#__PURE__*/_react.default.createElement(_unstated.Subscribe, {
      to: [_editor.default]
    }, function (_ref) {
      var nodePicker = _ref.state.nodePicker,
          deactivatePicker = _ref.deactivatePicker,
          updateNodePickerPossition = _ref.updateNodePickerPossition,
          nodePickerSelect = _ref.nodePickerSelect;
      return /*#__PURE__*/_react.default.createElement(_nodePicker.NodePicker, {
        nodePicker: nodePicker,
        onClose: deactivatePicker,
        onMouseMove: updateNodePickerPossition,
        onSelect: function onSelect(target) {
          nodePickerSelect(target);
          selectTab(0); // Switch to the "State" tab.
        }
      });
    }), /*#__PURE__*/_react.default.createElement(_reactDock.default, {
      position: "bottom",
      dimMode: "none",
      isVisible: true,
      defaultSize: defaultSize,
      onSizeChange: updateBodyMargin
    }, function () {
      return /*#__PURE__*/_react.default.createElement(DockContainer, null, /*#__PURE__*/_react.default.createElement(CloseButton, {
        onClick: toggleDevTools
      }, "\xD7"), /*#__PURE__*/_react.default.createElement(_unstated.Subscribe, {
        to: [_editor.default]
      }, function (_ref2) {
        var nodePicker = _ref2.state.nodePicker,
            deactivatePicker = _ref2.deactivatePicker,
            activatePicker = _ref2.activatePicker;
        return /*#__PURE__*/_react.default.createElement(_nodePicker.NodePickerTrigger, {
          onClick: nodePicker.active ? deactivatePicker : activatePicker,
          isActive: nodePicker.active
        });
      }), /*#__PURE__*/_react.default.createElement(_unstated.Subscribe, {
        to: [_editor.default]
      }, function (_ref3) {
        var saveSnapshot = _ref3.saveSnapshot;
        return /*#__PURE__*/_react.default.createElement(_saveSnapshotButton.default, {
          onClick: saveSnapshot
        }, "Save Snapshot");
      }), /*#__PURE__*/_react.default.createElement(_tabs.Tabs, {
        onSelect: selectTab,
        selectedIndex: tabIndex
      }, /*#__PURE__*/_react.default.createElement(_tabs.TabList, null, /*#__PURE__*/_react.default.createElement(_tabs.Tab, {
        index: "state"
      }, "State"), /*#__PURE__*/_react.default.createElement(_tabs.Tab, {
        index: "history"
      }, "History"), /*#__PURE__*/_react.default.createElement(_tabs.Tab, {
        index: "plugins"
      }, "Plugins"), /*#__PURE__*/_react.default.createElement(_tabs.Tab, {
        index: "schema"
      }, "Schema"), /*#__PURE__*/_react.default.createElement(_tabs.Tab, {
        index: "structure"
      }, "Structure"), /*#__PURE__*/_react.default.createElement(_tabs.Tab, {
        index: "snapshots"
      }, "Snapshots")), /*#__PURE__*/_react.default.createElement(_tabs.TabPanel, null, function (_ref4) {
        var index = _ref4.index;

        switch (index) {
          case "state":
            return /*#__PURE__*/_react.default.createElement(_state.default, null);

          case "history":
            return /*#__PURE__*/_react.default.createElement(_history.default, null);

          case "plugins":
            return /*#__PURE__*/_react.default.createElement(_plugins.default, null);

          case "schema":
            return /*#__PURE__*/_react.default.createElement(_schema.default, null);

          case "structure":
            return /*#__PURE__*/_react.default.createElement(_structure.default, null);

          case "snapshots":
            return /*#__PURE__*/_react.default.createElement(_snapshots.default, null);

          default:
            return /*#__PURE__*/_react.default.createElement(_state.default, null);
        }
      })));
    }));
  });
}
},{"react":"../node_modules/react/index.js","react-dock":"../node_modules/react-dock/lib/index.js","@emotion/styled":"../node_modules/@emotion/styled/dist/styled.browser.esm.js","./components/tabs":"../src/components/tabs.js","unstated":"../node_modules/unstated/lib/unstated.es.js","./state/global":"../src/state/global.js","./state/editor":"../src/state/editor.js","./tabs/state":"../src/tabs/state.js","./tabs/history":"../src/tabs/history.js","./tabs/schema":"../src/tabs/schema.js","./tabs/plugins":"../src/tabs/plugins.js","./tabs/structure":"../src/tabs/structure.js","./tabs/snapshots":"../src/tabs/snapshots.js","./components/css-reset":"../src/components/css-reset.js","./components/node-picker":"../src/components/node-picker/index.js","./components/save-snapshot-button":"../src/components/save-snapshot-button.js","./theme":"../src/theme.js"}],"../src/dev-tools.js":[function(require,module,exports) {
"use strict";

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

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

var _unstated = require("unstated");

var _global = _interopRequireDefault(require("./state/global"));

var _devToolsCollapsed = _interopRequireDefault(require("./dev-tools-collapsed"));

var _devToolsExpanded = _interopRequireDefault(require("./dev-tools-expanded"));

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

function DevTools() {
  return /*#__PURE__*/_react.default.createElement(_unstated.Subscribe, {
    to: [_global.default]
  }, function (_ref) {
    var state = _ref.state,
        toggleDevTools = _ref.toggleDevTools;
    return state.opened ? /*#__PURE__*/_react.default.createElement(_devToolsExpanded.default, null) : /*#__PURE__*/_react.default.createElement(_devToolsCollapsed.default, {
      onClick: toggleDevTools
    });
  });
}
},{"react":"../node_modules/react/index.js","unstated":"../node_modules/unstated/lib/unstated.es.js","./state/global":"../src/state/global.js","./dev-tools-collapsed":"../src/dev-tools-collapsed.js","./dev-tools-expanded":"../src/dev-tools-expanded.js"}],"../src/index.js":[function(require,module,exports) {
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.applyDevTools = applyDevTools;
exports.default = void 0;

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

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

var _unstated = require("unstated");

var _devTools = _interopRequireDefault(require("./dev-tools"));

var _editor = _interopRequireDefault(require("./state/editor"));

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

var DEVTOOLS_CLASS_NAME = "__prosemirror-dev-tools__";

function createPlace() {
  var place = document.querySelector(".".concat(DEVTOOLS_CLASS_NAME));

  if (!place) {
    place = document.createElement("div");
    place.className = DEVTOOLS_CLASS_NAME;
    document.body.appendChild(place);
  } else {
    _reactDom.default.unmountComponentAtNode(place);

    place.innerHTML = "";
  }

  return place;
}

function applyDevTools(editorView, props) {
  var place = createPlace();
  var editorState = new _editor.default(editorView, props);

  _reactDom.default.render( /*#__PURE__*/_react.default.createElement(_unstated.Provider, {
    inject: [editorState]
  }, /*#__PURE__*/_react.default.createElement(_devTools.default, null)), place);
}

var _default = applyDevTools;
exports.default = _default;
},{"react":"../node_modules/react/index.js","react-dom":"../node_modules/react-dom/index.js","unstated":"../node_modules/unstated/lib/unstated.es.js","./dev-tools":"../src/dev-tools.js","./state/editor":"../src/state/editor.js"}],"../node_modules/parcel/src/builtins/css-loader.js":[function(require,module,exports) {
var bundle = require('./bundle-url');

function updateLink(link) {
  var newLink = link.cloneNode();

  newLink.onload = function () {
    link.remove();
  };

  newLink.href = link.href.split('?')[0] + '?' + Date.now();
  link.parentNode.insertBefore(newLink, link.nextSibling);
}

var cssTimeout = null;

function reloadCSS() {
  if (cssTimeout) {
    return;
  }

  cssTimeout = setTimeout(function () {
    var links = document.querySelectorAll('link[rel="stylesheet"]');

    for (var i = 0; i < links.length; i++) {
      if (bundle.getBaseURL(links[i].href) === bundle.getBundleURL()) {
        updateLink(links[i]);
      }
    }

    cssTimeout = null;
  }, 50);
}

module.exports = reloadCSS;
},{"./bundle-url":"../node_modules/parcel/src/builtins/bundle-url.js"}],"editor.css":[function(require,module,exports) {
var reloadCSS = require('_css_loader');

module.hot.dispose(reloadCSS);
module.hot.accept(reloadCSS);
},{"_css_loader":"../node_modules/parcel/src/builtins/css-loader.js"}],"../node_modules/prosemirror-view/dist/index.es.js":[function(require,module,exports) {
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.__endComposition = endComposition;
exports.__parseFromClipboard = parseFromClipboard;
exports.__serializeForClipboard = serializeForClipboard;
exports.EditorView = exports.DecorationSet = exports.Decoration = void 0;

var _prosemirrorState = require("prosemirror-state");

var _prosemirrorModel = require("prosemirror-model");

var _prosemirrorTransform = require("prosemirror-transform");

var result = {};

if (typeof navigator != "undefined" && typeof document != "undefined") {
  var ie_edge = /Edge\/(\d+)/.exec(navigator.userAgent);
  var ie_upto10 = /MSIE \d/.test(navigator.userAgent);
  var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);
  result.mac = /Mac/.test(navigator.platform);
  var ie = result.ie = !!(ie_upto10 || ie_11up || ie_edge);
  result.ie_version = ie_upto10 ? document.documentMode || 6 : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : null;
  result.gecko = !ie && /gecko\/(\d+)/i.test(navigator.userAgent);
  result.gecko_version = result.gecko && +(/Firefox\/(\d+)/.exec(navigator.userAgent) || [0, 0])[1];
  var chrome = !ie && /Chrome\/(\d+)/.exec(navigator.userAgent);
  result.chrome = !!chrome;
  result.chrome_version = chrome && +chrome[1];
  result.ios = !ie && /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent);
  result.android = /Android \d/.test(navigator.userAgent);
  result.webkit = "webkitFontSmoothing" in document.documentElement.style;
  result.safari = /Apple Computer/.test(navigator.vendor);
  result.webkit_version = result.webkit && +(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent) || [0, 0])[1];
}

var domIndex = function (node) {
  for (var index = 0;; index++) {
    node = node.previousSibling;

    if (!node) {
      return index;
    }
  }
};

var parentNode = function (node) {
  var parent = node.parentNode;
  return parent && parent.nodeType == 11 ? parent.host : parent;
};

var textRange = function (node, from, to) {
  var range = document.createRange();
  range.setEnd(node, to == null ? node.nodeValue.length : to);
  range.setStart(node, from || 0);
  return range;
}; // Scans forward and backward through DOM positions equivalent to the
// given one to see if the two are in the same place (i.e. after a
// text node vs at the end of that text node)


var isEquivalentPosition = function (node, off, targetNode, targetOff) {
  return targetNode && (scanFor(node, off, targetNode, targetOff, -1) || scanFor(node, off, targetNode, targetOff, 1));
};

var atomElements = /^(img|br|input|textarea|hr)$/i;

function scanFor(node, off, targetNode, targetOff, dir) {
  for (;;) {
    if (node == targetNode && off == targetOff) {
      return true;
    }

    if (off == (dir < 0 ? 0 : nodeSize(node))) {
      var parent = node.parentNode;

      if (parent.nodeType != 1 || hasBlockDesc(node) || atomElements.test(node.nodeName) || node.contentEditable == "false") {
        return false;
      }

      off = domIndex(node) + (dir < 0 ? 0 : 1);
      node = parent;
    } else if (node.nodeType == 1) {
      node = node.childNodes[off + (dir < 0 ? -1 : 0)];

      if (node.contentEditable == "false") {
        return false;
      }

      off = dir < 0 ? nodeSize(node) : 0;
    } else {
      return false;
    }
  }
}

function nodeSize(node) {
  return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length;
}

function isOnEdge(node, offset, parent) {
  for (var atStart = offset == 0, atEnd = offset == nodeSize(node); atStart || atEnd;) {
    if (node == parent) {
      return true;
    }

    var index = domIndex(node);
    node = node.parentNode;

    if (!node) {
      return false;
    }

    atStart = atStart && index == 0;
    atEnd = atEnd && index == nodeSize(node);
  }
}

function hasBlockDesc(dom) {
  var desc;

  for (var cur = dom; cur; cur = cur.parentNode) {
    if (desc = cur.pmViewDesc) {
      break;
    }
  }

  return desc && desc.node && desc.node.isBlock && (desc.dom == dom || desc.contentDOM == dom);
} // Work around Chrome issue https://bugs.chromium.org/p/chromium/issues/detail?id=447523
// (isCollapsed inappropriately returns true in shadow dom)


var selectionCollapsed = function (domSel) {
  var collapsed = domSel.isCollapsed;

  if (collapsed && result.chrome && domSel.rangeCount && !domSel.getRangeAt(0).collapsed) {
    collapsed = false;
  }

  return collapsed;
};

function keyEvent(keyCode, key) {
  var event = document.createEvent("Event");
  event.initEvent("keydown", true, true);
  event.keyCode = keyCode;
  event.key = event.code = key;
  return event;
}

function windowRect(doc) {
  return {
    left: 0,
    right: doc.documentElement.clientWidth,
    top: 0,
    bottom: doc.documentElement.clientHeight
  };
}

function getSide(value, side) {
  return typeof value == "number" ? value : value[side];
}

function clientRect(node) {
  var rect = node.getBoundingClientRect(); // Make sure scrollbar width isn't included in the rectangle

  return {
    left: rect.left,
    right: rect.left + node.clientWidth,
    top: rect.top,
    bottom: rect.top + node.clientHeight
  };
}

function scrollRectIntoView(view, rect, startDOM) {
  var scrollThreshold = view.someProp("scrollThreshold") || 0,
      scrollMargin = view.someProp("scrollMargin") || 5;
  var doc = view.dom.ownerDocument;

  for (var parent = startDOM || view.dom;; parent = parentNode(parent)) {
    if (!parent) {
      break;
    }

    if (parent.nodeType != 1) {
      continue;
    }

    var atTop = parent == doc.body || parent.nodeType != 1;
    var bounding = atTop ? windowRect(doc) : clientRect(parent);
    var moveX = 0,
        moveY = 0;

    if (rect.top < bounding.top + getSide(scrollThreshold, "top")) {
      moveY = -(bounding.top - rect.top + getSide(scrollMargin, "top"));
    } else if (rect.bottom > bounding.bottom - getSide(scrollThreshold, "bottom")) {
      moveY = rect.bottom - bounding.bottom + getSide(scrollMargin, "bottom");
    }

    if (rect.left < bounding.left + getSide(scrollThreshold, "left")) {
      moveX = -(bounding.left - rect.left + getSide(scrollMargin, "left"));
    } else if (rect.right > bounding.right - getSide(scrollThreshold, "right")) {
      moveX = rect.right - bounding.right + getSide(scrollMargin, "right");
    }

    if (moveX || moveY) {
      if (atTop) {
        doc.defaultView.scrollBy(moveX, moveY);
      } else {
        var startX = parent.scrollLeft,
            startY = parent.scrollTop;

        if (moveY) {
          parent.scrollTop += moveY;
        }

        if (moveX) {
          parent.scrollLeft += moveX;
        }

        var dX = parent.scrollLeft - startX,
            dY = parent.scrollTop - startY;
        rect = {
          left: rect.left - dX,
          top: rect.top - dY,
          right: rect.right - dX,
          bottom: rect.bottom - dY
        };
      }
    }

    if (atTop) {
      break;
    }
  }
} // Store the scroll position of the editor's parent nodes, along with
// the top position of an element near the top of the editor, which
// will be used to make sure the visible viewport remains stable even
// when the size of the content above changes.


function storeScrollPos(view) {
  var rect = view.dom.getBoundingClientRect(),
      startY = Math.max(0, rect.top);
  var refDOM, refTop;

  for (var x = (rect.left + rect.right) / 2, y = startY + 1; y < Math.min(innerHeight, rect.bottom); y += 5) {
    var dom = view.root.elementFromPoint(x, y);

    if (dom == view.dom || !view.dom.contains(dom)) {
      continue;
    }

    var localRect = dom.getBoundingClientRect();

    if (localRect.top >= startY - 20) {
      refDOM = dom;
      refTop = localRect.top;
      break;
    }
  }

  return {
    refDOM: refDOM,
    refTop: refTop,
    stack: scrollStack(view.dom)
  };
}

function scrollStack(dom) {
  var stack = [],
      doc = dom.ownerDocument;

  for (; dom; dom = parentNode(dom)) {
    stack.push({
      dom: dom,
      top: dom.scrollTop,
      left: dom.scrollLeft
    });

    if (dom == doc) {
      break;
    }
  }

  return stack;
} // Reset the scroll position of the editor's parent nodes to that what
// it was before, when storeScrollPos was called.


function resetScrollPos(ref) {
  var refDOM = ref.refDOM;
  var refTop = ref.refTop;
  var stack = ref.stack;
  var newRefTop = refDOM ? refDOM.getBoundingClientRect().top : 0;
  restoreScrollStack(stack, newRefTop == 0 ? 0 : newRefTop - refTop);
}

function restoreScrollStack(stack, dTop) {
  for (var i = 0; i < stack.length; i++) {
    var ref = stack[i];
    var dom = ref.dom;
    var top = ref.top;
    var left = ref.left;

    if (dom.scrollTop != top + dTop) {
      dom.scrollTop = top + dTop;
    }

    if (dom.scrollLeft != left) {
      dom.scrollLeft = left;
    }
  }
}

var preventScrollSupported = null; // Feature-detects support for .focus({preventScroll: true}), and uses
// a fallback kludge when not supported.

function focusPreventScroll(dom) {
  if (dom.setActive) {
    return dom.setActive();
  } // in IE


  if (preventScrollSupported) {
    return dom.focus(preventScrollSupported);
  }

  var stored = scrollStack(dom);
  dom.focus(preventScrollSupported == null ? {
    get preventScroll() {
      preventScrollSupported = {
        preventScroll: true
      };
      return true;
    }

  } : undefined);

  if (!preventScrollSupported) {
    preventScrollSupported = false;
    restoreScrollStack(stored, 0);
  }
}

function findOffsetInNode(node, coords) {
  var closest,
      dxClosest = 2e8,
      coordsClosest,
      offset = 0;
  var rowBot = coords.top,
      rowTop = coords.top;

  for (var child = node.firstChild, childIndex = 0; child; child = child.nextSibling, childIndex++) {
    var rects = void 0;

    if (child.nodeType == 1) {
      rects = child.getClientRects();
    } else if (child.nodeType == 3) {
      rects = textRange(child).getClientRects();
    } else {
      continue;
    }

    for (var i = 0; i < rects.length; i++) {
      var rect = rects[i];

      if (rect.top <= rowBot && rect.bottom >= rowTop) {
        rowBot = Math.max(rect.bottom, rowBot);
        rowTop = Math.min(rect.top, rowTop);
        var dx = rect.left > coords.left ? rect.left - coords.left : rect.right < coords.left ? coords.left - rect.right : 0;

        if (dx < dxClosest) {
          closest = child;
          dxClosest = dx;
          coordsClosest = dx && closest.nodeType == 3 ? {
            left: rect.right < coords.left ? rect.right : rect.left,
            top: coords.top
          } : coords;

          if (child.nodeType == 1 && dx) {
            offset = childIndex + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0);
          }

          continue;
        }
      }

      if (!closest && (coords.left >= rect.right && coords.top >= rect.top || coords.left >= rect.left && coords.top >= rect.bottom)) {
        offset = childIndex + 1;
      }
    }
  }

  if (closest && closest.nodeType == 3) {
    return findOffsetInText(closest, coordsClosest);
  }

  if (!closest || dxClosest && closest.nodeType == 1) {
    return {
      node: node,
      offset: offset
    };
  }

  return findOffsetInNode(closest, coordsClosest);
}

function findOffsetInText(node, coords) {
  var len = node.nodeValue.length;
  var range = document.createRange();

  for (var i = 0; i < len; i++) {
    range.setEnd(node, i + 1);
    range.setStart(node, i);
    var rect = singleRect(range, 1);

    if (rect.top == rect.bottom) {
      continue;
    }

    if (inRect(coords, rect)) {
      return {
        node: node,
        offset: i + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0)
      };
    }
  }

  return {
    node: node,
    offset: 0
  };
}

function inRect(coords, rect) {
  return coords.left >= rect.left - 1 && coords.left <= rect.right + 1 && coords.top >= rect.top - 1 && coords.top <= rect.bottom + 1;
}

function targetKludge(dom, coords) {
  var parent = dom.parentNode;

  if (parent && /^li$/i.test(parent.nodeName) && coords.left < dom.getBoundingClientRect().left) {
    return parent;
  }

  return dom;
}

function posFromElement(view, elt, coords) {
  var ref = findOffsetInNode(elt, coords);
  var node = ref.node;
  var offset = ref.offset;
  var bias = -1;

  if (node.nodeType == 1 && !node.firstChild) {
    var rect = node.getBoundingClientRect();
    bias = rect.left != rect.right && coords.left > (rect.left + rect.right) / 2 ? 1 : -1;
  }

  return view.docView.posFromDOM(node, offset, bias);
}

function posFromCaret(view, node, offset, coords) {
  // Browser (in caretPosition/RangeFromPoint) will agressively
  // normalize towards nearby inline nodes. Since we are interested in
  // positions between block nodes too, we first walk up the hierarchy
  // of nodes to see if there are block nodes that the coordinates
  // fall outside of. If so, we take the position before/after that
  // block. If not, we call `posFromDOM` on the raw node/offset.
  var outside = -1;

  for (var cur = node;;) {
    if (cur == view.dom) {
      break;
    }

    var desc = view.docView.nearestDesc(cur, true);

    if (!desc) {
      return null;
    }

    if (desc.node.isBlock && desc.parent) {
      var rect = desc.dom.getBoundingClientRect();

      if (rect.left > coords.left || rect.top > coords.top) {
        outside = desc.posBefore;
      } else if (rect.right < coords.left || rect.bottom < coords.top) {
        outside = desc.posAfter;
      } else {
        break;
      }
    }

    cur = desc.dom.parentNode;
  }

  return outside > -1 ? outside : view.docView.posFromDOM(node, offset);
}

function elementFromPoint(element, coords, box) {
  var len = element.childNodes.length;

  if (len && box.top < box.bottom) {
    for (var startI = Math.max(0, Math.min(len - 1, Math.floor(len * (coords.top - box.top) / (box.bottom - box.top)) - 2)), i = startI;;) {
      var child = element.childNodes[i];

      if (child.nodeType == 1) {
        var rects = child.getClientRects();

        for (var j = 0; j < rects.length; j++) {
          var rect = rects[j];

          if (inRect(coords, rect)) {
            return elementFromPoint(child, coords, rect);
          }
        }
      }

      if ((i = (i + 1) % len) == startI) {
        break;
      }
    }
  }

  return element;
} // Given an x,y position on the editor, get the position in the document.


function posAtCoords(view, coords) {
  var assign, assign$1;
  var root = view.root,
      node,
      offset;

  if (root.caretPositionFromPoint) {
    try {
      // Firefox throws for this call in hard-to-predict circumstances (#994)
      var pos$1 = root.caretPositionFromPoint(coords.left, coords.top);

      if (pos$1) {
        assign = pos$1, node = assign.offsetNode, offset = assign.offset;
      }
    } catch (_) {}
  }

  if (!node && root.caretRangeFromPoint) {
    var range = root.caretRangeFromPoint(coords.left, coords.top);

    if (range) {
      assign$1 = range, node = assign$1.startContainer, offset = assign$1.startOffset;
    }
  }

  var elt = root.elementFromPoint(coords.left, coords.top + 1),
      pos; // Safari's caretRangeFromPoint returns nonsense when on a draggable element

  if (result.safari && elt.draggable) {
    node = offset = null;
  }

  if (!elt || !view.dom.contains(elt.nodeType != 1 ? elt.parentNode : elt)) {
    var box = view.dom.getBoundingClientRect();

    if (!inRect(coords, box)) {
      return null;
    }

    elt = elementFromPoint(view.dom, coords, box);

    if (!elt) {
      return null;
    }
  }

  elt = targetKludge(elt, coords);

  if (node) {
    if (result.gecko && node.nodeType == 1) {
      // Firefox will sometimes return offsets into <input> nodes, which
      // have no actual children, from caretPositionFromPoint (#953)
      offset = Math.min(offset, node.childNodes.length); // It'll also move the returned position before image nodes,
      // even if those are behind it.

      if (offset < node.childNodes.length) {
        var next = node.childNodes[offset],
            box$1;

        if (next.nodeName == "IMG" && (box$1 = next.getBoundingClientRect()).right <= coords.left && box$1.bottom > coords.top) {
          offset++;
        }
      }
    } // Suspiciously specific kludge to work around caret*FromPoint
    // never returning a position at the end of the document


    if (node == view.dom && offset == node.childNodes.length - 1 && node.lastChild.nodeType == 1 && coords.top > node.lastChild.getBoundingClientRect().bottom) {
      pos = view.state.doc.content.size;
    } // Ignore positions directly after a BR, since caret*FromPoint
    // 'round up' positions that would be more accurately placed
    // before the BR node.
    else if (offset == 0 || node.nodeType != 1 || node.childNodes[offset - 1].nodeName != "BR") {
        pos = posFromCaret(view, node, offset, coords);
      }
  }

  if (pos == null) {
    pos = posFromElement(view, elt, coords);
  }

  var desc = view.docView.nearestDesc(elt, true);
  return {
    pos: pos,
    inside: desc ? desc.posAtStart - desc.border : -1
  };
}

function singleRect(object, bias) {
  var rects = object.getClientRects();
  return !rects.length ? object.getBoundingClientRect() : rects[bias < 0 ? 0 : rects.length - 1];
} // : (EditorView, number) → {left: number, top: number, right: number, bottom: number}
// Given a position in the document model, get a bounding box of the
// character at that position, relative to the window.


function coordsAtPos(view, pos) {
  var ref = view.docView.domFromPos(pos);
  var node = ref.node;
  var offset = ref.offset; // These browsers support querying empty text ranges

  if (node.nodeType == 3 && (result.webkit || result.gecko)) {
    var rect = singleRect(textRange(node, offset, offset), 0); // Firefox returns bad results (the position before the space)
    // when querying a position directly after line-broken
    // whitespace. Detect this situation and and kludge around it

    if (result.gecko && offset && /\s/.test(node.nodeValue[offset - 1]) && offset < node.nodeValue.length) {
      var rectBefore = singleRect(textRange(node, offset - 1, offset - 1), -1);

      if (rectBefore.top == rect.top) {
        var rectAfter = singleRect(textRange(node, offset, offset + 1), -1);

        if (rectAfter.top != rect.top) {
          return flattenV(rectAfter, rectAfter.left < rectBefore.left);
        }
      }
    }

    return rect;
  }

  if (node.nodeType == 1 && !view.state.doc.resolve(pos).parent.inlineContent) {
    // Return a horizontal line in block context
    var top = true,
        rect$1;

    if (offset < node.childNodes.length) {
      var after = node.childNodes[offset];

      if (after.nodeType == 1) {
        rect$1 = after.getBoundingClientRect();
      }
    }

    if (!rect$1 && offset) {
      var before = node.childNodes[offset - 1];

      if (before.nodeType == 1) {
        rect$1 = before.getBoundingClientRect();
        top = false;
      }
    }

    return flattenH(rect$1 || node.getBoundingClientRect(), top);
  } // Not Firefox/Chrome, or not in a text node, so we have to use
  // actual element/character rectangles to get a solution (this part
  // is not very bidi-safe)
  //
  // Try the left side first, fall back to the right one if that
  // doesn't work.


  for (var dir = -1; dir < 2; dir += 2) {
    if (dir < 0 && offset) {
      var prev = void 0,
          target = node.nodeType == 3 ? textRange(node, offset - 1, offset) : (prev = node.childNodes[offset - 1]).nodeType == 3 ? textRange(prev) : prev.nodeType == 1 && prev.nodeName != "BR" ? prev : null; // BR nodes tend to only return the rectangle before them

      if (target) {
        var rect$2 = singleRect(target, 1);

        if (rect$2.top < rect$2.bottom) {
          return flattenV(rect$2, false);
        }
      }
    } else if (dir > 0 && offset < nodeSize(node)) {
      var next = void 0,
          target$1 = node.nodeType == 3 ? textRange(node, offset, offset + 1) : (next = node.childNodes[offset]).nodeType == 3 ? textRange(next) : next.nodeType == 1 ? next : null;

      if (target$1) {
        var rect$3 = singleRect(target$1, -1);

        if (rect$3.top < rect$3.bottom) {
          return flattenV(rect$3, true);
        }
      }
    }
  } // All else failed, just try to get a rectangle for the target node


  return flattenV(singleRect(node.nodeType == 3 ? textRange(node) : node, 0), false);
}

function flattenV(rect, left) {
  if (rect.width == 0) {
    return rect;
  }

  var x = left ? rect.left : rect.right;
  return {
    top: rect.top,
    bottom: rect.bottom,
    left: x,
    right: x
  };
}

function flattenH(rect, top) {
  if (rect.height == 0) {
    return rect;
  }

  var y = top ? rect.top : rect.bottom;
  return {
    top: y,
    bottom: y,
    left: rect.left,
    right: rect.right
  };
}

function withFlushedState(view, state, f) {
  var viewState = view.state,
      active = view.root.activeElement;

  if (viewState != state) {
    view.updateState(state);
  }

  if (active != view.dom) {
    view.focus();
  }

  try {
    return f();
  } finally {
    if (viewState != state) {
      view.updateState(viewState);
    }

    if (active != view.dom && active) {
      active.focus();
    }
  }
} // : (EditorView, number, number)
// Whether vertical position motion in a given direction
// from a position would leave a text block.


function endOfTextblockVertical(view, state, dir) {
  var sel = state.selection;
  var $pos = dir == "up" ? sel.$anchor.min(sel.$head) : sel.$anchor.max(sel.$head);
  return withFlushedState(view, state, function () {
    var ref = view.docView.domFromPos($pos.pos);
    var dom = ref.node;

    for (;;) {
      var nearest = view.docView.nearestDesc(dom, true);

      if (!nearest) {
        break;
      }

      if (nearest.node.isBlock) {
        dom = nearest.dom;
        break;
      }

      dom = nearest.dom.parentNode;
    }

    var coords = coordsAtPos(view, $pos.pos);

    for (var child = dom.firstChild; child; child = child.nextSibling) {
      var boxes = void 0;

      if (child.nodeType == 1) {
        boxes = child.getClientRects();
      } else if (child.nodeType == 3) {
        boxes = textRange(child, 0, child.nodeValue.length).getClientRects();
      } else {
        continue;
      }

      for (var i = 0; i < boxes.length; i++) {
        var box = boxes[i];

        if (box.bottom > box.top && (dir == "up" ? box.bottom < coords.top + 1 : box.top > coords.bottom - 1)) {
          return false;
        }
      }
    }

    return true;
  });
}

var maybeRTL = /[\u0590-\u08ac]/;

function endOfTextblockHorizontal(view, state, dir) {
  var ref = state.selection;
  var $head = ref.$head;

  if (!$head.parent.isTextblock) {
    return false;
  }

  var offset = $head.parentOffset,
      atStart = !offset,
      atEnd = offset == $head.parent.content.size;
  var sel = getSelection(); // If the textblock is all LTR, or the browser doesn't support
  // Selection.modify (Edge), fall back to a primitive approach

  if (!maybeRTL.test($head.parent.textContent) || !sel.modify) {
    return dir == "left" || dir == "backward" ? atStart : atEnd;
  }

  return withFlushedState(view, state, function () {
    // This is a huge hack, but appears to be the best we can
    // currently do: use `Selection.modify` to move the selection by
    // one character, and see if that moves the cursor out of the
    // textblock (or doesn't move it at all, when at the start/end of
    // the document).
    var oldRange = sel.getRangeAt(0),
        oldNode = sel.focusNode,
        oldOff = sel.focusOffset;
    var oldBidiLevel = sel.caretBidiLevel; // Only for Firefox

    sel.modify("move", dir, "character");
    var parentDOM = $head.depth ? view.docView.domAfterPos($head.before()) : view.dom;
    var result = !parentDOM.contains(sel.focusNode.nodeType == 1 ? sel.focusNode : sel.focusNode.parentNode) || oldNode == sel.focusNode && oldOff == sel.focusOffset; // Restore the previous selection

    sel.removeAllRanges();
    sel.addRange(oldRange);

    if (oldBidiLevel != null) {
      sel.caretBidiLevel = oldBidiLevel;
    }

    return result;
  });
}

var cachedState = null,
    cachedDir = null,
    cachedResult = false;

function endOfTextblock(view, state, dir) {
  if (cachedState == state && cachedDir == dir) {
    return cachedResult;
  }

  cachedState = state;
  cachedDir = dir;
  return cachedResult = dir == "up" || dir == "down" ? endOfTextblockVertical(view, state, dir) : endOfTextblockHorizontal(view, state, dir);
} // NodeView:: interface
//
// By default, document nodes are rendered using the result of the
// [`toDOM`](#model.NodeSpec.toDOM) method of their spec, and managed
// entirely by the editor. For some use cases, such as embedded
// node-specific editing interfaces, you want more control over
// the behavior of a node's in-editor representation, and need to
// [define](#view.EditorProps.nodeViews) a custom node view.
//
// Mark views only support `dom` and `contentDOM`, and don't support
// any of the node view methods.
//
// Objects returned as node views must conform to this interface.
//
//   dom:: ?dom.Node
//   The outer DOM node that represents the document node. When not
//   given, the default strategy is used to create a DOM node.
//
//   contentDOM:: ?dom.Node
//   The DOM node that should hold the node's content. Only meaningful
//   if the node view also defines a `dom` property and if its node
//   type is not a leaf node type. When this is present, ProseMirror
//   will take care of rendering the node's children into it. When it
//   is not present, the node view itself is responsible for rendering
//   (or deciding not to render) its child nodes.
//
//   update:: ?(node: Node, decorations: [Decoration]) → bool
//   When given, this will be called when the view is updating itself.
//   It will be given a node (possibly of a different type), and an
//   array of active decorations (which are automatically drawn, and
//   the node view may ignore if it isn't interested in them), and
//   should return true if it was able to update to that node, and
//   false otherwise. If the node view has a `contentDOM` property (or
//   no `dom` property), updating its child nodes will be handled by
//   ProseMirror.
//
//   selectNode:: ?()
//   Can be used to override the way the node's selected status (as a
//   node selection) is displayed.
//
//   deselectNode:: ?()
//   When defining a `selectNode` method, you should also provide a
//   `deselectNode` method to remove the effect again.
//
//   setSelection:: ?(anchor: number, head: number, root: dom.Document)
//   This will be called to handle setting the selection inside the
//   node. The `anchor` and `head` positions are relative to the start
//   of the node. By default, a DOM selection will be created between
//   the DOM positions corresponding to those positions, but if you
//   override it you can do something else.
//
//   stopEvent:: ?(event: dom.Event) → bool
//   Can be used to prevent the editor view from trying to handle some
//   or all DOM events that bubble up from the node view. Events for
//   which this returns true are not handled by the editor.
//
//   ignoreMutation:: ?(dom.MutationRecord) → bool
//   Called when a DOM
//   [mutation](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver)
//   or a selection change happens within the view. When the change is
//   a selection change, the record will have a `type` property of
//   `"selection"` (which doesn't occur for native mutation records).
//   Return false if the editor should re-read the selection or
//   re-parse the range around the mutation, true if it can safely be
//   ignored.
//
//   destroy:: ?()
//   Called when the node view is removed from the editor or the whole
//   editor is destroyed.
// View descriptions are data structures that describe the DOM that is
// used to represent the editor's content. They are used for:
//
// - Incremental redrawing when the document changes
//
// - Figuring out what part of the document a given DOM position
//   corresponds to
//
// - Wiring in custom implementations of the editing interface for a
//   given node
//
// They form a doubly-linked mutable tree, starting at `view.docView`.


var NOT_DIRTY = 0,
    CHILD_DIRTY = 1,
    CONTENT_DIRTY = 2,
    NODE_DIRTY = 3; // Superclass for the various kinds of descriptions. Defines their
// basic structure and shared methods.

var ViewDesc = function ViewDesc(parent, children, dom, contentDOM) {
  this.parent = parent;
  this.children = children;
  this.dom = dom; // An expando property on the DOM node provides a link back to its
  // description.

  dom.pmViewDesc = this; // This is the node that holds the child views. It may be null for
  // descs that don't have children.

  this.contentDOM = contentDOM;
  this.dirty = NOT_DIRTY;
};

var prototypeAccessors = {
  beforePosition: {
    configurable: true
  },
  size: {
    configurable: true
  },
  border: {
    configurable: true
  },
  posBefore: {
    configurable: true
  },
  posAtStart: {
    configurable: true
  },
  posAfter: {
    configurable: true
  },
  posAtEnd: {
    configurable: true
  },
  contentLost: {
    configurable: true
  }
}; // Used to check whether a given description corresponds to a
// widget/mark/node.

ViewDesc.prototype.matchesWidget = function matchesWidget() {
  return false;
};

ViewDesc.prototype.matchesMark = function matchesMark() {
  return false;
};

ViewDesc.prototype.matchesNode = function matchesNode() {
  return false;
};

ViewDesc.prototype.matchesHack = function matchesHack() {
  return false;
};

prototypeAccessors.beforePosition.get = function () {
  return false;
}; // : () → ?ParseRule
// When parsing in-editor content (in domchange.js), we allow
// descriptions to determine the parse rules that should be used to
// parse them.


ViewDesc.prototype.parseRule = function parseRule() {
  return null;
}; // : (dom.Event) → bool
// Used by the editor's event handler to ignore events that come
// from certain descs.


ViewDesc.prototype.stopEvent = function stopEvent() {
  return false;
}; // The size of the content represented by this desc.


prototypeAccessors.size.get = function () {
  var size = 0;

  for (var i = 0; i < this.children.length; i++) {
    size += this.children[i].size;
  }

  return size;
}; // For block nodes, this represents the space taken up by their
// start/end tokens.


prototypeAccessors.border.get = function () {
  return 0;
};

ViewDesc.prototype.destroy = function destroy() {
  this.parent = null;

  if (this.dom.pmViewDesc == this) {
    this.dom.pmViewDesc = null;
  }

  for (var i = 0; i < this.children.length; i++) {
    this.children[i].destroy();
  }
};

ViewDesc.prototype.posBeforeChild = function posBeforeChild(child) {
  for (var i = 0, pos = this.posAtStart; i < this.children.length; i++) {
    var cur = this.children[i];

    if (cur == child) {
      return pos;
    }

    pos += cur.size;
  }
};

prototypeAccessors.posBefore.get = function () {
  return this.parent.posBeforeChild(this);
};

prototypeAccessors.posAtStart.get = function () {
  return this.parent ? this.parent.posBeforeChild(this) + this.border : 0;
};

prototypeAccessors.posAfter.get = function () {
  return this.posBefore + this.size;
};

prototypeAccessors.posAtEnd.get = function () {
  return this.posAtStart + this.size - 2 * this.border;
}; // : (dom.Node, number, ?number) → number


ViewDesc.prototype.localPosFromDOM = function localPosFromDOM(dom, offset, bias) {
  // If the DOM position is in the content, use the child desc after
  // it to figure out a position.
  if (this.contentDOM && this.contentDOM.contains(dom.nodeType == 1 ? dom : dom.parentNode)) {
    if (bias < 0) {
      var domBefore, desc;

      if (dom == this.contentDOM) {
        domBefore = dom.childNodes[offset - 1];
      } else {
        while (dom.parentNode != this.contentDOM) {
          dom = dom.parentNode;
        }

        domBefore = dom.previousSibling;
      }

      while (domBefore && !((desc = domBefore.pmViewDesc) && desc.parent == this)) {
        domBefore = domBefore.previousSibling;
      }

      return domBefore ? this.posBeforeChild(desc) + desc.size : this.posAtStart;
    } else {
      var domAfter, desc$1;

      if (dom == this.contentDOM) {
        domAfter = dom.childNodes[offset];
      } else {
        while (dom.parentNode != this.contentDOM) {
          dom = dom.parentNode;
        }

        domAfter = dom.nextSibling;
      }

      while (domAfter && !((desc$1 = domAfter.pmViewDesc) && desc$1.parent == this)) {
        domAfter = domAfter.nextSibling;
      }

      return domAfter ? this.posBeforeChild(desc$1) : this.posAtEnd;
    }
  } // Otherwise, use various heuristics, falling back on the bias
  // parameter, to determine whether to return the position at the
  // start or at the end of this view desc.


  var atEnd;

  if (this.contentDOM && this.contentDOM != this.dom && this.dom.contains(this.contentDOM)) {
    atEnd = dom.compareDocumentPosition(this.contentDOM) & 2;
  } else if (this.dom.firstChild) {
    if (offset == 0) {
      for (var search = dom;; search = search.parentNode) {
        if (search == this.dom) {
          atEnd = false;
          break;
        }

        if (search.parentNode.firstChild != search) {
          break;
        }
      }
    }

    if (atEnd == null && offset == dom.childNodes.length) {
      for (var search$1 = dom;; search$1 = search$1.parentNode) {
        if (search$1 == this.dom) {
          atEnd = true;
          break;
        }

        if (search$1.parentNode.lastChild != search$1) {
          break;
        }
      }
    }
  }

  return (atEnd == null ? bias > 0 : atEnd) ? this.posAtEnd : this.posAtStart;
}; // Scan up the dom finding the first desc that is a descendant of
// this one.


ViewDesc.prototype.nearestDesc = function nearestDesc(dom, onlyNodes) {
  for (var first = true, cur = dom; cur; cur = cur.parentNode) {
    var desc = this.getDesc(cur);

    if (desc && (!onlyNodes || desc.node)) {
      // If dom is outside of this desc's nodeDOM, don't count it.
      if (first && desc.nodeDOM && !(desc.nodeDOM.nodeType == 1 ? desc.nodeDOM.contains(dom.nodeType == 1 ? dom : dom.parentNode) : desc.nodeDOM == dom)) {
        first = false;
      } else {
        return desc;
      }
    }
  }
};

ViewDesc.prototype.getDesc = function getDesc(dom) {
  var desc = dom.pmViewDesc;

  for (var cur = desc; cur; cur = cur.parent) {
    if (cur == this) {
      return desc;
    }
  }
};

ViewDesc.prototype.posFromDOM = function posFromDOM(dom, offset, bias) {
  for (var scan = dom;; scan = scan.parentNode) {
    var desc = this.getDesc(scan);

    if (desc) {
      return desc.localPosFromDOM(dom, offset, bias);
    }
  }
}; // : (number) → ?NodeViewDesc
// Find the desc for the node after the given pos, if any. (When a
// parent node overrode rendering, there might not be one.)


ViewDesc.prototype.descAt = function descAt(pos) {
  for (var i = 0, offset = 0; i < this.children.length; i++) {
    var child = this.children[i],
        end = offset + child.size;

    if (offset == pos && end != offset) {
      while (!child.border && child.children.length) {
        child = child.children[0];
      }

      return child;
    }

    if (pos < end) {
      return child.descAt(pos - offset - child.border);
    }

    offset = end;
  }
}; // : (number) → {node: dom.Node, offset: number}


ViewDesc.prototype.domFromPos = function domFromPos(pos) {
  if (!this.contentDOM) {
    return {
      node: this.dom,
      offset: 0
    };
  }

  for (var offset = 0, i = 0;; i++) {
    if (offset == pos) {
      while (i < this.children.length && (this.children[i].beforePosition || this.children[i].dom.parentNode != this.contentDOM)) {
        i++;
      }

      return {
        node: this.contentDOM,
        offset: i == this.children.length ? this.contentDOM.childNodes.length : domIndex(this.children[i].dom)
      };
    }

    if (i == this.children.length) {
      throw new Error("Invalid position " + pos);
    }

    var child = this.children[i],
        end = offset + child.size;

    if (pos < end) {
      return child.domFromPos(pos - offset - child.border);
    }

    offset = end;
  }
}; // Used to find a DOM range in a single parent for a given changed
// range.


ViewDesc.prototype.parseRange = function parseRange(from, to, base) {
  if (base === void 0) base = 0;

  if (this.children.length == 0) {
    return {
      node: this.contentDOM,
      from: from,
      to: to,
      fromOffset: 0,
      toOffset: this.contentDOM.childNodes.length
    };
  }

  var fromOffset = -1,
      toOffset = -1;

  for (var offset = base, i = 0;; i++) {
    var child = this.children[i],
        end = offset + child.size;

    if (fromOffset == -1 && from <= end) {
      var childBase = offset + child.border; // FIXME maybe descend mark views to parse a narrower range?

      if (from >= childBase && to <= end - child.border && child.node && child.contentDOM && this.contentDOM.contains(child.contentDOM)) {
        return child.parseRange(from, to, childBase);
      }

      from = offset;

      for (var j = i; j > 0; j--) {
        var prev = this.children[j - 1];

        if (prev.size && prev.dom.parentNode == this.contentDOM && !prev.emptyChildAt(1)) {
          fromOffset = domIndex(prev.dom) + 1;
          break;
        }

        from -= prev.size;
      }

      if (fromOffset == -1) {
        fromOffset = 0;
      }
    }

    if (fromOffset > -1 && to <= end) {
      to = end;

      for (var j$1 = i + 1; j$1 < this.children.length; j$1++) {
        var next = this.children[j$1];

        if (next.size && next.dom.parentNode == this.contentDOM && !next.emptyChildAt(-1)) {
          toOffset = domIndex(next.dom);
          break;
        }

        to += next.size;
      }

      if (toOffset == -1) {
        toOffset = this.contentDOM.childNodes.length;
      }

      break;
    }

    offset = end;
  }

  return {
    node: this.contentDOM,
    from: from,
    to: to,
    fromOffset: fromOffset,
    toOffset: toOffset
  };
};

ViewDesc.prototype.emptyChildAt = function emptyChildAt(side) {
  if (this.border || !this.contentDOM || !this.children.length) {
    return false;
  }

  var child = this.children[side < 0 ? 0 : this.children.length - 1];
  return child.size == 0 || child.emptyChildAt(side);
}; // : (number) → dom.Node


ViewDesc.prototype.domAfterPos = function domAfterPos(pos) {
  var ref = this.domFromPos(pos);
  var node = ref.node;
  var offset = ref.offset;

  if (node.nodeType != 1 || offset == node.childNodes.length) {
    throw new RangeError("No node after pos " + pos);
  }

  return node.childNodes[offset];
}; // : (number, number, dom.Document)
// View descs are responsible for setting any selection that falls
// entirely inside of them, so that custom implementations can do
// custom things with the selection. Note that this falls apart when
// a selection starts in such a node and ends in another, in which
// case we just use whatever domFromPos produces as a best effort.


ViewDesc.prototype.setSelection = function setSelection(anchor, head, root, force) {
  // If the selection falls entirely in a child, give it to that child
  var from = Math.min(anchor, head),
      to = Math.max(anchor, head);

  for (var i = 0, offset = 0; i < this.children.length; i++) {
    var child = this.children[i],
        end = offset + child.size;

    if (from > offset && to < end) {
      return child.setSelection(anchor - offset - child.border, head - offset - child.border, root, force);
    }

    offset = end;
  }

  var anchorDOM = this.domFromPos(anchor),
      headDOM = this.domFromPos(head);
  var domSel = root.getSelection();

  if (!force && isEquivalentPosition(anchorDOM.node, anchorDOM.offset, domSel.anchorNode, domSel.anchorOffset) && isEquivalentPosition(headDOM.node, headDOM.offset, domSel.focusNode, domSel.focusOffset)) {
    return;
  } // Selection.extend can be used to create an 'inverted' selection
  // (one where the focus is before the anchor), but not all
  // browsers support it yet.


  var domSelExtended = false;

  if (domSel.extend || anchor == head) {
    domSel.collapse(anchorDOM.node, anchorDOM.offset);

    try {
      if (anchor != head) {
        domSel.extend(headDOM.node, headDOM.offset);
      }

      domSelExtended = true;
    } catch (err) {
      // In some cases with Chrome the selection is empty after calling
      // collapse, even when it should be valid. This appears to be a bug, but
      // it is difficult to isolate. If this happens fallback to the old path
      // without using extend.
      if (!(err instanceof DOMException)) {
        throw err;
      }
    }
  }

  if (!domSelExtended) {
    if (anchor > head) {
      var tmp = anchorDOM;
      anchorDOM = headDOM;
      headDOM = tmp;
    }

    var range = document.createRange();
    range.setEnd(headDOM.node, headDOM.offset);
    range.setStart(anchorDOM.node, anchorDOM.offset);
    domSel.removeAllRanges();
    domSel.addRange(range);
  }
}; // : (dom.MutationRecord) → bool


ViewDesc.prototype.ignoreMutation = function ignoreMutation(mutation) {
  return !this.contentDOM && mutation.type != "selection";
};

prototypeAccessors.contentLost.get = function () {
  return this.contentDOM && this.contentDOM != this.dom && !this.dom.contains(this.contentDOM);
}; // Remove a subtree of the element tree that has been touched
// by a DOM change, so that the next update will redraw it.


ViewDesc.prototype.markDirty = function markDirty(from, to) {
  for (var offset = 0, i = 0; i < this.children.length; i++) {
    var child = this.children[i],
        end = offset + child.size;

    if (offset == end ? from <= end && to >= offset : from < end && to > offset) {
      var startInside = offset + child.border,
          endInside = end - child.border;

      if (from >= startInside && to <= endInside) {
        this.dirty = from == offset || to == end ? CONTENT_DIRTY : CHILD_DIRTY;

        if (from == startInside && to == endInside && (child.contentLost || child.dom.parentNode != this.contentDOM)) {
          child.dirty = NODE_DIRTY;
        } else {
          child.markDirty(from - startInside, to - startInside);
        }

        return;
      } else {
        child.dirty = NODE_DIRTY;
      }
    }

    offset = end;
  }

  this.dirty = CONTENT_DIRTY;
};

ViewDesc.prototype.markParentsDirty = function markParentsDirty() {
  var level = 1;

  for (var node = this.parent; node; node = node.parent, level++) {
    var dirty = level == 1 ? CONTENT_DIRTY : CHILD_DIRTY;

    if (node.dirty < dirty) {
      node.dirty = dirty;
    }
  }
};

Object.defineProperties(ViewDesc.prototype, prototypeAccessors); // Reused array to avoid allocating fresh arrays for things that will
// stay empty anyway.

var nothing = []; // A widget desc represents a widget decoration, which is a DOM node
// drawn between the document nodes.

var WidgetViewDesc = /*@__PURE__*/function (ViewDesc) {
  function WidgetViewDesc(parent, widget, view, pos) {
    var self,
        dom = widget.type.toDOM;

    if (typeof dom == "function") {
      dom = dom(view, function () {
        if (!self) {
          return pos;
        }

        if (self.parent) {
          return self.parent.posBeforeChild(self);
        }
      });
    }

    if (!widget.type.spec.raw) {
      if (dom.nodeType != 1) {
        var wrap = document.createElement("span");
        wrap.appendChild(dom);
        dom = wrap;
      }

      dom.contentEditable = false;
      dom.classList.add("ProseMirror-widget");
    }

    ViewDesc.call(this, parent, nothing, dom, null);
    this.widget = widget;
    self = this;
  }

  if (ViewDesc) WidgetViewDesc.__proto__ = ViewDesc;
  WidgetViewDesc.prototype = Object.create(ViewDesc && ViewDesc.prototype);
  WidgetViewDesc.prototype.constructor = WidgetViewDesc;
  var prototypeAccessors$1 = {
    beforePosition: {
      configurable: true
    }
  };

  prototypeAccessors$1.beforePosition.get = function () {
    return this.widget.type.side < 0;
  };

  WidgetViewDesc.prototype.matchesWidget = function matchesWidget(widget) {
    return this.dirty == NOT_DIRTY && widget.type.eq(this.widget.type);
  };

  WidgetViewDesc.prototype.parseRule = function parseRule() {
    return {
      ignore: true
    };
  };

  WidgetViewDesc.prototype.stopEvent = function stopEvent(event) {
    var stop = this.widget.spec.stopEvent;
    return stop ? stop(event) : false;
  };

  WidgetViewDesc.prototype.ignoreMutation = function ignoreMutation(mutation) {
    return mutation.type != "selection" || this.widget.spec.ignoreSelection;
  };

  Object.defineProperties(WidgetViewDesc.prototype, prototypeAccessors$1);
  return WidgetViewDesc;
}(ViewDesc);

var CompositionViewDesc = /*@__PURE__*/function (ViewDesc) {
  function CompositionViewDesc(parent, dom, textDOM, text) {
    ViewDesc.call(this, parent, nothing, dom, null);
    this.textDOM = textDOM;
    this.text = text;
  }

  if (ViewDesc) CompositionViewDesc.__proto__ = ViewDesc;
  CompositionViewDesc.prototype = Object.create(ViewDesc && ViewDesc.prototype);
  CompositionViewDesc.prototype.constructor = CompositionViewDesc;
  var prototypeAccessors$2 = {
    size: {
      configurable: true
    }
  };

  prototypeAccessors$2.size.get = function () {
    return this.text.length;
  };

  CompositionViewDesc.prototype.localPosFromDOM = function localPosFromDOM(dom, offset) {
    if (dom != this.textDOM) {
      return this.posAtStart + (offset ? this.size : 0);
    }

    return this.posAtStart + offset;
  };

  CompositionViewDesc.prototype.domFromPos = function domFromPos(pos) {
    return {
      node: this.textDOM,
      offset: pos
    };
  };

  CompositionViewDesc.prototype.ignoreMutation = function ignoreMutation(mut) {
    return mut.type === 'characterData' && mut.target.nodeValue == mut.oldValue;
  };

  Object.defineProperties(CompositionViewDesc.prototype, prototypeAccessors$2);
  return CompositionViewDesc;
}(ViewDesc); // A mark desc represents a mark. May have multiple children,
// depending on how the mark is split. Note that marks are drawn using
// a fixed nesting order, for simplicity and predictability, so in
// some cases they will be split more often than would appear
// necessary.


var MarkViewDesc = /*@__PURE__*/function (ViewDesc) {
  function MarkViewDesc(parent, mark, dom, contentDOM) {
    ViewDesc.call(this, parent, [], dom, contentDOM);
    this.mark = mark;
  }

  if (ViewDesc) MarkViewDesc.__proto__ = ViewDesc;
  MarkViewDesc.prototype = Object.create(ViewDesc && ViewDesc.prototype);
  MarkViewDesc.prototype.constructor = MarkViewDesc;

  MarkViewDesc.create = function create(parent, mark, inline, view) {
    var custom = view.nodeViews[mark.type.name];
    var spec = custom && custom(mark, view, inline);

    if (!spec || !spec.dom) {
      spec = _prosemirrorModel.DOMSerializer.renderSpec(document, mark.type.spec.toDOM(mark, inline));
    }

    return new MarkViewDesc(parent, mark, spec.dom, spec.contentDOM || spec.dom);
  };

  MarkViewDesc.prototype.parseRule = function parseRule() {
    return {
      mark: this.mark.type.name,
      attrs: this.mark.attrs,
      contentElement: this.contentDOM
    };
  };

  MarkViewDesc.prototype.matchesMark = function matchesMark(mark) {
    return this.dirty != NODE_DIRTY && this.mark.eq(mark);
  };

  MarkViewDesc.prototype.markDirty = function markDirty(from, to) {
    ViewDesc.prototype.markDirty.call(this, from, to); // Move dirty info to nearest node view

    if (this.dirty != NOT_DIRTY) {
      var parent = this.parent;

      while (!parent.node) {
        parent = parent.parent;
      }

      if (parent.dirty < this.dirty) {
        parent.dirty = this.dirty;
      }

      this.dirty = NOT_DIRTY;
    }
  };

  MarkViewDesc.prototype.slice = function slice(from, to, view) {
    var copy = MarkViewDesc.create(this.parent, this.mark, true, view);
    var nodes = this.children,
        size = this.size;

    if (to < size) {
      nodes = replaceNodes(nodes, to, size, view);
    }

    if (from > 0) {
      nodes = replaceNodes(nodes, 0, from, view);
    }

    for (var i = 0; i < nodes.length; i++) {
      nodes[i].parent = copy;
    }

    copy.children = nodes;
    return copy;
  };

  return MarkViewDesc;
}(ViewDesc); // Node view descs are the main, most common type of view desc, and
// correspond to an actual node in the document. Unlike mark descs,
// they populate their child array themselves.


var NodeViewDesc = /*@__PURE__*/function (ViewDesc) {
  function NodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, view, pos) {
    ViewDesc.call(this, parent, node.isLeaf ? nothing : [], dom, contentDOM);
    this.nodeDOM = nodeDOM;
    this.node = node;
    this.outerDeco = outerDeco;
    this.innerDeco = innerDeco;

    if (contentDOM) {
      this.updateChildren(view, pos);
    }
  }

  if (ViewDesc) NodeViewDesc.__proto__ = ViewDesc;
  NodeViewDesc.prototype = Object.create(ViewDesc && ViewDesc.prototype);
  NodeViewDesc.prototype.constructor = NodeViewDesc;
  var prototypeAccessors$3 = {
    size: {
      configurable: true
    },
    border: {
      configurable: true
    }
  }; // By default, a node is rendered using the `toDOM` method from the
  // node type spec. But client code can use the `nodeViews` spec to
  // supply a custom node view, which can influence various aspects of
  // the way the node works.
  //
  // (Using subclassing for this was intentionally decided against,
  // since it'd require exposing a whole slew of finnicky
  // implementation details to the user code that they probably will
  // never need.)

  NodeViewDesc.create = function create(parent, node, outerDeco, innerDeco, view, pos) {
    var assign;
    var custom = view.nodeViews[node.type.name],
        descObj;
    var spec = custom && custom(node, view, function () {
      // (This is a function that allows the custom view to find its
      // own position)
      if (!descObj) {
        return pos;
      }

      if (descObj.parent) {
        return descObj.parent.posBeforeChild(descObj);
      }
    }, outerDeco);
    var dom = spec && spec.dom,
        contentDOM = spec && spec.contentDOM;

    if (node.isText) {
      if (!dom) {
        dom = document.createTextNode(node.text);
      } else if (dom.nodeType != 3) {
        throw new RangeError("Text must be rendered as a DOM text node");
      }
    } else if (!dom) {
      assign = _prosemirrorModel.DOMSerializer.renderSpec(document, node.type.spec.toDOM(node)), dom = assign.dom, contentDOM = assign.contentDOM;
    }

    if (!contentDOM && !node.isText && dom.nodeName != "BR") {
      // Chrome gets confused by <br contenteditable=false>
      if (!dom.hasAttribute("contenteditable")) {
        dom.contentEditable = false;
      }

      if (node.type.spec.draggable) {
        dom.draggable = true;
      }
    }

    var nodeDOM = dom;
    dom = applyOuterDeco(dom, outerDeco, node);

    if (spec) {
      return descObj = new CustomNodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, spec, view, pos + 1);
    } else if (node.isText) {
      return new TextViewDesc(parent, node, outerDeco, innerDeco, dom, nodeDOM, view);
    } else {
      return new NodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, view, pos + 1);
    }
  };

  NodeViewDesc.prototype.parseRule = function parseRule() {
    var this$1 = this; // Experimental kludge to allow opt-in re-parsing of nodes

    if (this.node.type.spec.reparseInView) {
      return null;
    } // FIXME the assumption that this can always return the current
    // attrs means that if the user somehow manages to change the
    // attrs in the dom, that won't be picked up. Not entirely sure
    // whether this is a problem


    var rule = {
      node: this.node.type.name,
      attrs: this.node.attrs
    };

    if (this.node.type.spec.code) {
      rule.preserveWhitespace = "full";
    }

    if (this.contentDOM && !this.contentLost) {
      rule.contentElement = this.contentDOM;
    } else {
      rule.getContent = function () {
        return this$1.contentDOM ? _prosemirrorModel.Fragment.empty : this$1.node.content;
      };
    }

    return rule;
  };

  NodeViewDesc.prototype.matchesNode = function matchesNode(node, outerDeco, innerDeco) {
    return this.dirty == NOT_DIRTY && node.eq(this.node) && sameOuterDeco(outerDeco, this.outerDeco) && innerDeco.eq(this.innerDeco);
  };

  prototypeAccessors$3.size.get = function () {
    return this.node.nodeSize;
  };

  prototypeAccessors$3.border.get = function () {
    return this.node.isLeaf ? 0 : 1;
  }; // Syncs `this.children` to match `this.node.content` and the local
  // decorations, possibly introducing nesting for marks. Then, in a
  // separate step, syncs the DOM inside `this.contentDOM` to
  // `this.children`.


  NodeViewDesc.prototype.updateChildren = function updateChildren(view, pos) {
    var this$1 = this;
    var inline = this.node.inlineContent,
        off = pos;
    var composition = inline && view.composing && this.localCompositionNode(view, pos);
    var updater = new ViewTreeUpdater(this, composition && composition.node);
    iterDeco(this.node, this.innerDeco, function (widget, i, insideNode) {
      if (widget.spec.marks) {
        updater.syncToMarks(widget.spec.marks, inline, view);
      } else if (widget.type.side >= 0 && !insideNode) {
        updater.syncToMarks(i == this$1.node.childCount ? _prosemirrorModel.Mark.none : this$1.node.child(i).marks, inline, view);
      } // If the next node is a desc matching this widget, reuse it,
      // otherwise insert the widget as a new view desc.


      updater.placeWidget(widget, view, off);
    }, function (child, outerDeco, innerDeco, i) {
      // Make sure the wrapping mark descs match the node's marks.
      updater.syncToMarks(child.marks, inline, view); // Either find an existing desc that exactly matches this node,
      // and drop the descs before it.

      updater.findNodeMatch(child, outerDeco, innerDeco, i) || // Or try updating the next desc to reflect this node.
      updater.updateNextNode(child, outerDeco, innerDeco, view, i) || // Or just add it as a new desc.
      updater.addNode(child, outerDeco, innerDeco, view, off);
      off += child.nodeSize;
    }); // Drop all remaining descs after the current position.

    updater.syncToMarks(nothing, inline, view);

    if (this.node.isTextblock) {
      updater.addTextblockHacks();
    }

    updater.destroyRest(); // Sync the DOM if anything changed

    if (updater.changed || this.dirty == CONTENT_DIRTY) {
      // May have to protect focused DOM from being changed if a composition is active
      if (composition) {
        this.protectLocalComposition(view, composition);
      }

      this.renderChildren();
    }
  };

  NodeViewDesc.prototype.renderChildren = function renderChildren() {
    renderDescs(this.contentDOM, this.children);

    if (result.ios) {
      iosHacks(this.dom);
    }
  };

  NodeViewDesc.prototype.localCompositionNode = function localCompositionNode(view, pos) {
    // Only do something if both the selection and a focused text node
    // are inside of this node, and the node isn't already part of a
    // view that's a child of this view
    var ref = view.state.selection;
    var from = ref.from;
    var to = ref.to;

    if (!(view.state.selection instanceof _prosemirrorState.TextSelection) || from < pos || to > pos + this.node.content.size) {
      return;
    }

    var sel = view.root.getSelection();
    var textNode = nearbyTextNode(sel.focusNode, sel.focusOffset);

    if (!textNode || !this.dom.contains(textNode.parentNode)) {
      return;
    } // Find the text in the focused node in the node, stop if it's not
    // there (may have been modified through other means, in which
    // case it should overwritten)


    var text = textNode.nodeValue;
    var textPos = findTextInFragment(this.node.content, text, from - pos, to - pos);
    return textPos < 0 ? null : {
      node: textNode,
      pos: textPos,
      text: text
    };
  };

  NodeViewDesc.prototype.protectLocalComposition = function protectLocalComposition(view, ref) {
    var node = ref.node;
    var pos = ref.pos;
    var text = ref.text; // The node is already part of a local view desc, leave it there

    if (this.getDesc(node)) {
      return;
    } // Create a composition view for the orphaned nodes


    var topNode = node;

    for (;; topNode = topNode.parentNode) {
      if (topNode.parentNode == this.contentDOM) {
        break;
      }

      while (topNode.previousSibling) {
        topNode.parentNode.removeChild(topNode.previousSibling);
      }

      while (topNode.nextSibling) {
        topNode.parentNode.removeChild(topNode.nextSibling);
      }

      if (topNode.pmViewDesc) {
        topNode.pmViewDesc = null;
      }
    }

    var desc = new CompositionViewDesc(this, topNode, node, text);
    view.compositionNodes.push(desc); // Patch up this.children to contain the composition view

    this.children = replaceNodes(this.children, pos, pos + text.length, view, desc);
  }; // : (Node, [Decoration], DecorationSet, EditorView) → bool
  // If this desc be updated to match the given node decoration,
  // do so and return true.


  NodeViewDesc.prototype.update = function update(node, outerDeco, innerDeco, view) {
    if (this.dirty == NODE_DIRTY || !node.sameMarkup(this.node)) {
      return false;
    }

    this.updateInner(node, outerDeco, innerDeco, view);
    return true;
  };

  NodeViewDesc.prototype.updateInner = function updateInner(node, outerDeco, innerDeco, view) {
    this.updateOuterDeco(outerDeco);
    this.node = node;
    this.innerDeco = innerDeco;

    if (this.contentDOM) {
      this.updateChildren(view, this.posAtStart);
    }

    this.dirty = NOT_DIRTY;
  };

  NodeViewDesc.prototype.updateOuterDeco = function updateOuterDeco(outerDeco) {
    if (sameOuterDeco(outerDeco, this.outerDeco)) {
      return;
    }

    var needsWrap = this.nodeDOM.nodeType != 1;
    var oldDOM = this.dom;
    this.dom = patchOuterDeco(this.dom, this.nodeDOM, computeOuterDeco(this.outerDeco, this.node, needsWrap), computeOuterDeco(outerDeco, this.node, needsWrap));

    if (this.dom != oldDOM) {
      oldDOM.pmViewDesc = null;
      this.dom.pmViewDesc = this;
    }

    this.outerDeco = outerDeco;
  }; // Mark this node as being the selected node.


  NodeViewDesc.prototype.selectNode = function selectNode() {
    this.nodeDOM.classList.add("ProseMirror-selectednode");

    if (this.contentDOM || !this.node.type.spec.draggable) {
      this.dom.draggable = true;
    }
  }; // Remove selected node marking from this node.


  NodeViewDesc.prototype.deselectNode = function deselectNode() {
    this.nodeDOM.classList.remove("ProseMirror-selectednode");

    if (this.contentDOM || !this.node.type.spec.draggable) {
      this.dom.removeAttribute("draggable");
    }
  };

  Object.defineProperties(NodeViewDesc.prototype, prototypeAccessors$3);
  return NodeViewDesc;
}(ViewDesc); // Create a view desc for the top-level document node, to be exported
// and used by the view class.


function docViewDesc(doc, outerDeco, innerDeco, dom, view) {
  applyOuterDeco(dom, outerDeco, doc);
  return new NodeViewDesc(null, doc, outerDeco, innerDeco, dom, dom, dom, view, 0);
}

var TextViewDesc = /*@__PURE__*/function (NodeViewDesc) {
  function TextViewDesc(parent, node, outerDeco, innerDeco, dom, nodeDOM, view) {
    NodeViewDesc.call(this, parent, node, outerDeco, innerDeco, dom, null, nodeDOM, view);
  }

  if (NodeViewDesc) TextViewDesc.__proto__ = NodeViewDesc;
  TextViewDesc.prototype = Object.create(NodeViewDesc && NodeViewDesc.prototype);
  TextViewDesc.prototype.constructor = TextViewDesc;

  TextViewDesc.prototype.parseRule = function parseRule() {
    return {
      skip: this.nodeDOM.parentNode || true
    };
  };

  TextViewDesc.prototype.update = function update(node, outerDeco) {
    if (this.dirty == NODE_DIRTY || this.dirty != NOT_DIRTY && !this.inParent() || !node.sameMarkup(this.node)) {
      return false;
    }

    this.updateOuterDeco(outerDeco);

    if ((this.dirty != NOT_DIRTY || node.text != this.node.text) && node.text != this.nodeDOM.nodeValue) {
      this.nodeDOM.nodeValue = node.text;
    }

    this.node = node;
    this.dirty = NOT_DIRTY;
    return true;
  };

  TextViewDesc.prototype.inParent = function inParent() {
    var parentDOM = this.parent.contentDOM;

    for (var n = this.nodeDOM; n; n = n.parentNode) {
      if (n == parentDOM) {
        return true;
      }
    }

    return false;
  };

  TextViewDesc.prototype.domFromPos = function domFromPos(pos) {
    return {
      node: this.nodeDOM,
      offset: pos
    };
  };

  TextViewDesc.prototype.localPosFromDOM = function localPosFromDOM(dom, offset, bias) {
    if (dom == this.nodeDOM) {
      return this.posAtStart + Math.min(offset, this.node.text.length);
    }

    return NodeViewDesc.prototype.localPosFromDOM.call(this, dom, offset, bias);
  };

  TextViewDesc.prototype.ignoreMutation = function ignoreMutation(mutation) {
    return mutation.type != "characterData" && mutation.type != "selection";
  };

  TextViewDesc.prototype.slice = function slice(from, to, view) {
    var node = this.node.cut(from, to),
        dom = document.createTextNode(node.text);
    return new TextViewDesc(this.parent, node, this.outerDeco, this.innerDeco, dom, dom, view);
  };

  return TextViewDesc;
}(NodeViewDesc); // A dummy desc used to tag trailing BR or span nodes created to work
// around contentEditable terribleness.


var BRHackViewDesc = /*@__PURE__*/function (ViewDesc) {
  function BRHackViewDesc() {
    ViewDesc.apply(this, arguments);
  }

  if (ViewDesc) BRHackViewDesc.__proto__ = ViewDesc;
  BRHackViewDesc.prototype = Object.create(ViewDesc && ViewDesc.prototype);
  BRHackViewDesc.prototype.constructor = BRHackViewDesc;

  BRHackViewDesc.prototype.parseRule = function parseRule() {
    return {
      ignore: true
    };
  };

  BRHackViewDesc.prototype.matchesHack = function matchesHack() {
    return this.dirty == NOT_DIRTY;
  };

  return BRHackViewDesc;
}(ViewDesc); // A separate subclass is used for customized node views, so that the
// extra checks only have to be made for nodes that are actually
// customized.


var CustomNodeViewDesc = /*@__PURE__*/function (NodeViewDesc) {
  function CustomNodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, spec, view, pos) {
    NodeViewDesc.call(this, parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, view, pos);
    this.spec = spec;
  }

  if (NodeViewDesc) CustomNodeViewDesc.__proto__ = NodeViewDesc;
  CustomNodeViewDesc.prototype = Object.create(NodeViewDesc && NodeViewDesc.prototype);
  CustomNodeViewDesc.prototype.constructor = CustomNodeViewDesc; // A custom `update` method gets to decide whether the update goes
  // through. If it does, and there's a `contentDOM` node, our logic
  // updates the children.

  CustomNodeViewDesc.prototype.update = function update(node, outerDeco, innerDeco, view) {
    if (this.dirty == NODE_DIRTY) {
      return false;
    }

    if (this.spec.update) {
      var result = this.spec.update(node, outerDeco);

      if (result) {
        this.updateInner(node, outerDeco, innerDeco, view);
      }

      return result;
    } else if (!this.contentDOM && !node.isLeaf) {
      return false;
    } else {
      return NodeViewDesc.prototype.update.call(this, node, outerDeco, innerDeco, view);
    }
  };

  CustomNodeViewDesc.prototype.selectNode = function selectNode() {
    this.spec.selectNode ? this.spec.selectNode() : NodeViewDesc.prototype.selectNode.call(this);
  };

  CustomNodeViewDesc.prototype.deselectNode = function deselectNode() {
    this.spec.deselectNode ? this.spec.deselectNode() : NodeViewDesc.prototype.deselectNode.call(this);
  };

  CustomNodeViewDesc.prototype.setSelection = function setSelection(anchor, head, root, force) {
    this.spec.setSelection ? this.spec.setSelection(anchor, head, root) : NodeViewDesc.prototype.setSelection.call(this, anchor, head, root, force);
  };

  CustomNodeViewDesc.prototype.destroy = function destroy() {
    if (this.spec.destroy) {
      this.spec.destroy();
    }

    NodeViewDesc.prototype.destroy.call(this);
  };

  CustomNodeViewDesc.prototype.stopEvent = function stopEvent(event) {
    return this.spec.stopEvent ? this.spec.stopEvent(event) : false;
  };

  CustomNodeViewDesc.prototype.ignoreMutation = function ignoreMutation(mutation) {
    return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : NodeViewDesc.prototype.ignoreMutation.call(this, mutation);
  };

  return CustomNodeViewDesc;
}(NodeViewDesc); // : (dom.Node, [ViewDesc])
// Sync the content of the given DOM node with the nodes associated
// with the given array of view descs, recursing into mark descs
// because this should sync the subtree for a whole node at a time.


function renderDescs(parentDOM, descs) {
  var dom = parentDOM.firstChild;

  for (var i = 0; i < descs.length; i++) {
    var desc = descs[i],
        childDOM = desc.dom;

    if (childDOM.parentNode == parentDOM) {
      while (childDOM != dom) {
        dom = rm(dom);
      }

      dom = dom.nextSibling;
    } else {
      parentDOM.insertBefore(childDOM, dom);
    }

    if (desc instanceof MarkViewDesc) {
      var pos = dom ? dom.previousSibling : parentDOM.lastChild;
      renderDescs(desc.contentDOM, desc.children);
      dom = pos ? pos.nextSibling : parentDOM.firstChild;
    }
  }

  while (dom) {
    dom = rm(dom);
  }
}

function OuterDecoLevel(nodeName) {
  if (nodeName) {
    this.nodeName = nodeName;
  }
}

OuterDecoLevel.prototype = Object.create(null);
var noDeco = [new OuterDecoLevel()];

function computeOuterDeco(outerDeco, node, needsWrap) {
  if (outerDeco.length == 0) {
    return noDeco;
  }

  var top = needsWrap ? noDeco[0] : new OuterDecoLevel(),
      result = [top];

  for (var i = 0; i < outerDeco.length; i++) {
    var attrs = outerDeco[i].type.attrs,
        cur = top;

    if (!attrs) {
      continue;
    }

    if (attrs.nodeName) {
      result.push(cur = new OuterDecoLevel(attrs.nodeName));
    }

    for (var name in attrs) {
      var val = attrs[name];

      if (val == null) {
        continue;
      }

      if (needsWrap && result.length == 1) {
        result.push(cur = top = new OuterDecoLevel(node.isInline ? "span" : "div"));
      }

      if (name == "class") {
        cur.class = (cur.class ? cur.class + " " : "") + val;
      } else if (name == "style") {
        cur.style = (cur.style ? cur.style + ";" : "") + val;
      } else if (name != "nodeName") {
        cur[name] = val;
      }
    }
  }

  return result;
}

function patchOuterDeco(outerDOM, nodeDOM, prevComputed, curComputed) {
  // Shortcut for trivial case
  if (prevComputed == noDeco && curComputed == noDeco) {
    return nodeDOM;
  }

  var curDOM = nodeDOM;

  for (var i = 0; i < curComputed.length; i++) {
    var deco = curComputed[i],
        prev = prevComputed[i];

    if (i) {
      var parent = void 0;

      if (prev && prev.nodeName == deco.nodeName && curDOM != outerDOM && (parent = curDOM.parentNode) && parent.tagName.toLowerCase() == deco.nodeName) {
        curDOM = parent;
      } else {
        parent = document.createElement(deco.nodeName);
        parent.appendChild(curDOM);
        prev = noDeco[0];
        curDOM = parent;
      }
    }

    patchAttributes(curDOM, prev || noDeco[0], deco);
  }

  return curDOM;
}

function patchAttributes(dom, prev, cur) {
  for (var name in prev) {
    if (name != "class" && name != "style" && name != "nodeName" && !(name in cur)) {
      dom.removeAttribute(name);
    }
  }

  for (var name$1 in cur) {
    if (name$1 != "class" && name$1 != "style" && name$1 != "nodeName" && cur[name$1] != prev[name$1]) {
      dom.setAttribute(name$1, cur[name$1]);
    }
  }

  if (prev.class != cur.class) {
    var prevList = prev.class ? prev.class.split(" ") : nothing;
    var curList = cur.class ? cur.class.split(" ") : nothing;

    for (var i = 0; i < prevList.length; i++) {
      if (curList.indexOf(prevList[i]) == -1) {
        dom.classList.remove(prevList[i]);
      }
    }

    for (var i$1 = 0; i$1 < curList.length; i$1++) {
      if (prevList.indexOf(curList[i$1]) == -1) {
        dom.classList.add(curList[i$1]);
      }
    }
  }

  if (prev.style != cur.style) {
    if (prev.style) {
      var prop = /\s*([\w\-\xa1-\uffff]+)\s*:(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|\(.*?\)|[^;])*/g,
          m;

      while (m = prop.exec(prev.style)) {
        dom.style.removeProperty(m[1]);
      }
    }

    if (cur.style) {
      dom.style.cssText += cur.style;
    }
  }
}

function applyOuterDeco(dom, deco, node) {
  return patchOuterDeco(dom, dom, noDeco, computeOuterDeco(deco, node, dom.nodeType != 1));
} // : ([Decoration], [Decoration]) → bool


function sameOuterDeco(a, b) {
  if (a.length != b.length) {
    return false;
  }

  for (var i = 0; i < a.length; i++) {
    if (!a[i].type.eq(b[i].type)) {
      return false;
    }
  }

  return true;
} // Remove a DOM node and return its next sibling.


function rm(dom) {
  var next = dom.nextSibling;
  dom.parentNode.removeChild(dom);
  return next;
} // Helper class for incrementally updating a tree of mark descs and
// the widget and node descs inside of them.


var ViewTreeUpdater = function ViewTreeUpdater(top, lockedNode) {
  this.top = top;
  this.lock = lockedNode; // Index into `this.top`'s child array, represents the current
  // update position.

  this.index = 0; // When entering a mark, the current top and index are pushed
  // onto this.

  this.stack = []; // Tracks whether anything was changed

  this.changed = false;
  var pre = preMatch(top.node.content, top.children);
  this.preMatched = pre.nodes;
  this.preMatchOffset = pre.offset;
};

ViewTreeUpdater.prototype.getPreMatch = function getPreMatch(index) {
  return index >= this.preMatchOffset ? this.preMatched[index - this.preMatchOffset] : null;
}; // Destroy and remove the children between the given indices in
// `this.top`.


ViewTreeUpdater.prototype.destroyBetween = function destroyBetween(start, end) {
  if (start == end) {
    return;
  }

  for (var i = start; i < end; i++) {
    this.top.children[i].destroy();
  }

  this.top.children.splice(start, end - start);
  this.changed = true;
}; // Destroy all remaining children in `this.top`.


ViewTreeUpdater.prototype.destroyRest = function destroyRest() {
  this.destroyBetween(this.index, this.top.children.length);
}; // : ([Mark], EditorView)
// Sync the current stack of mark descs with the given array of
// marks, reusing existing mark descs when possible.


ViewTreeUpdater.prototype.syncToMarks = function syncToMarks(marks, inline, view) {
  var keep = 0,
      depth = this.stack.length >> 1;
  var maxKeep = Math.min(depth, marks.length);

  while (keep < maxKeep && (keep == depth - 1 ? this.top : this.stack[keep + 1 << 1]).matchesMark(marks[keep]) && marks[keep].type.spec.spanning !== false) {
    keep++;
  }

  while (keep < depth) {
    this.destroyRest();
    this.top.dirty = NOT_DIRTY;
    this.index = this.stack.pop();
    this.top = this.stack.pop();
    depth--;
  }

  while (depth < marks.length) {
    this.stack.push(this.top, this.index + 1);
    var found = -1;

    for (var i = this.index; i < Math.min(this.index + 3, this.top.children.length); i++) {
      if (this.top.children[i].matchesMark(marks[depth])) {
        found = i;
        break;
      }
    }

    if (found > -1) {
      if (found > this.index) {
        this.changed = true;
        this.destroyBetween(this.index, found);
      }

      this.top = this.top.children[this.index];
    } else {
      var markDesc = MarkViewDesc.create(this.top, marks[depth], inline, view);
      this.top.children.splice(this.index, 0, markDesc);
      this.top = markDesc;
      this.changed = true;
    }

    this.index = 0;
    depth++;
  }
}; // : (Node, [Decoration], DecorationSet) → bool
// Try to find a node desc matching the given data. Skip over it and
// return true when successful.


ViewTreeUpdater.prototype.findNodeMatch = function findNodeMatch(node, outerDeco, innerDeco, index) {
  var found = -1,
      preMatch = index < 0 ? undefined : this.getPreMatch(index),
      children = this.top.children;

  if (preMatch && preMatch.matchesNode(node, outerDeco, innerDeco)) {
    found = children.indexOf(preMatch);
  } else {
    for (var i = this.index, e = Math.min(children.length, i + 5); i < e; i++) {
      var child = children[i];

      if (child.matchesNode(node, outerDeco, innerDeco) && this.preMatched.indexOf(child) < 0) {
        found = i;
        break;
      }
    }
  }

  if (found < 0) {
    return false;
  }

  this.destroyBetween(this.index, found);
  this.index++;
  return true;
}; // : (Node, [Decoration], DecorationSet, EditorView, Fragment, number) → bool
// Try to update the next node, if any, to the given data. Checks
// pre-matches to avoid overwriting nodes that could still be used.


ViewTreeUpdater.prototype.updateNextNode = function updateNextNode(node, outerDeco, innerDeco, view, index) {
  for (var i = this.index; i < this.top.children.length; i++) {
    var next = this.top.children[i];

    if (next instanceof NodeViewDesc) {
      var preMatch = this.preMatched.indexOf(next);

      if (preMatch > -1 && preMatch + this.preMatchOffset != index) {
        return false;
      }

      var nextDOM = next.dom; // Can't update if nextDOM is or contains this.lock, except if
      // it's a text node whose content already matches the new text
      // and whose decorations match the new ones.

      var locked = this.lock && (nextDOM == this.lock || nextDOM.nodeType == 1 && nextDOM.contains(this.lock.parentNode)) && !(node.isText && next.node && next.node.isText && next.nodeDOM.nodeValue == node.text && next.dirty != NODE_DIRTY && sameOuterDeco(outerDeco, next.outerDeco));

      if (!locked && next.update(node, outerDeco, innerDeco, view)) {
        this.destroyBetween(this.index, i);

        if (next.dom != nextDOM) {
          this.changed = true;
        }

        this.index++;
        return true;
      }

      break;
    }
  }

  return false;
}; // : (Node, [Decoration], DecorationSet, EditorView)
// Insert the node as a newly created node desc.


ViewTreeUpdater.prototype.addNode = function addNode(node, outerDeco, innerDeco, view, pos) {
  this.top.children.splice(this.index++, 0, NodeViewDesc.create(this.top, node, outerDeco, innerDeco, view, pos));
  this.changed = true;
};

ViewTreeUpdater.prototype.placeWidget = function placeWidget(widget, view, pos) {
  if (this.index < this.top.children.length && this.top.children[this.index].matchesWidget(widget)) {
    this.index++;
  } else {
    var desc = new WidgetViewDesc(this.top, widget, view, pos);
    this.top.children.splice(this.index++, 0, desc);
    this.changed = true;
  }
}; // Make sure a textblock looks and behaves correctly in
// contentEditable.


ViewTreeUpdater.prototype.addTextblockHacks = function addTextblockHacks() {
  var lastChild = this.top.children[this.index - 1];

  while (lastChild instanceof MarkViewDesc) {
    lastChild = lastChild.children[lastChild.children.length - 1];
  }

  if (!lastChild || // Empty textblock
  !(lastChild instanceof TextViewDesc) || /\n$/.test(lastChild.node.text)) {
    if (this.index < this.top.children.length && this.top.children[this.index].matchesHack()) {
      this.index++;
    } else {
      var dom = document.createElement("br");
      this.top.children.splice(this.index++, 0, new BRHackViewDesc(this.top, nothing, dom, null));
      this.changed = true;
    }
  }
}; // : (Fragment, [ViewDesc]) → [ViewDesc]
// Iterate from the end of the fragment and array of descs to find
// directly matching ones, in order to avoid overeagerly reusing
// those for other nodes. Returns an array whose positions correspond
// to node positions in the fragment, and whose elements are either
// descs matched to the child at that index, or empty.


function preMatch(frag, descs) {
  var result = [],
      end = frag.childCount;

  for (var i = descs.length - 1; end > 0 && i >= 0; i--) {
    var desc = descs[i],
        node = desc.node;

    if (!node) {
      continue;
    }

    if (node != frag.child(end - 1)) {
      break;
    }

    result.push(desc);
    --end;
  }

  return {
    nodes: result.reverse(),
    offset: end
  };
}

function compareSide(a, b) {
  return a.type.side - b.type.side;
} // : (ViewDesc, DecorationSet, (Decoration, number), (Node, [Decoration], DecorationSet, number))
// This function abstracts iterating over the nodes and decorations in
// a fragment. Calls `onNode` for each node, with its local and child
// decorations. Splits text nodes when there is a decoration starting
// or ending inside of them. Calls `onWidget` for each widget.


function iterDeco(parent, deco, onWidget, onNode) {
  var locals = deco.locals(parent),
      offset = 0; // Simple, cheap variant for when there are no local decorations

  if (locals.length == 0) {
    for (var i = 0; i < parent.childCount; i++) {
      var child = parent.child(i);
      onNode(child, locals, deco.forChild(offset, child), i);
      offset += child.nodeSize;
    }

    return;
  }

  var decoIndex = 0,
      active = [],
      restNode = null;

  for (var parentIndex = 0;;) {
    if (decoIndex < locals.length && locals[decoIndex].to == offset) {
      var widget = locals[decoIndex++],
          widgets = void 0;

      while (decoIndex < locals.length && locals[decoIndex].to == offset) {
        (widgets || (widgets = [widget])).push(locals[decoIndex++]);
      }

      if (widgets) {
        widgets.sort(compareSide);

        for (var i$1 = 0; i$1 < widgets.length; i$1++) {
          onWidget(widgets[i$1], parentIndex, !!restNode);
        }
      } else {
        onWidget(widget, parentIndex, !!restNode);
      }
    }

    var child$1 = void 0,
        index = void 0;

    if (restNode) {
      index = -1;
      child$1 = restNode;
      restNode = null;
    } else if (parentIndex < parent.childCount) {
      index = parentIndex;
      child$1 = parent.child(parentIndex++);
    } else {
      break;
    }

    for (var i$2 = 0; i$2 < active.length; i$2++) {
      if (active[i$2].to <= offset) {
        active.splice(i$2--, 1);
      }
    }

    while (decoIndex < locals.length && locals[decoIndex].from == offset) {
      active.push(locals[decoIndex++]);
    }

    var end = offset + child$1.nodeSize;

    if (child$1.isText) {
      var cutAt = end;

      if (decoIndex < locals.length && locals[decoIndex].from < cutAt) {
        cutAt = locals[decoIndex].from;
      }

      for (var i$3 = 0; i$3 < active.length; i$3++) {
        if (active[i$3].to < cutAt) {
          cutAt = active[i$3].to;
        }
      }

      if (cutAt < end) {
        restNode = child$1.cut(cutAt - offset);
        child$1 = child$1.cut(0, cutAt - offset);
        end = cutAt;
        index = -1;
      }
    }

    onNode(child$1, active.length ? active.slice() : nothing, deco.forChild(offset, child$1), index);
    offset = end;
  }
} // List markers in Mobile Safari will mysteriously disappear
// sometimes. This works around that.


function iosHacks(dom) {
  if (dom.nodeName == "UL" || dom.nodeName == "OL") {
    var oldCSS = dom.style.cssText;
    dom.style.cssText = oldCSS + "; list-style: square !important";
    window.getComputedStyle(dom).listStyle;
    dom.style.cssText = oldCSS;
  }
}

function nearbyTextNode(node, offset) {
  for (;;) {
    if (node.nodeType == 3) {
      return node;
    }

    if (node.nodeType == 1 && offset > 0) {
      if (node.childNodes.length > offset && node.childNodes[offset].nodeType == 3) {
        return node.childNodes[offset];
      }

      node = node.childNodes[offset - 1];
      offset = nodeSize(node);
    } else if (node.nodeType == 1 && offset < node.childNodes.length) {
      node = node.childNodes[offset];
      offset = 0;
    } else {
      return null;
    }
  }
} // Find a piece of text in an inline fragment, overlapping from-to


function findTextInFragment(frag, text, from, to) {
  for (var i = 0, pos = 0; i < frag.childCount && pos <= to;) {
    var child = frag.child(i++),
        childStart = pos;
    pos += child.nodeSize;

    if (!child.isText) {
      continue;
    }

    var str = child.text;

    while (i < frag.childCount) {
      var next = frag.child(i++);
      pos += next.nodeSize;

      if (!next.isText) {
        break;
      }

      str += next.text;
    }

    if (pos >= from) {
      var found = str.lastIndexOf(text, to - childStart);

      if (found >= 0 && found + text.length + childStart >= from) {
        return childStart + found;
      }
    }
  }

  return -1;
} // Replace range from-to in an array of view descs with replacement
// (may be null to just delete). This goes very much against the grain
// of the rest of this code, which tends to create nodes with the
// right shape in one go, rather than messing with them after
// creation, but is necessary in the composition hack.


function replaceNodes(nodes, from, to, view, replacement) {
  var result = [];

  for (var i = 0, off = 0; i < nodes.length; i++) {
    var child = nodes[i],
        start = off,
        end = off += child.size;

    if (start >= to || end <= from) {
      result.push(child);
    } else {
      if (start < from) {
        result.push(child.slice(0, from - start, view));
      }

      if (replacement) {
        result.push(replacement);
        replacement = null;
      }

      if (end > to) {
        result.push(child.slice(to - start, child.size, view));
      }
    }
  }

  return result;
}

function moveSelectionBlock(state, dir) {
  var ref = state.selection;
  var $anchor = ref.$anchor;
  var $head = ref.$head;
  var $side = dir > 0 ? $anchor.max($head) : $anchor.min($head);
  var $start = !$side.parent.inlineContent ? $side : $side.depth ? state.doc.resolve(dir > 0 ? $side.after() : $side.before()) : null;
  return $start && _prosemirrorState.Selection.findFrom($start, dir);
}

function apply(view, sel) {
  view.dispatch(view.state.tr.setSelection(sel).scrollIntoView());
  return true;
}

function selectHorizontally(view, dir, mods) {
  var sel = view.state.selection;

  if (sel instanceof _prosemirrorState.TextSelection) {
    if (!sel.empty || mods.indexOf("s") > -1) {
      return false;
    } else if (view.endOfTextblock(dir > 0 ? "right" : "left")) {
      var next = moveSelectionBlock(view.state, dir);

      if (next && next instanceof _prosemirrorState.NodeSelection) {
        return apply(view, next);
      }

      return false;
    } else {
      var $head = sel.$head,
          node = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter,
          desc;

      if (!node || node.isText) {
        return false;
      }

      var nodePos = dir < 0 ? $head.pos - node.nodeSize : $head.pos;

      if (!(node.isAtom || (desc = view.docView.descAt(nodePos)) && !desc.contentDOM)) {
        return false;
      }

      if (_prosemirrorState.NodeSelection.isSelectable(node)) {
        return apply(view, new _prosemirrorState.NodeSelection(dir < 0 ? view.state.doc.resolve($head.pos - node.nodeSize) : $head));
      } else if (result.webkit) {
        // Chrome and Safari will introduce extra pointless cursor
        // positions around inline uneditable nodes, so we have to
        // take over and move the cursor past them (#937)
        return apply(view, new _prosemirrorState.TextSelection(view.state.doc.resolve(dir < 0 ? nodePos : nodePos + node.nodeSize)));
      } else {
        return false;
      }
    }
  } else if (sel instanceof _prosemirrorState.NodeSelection && sel.node.isInline) {
    return apply(view, new _prosemirrorState.TextSelection(dir > 0 ? sel.$to : sel.$from));
  } else {
    var next$1 = moveSelectionBlock(view.state, dir);

    if (next$1) {
      return apply(view, next$1);
    }

    return false;
  }
}

function nodeLen(node) {
  return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length;
}

function isIgnorable(dom) {
  var desc = dom.pmViewDesc;
  return desc && desc.size == 0 && (dom.nextSibling || dom.nodeName != "BR");
} // Make sure the cursor isn't directly after one or more ignored
// nodes, which will confuse the browser's cursor motion logic.


function skipIgnoredNodesLeft(view) {
  var sel = view.root.getSelection();
  var node = sel.focusNode,
      offset = sel.focusOffset;

  if (!node) {
    return;
  }

  var moveNode,
      moveOffset,
      force = false; // Gecko will do odd things when the selection is directly in front
  // of a non-editable node, so in that case, move it into the next
  // node if possible. Issue prosemirror/prosemirror#832.

  if (result.gecko && node.nodeType == 1 && offset < nodeLen(node) && isIgnorable(node.childNodes[offset])) {
    force = true;
  }

  for (;;) {
    if (offset > 0) {
      if (node.nodeType != 1) {
        break;
      } else {
        var before = node.childNodes[offset - 1];

        if (isIgnorable(before)) {
          moveNode = node;
          moveOffset = --offset;
        } else if (before.nodeType == 3) {
          node = before;
          offset = node.nodeValue.length;
        } else {
          break;
        }
      }
    } else if (isBlockNode(node)) {
      break;
    } else {
      var prev = node.previousSibling;

      while (prev && isIgnorable(prev)) {
        moveNode = node.parentNode;
        moveOffset = domIndex(prev);
        prev = prev.previousSibling;
      }

      if (!prev) {
        node = node.parentNode;

        if (node == view.dom) {
          break;
        }

        offset = 0;
      } else {
        node = prev;
        offset = nodeLen(node);
      }
    }
  }

  if (force) {
    setSelFocus(view, sel, node, offset);
  } else if (moveNode) {
    setSelFocus(view, sel, moveNode, moveOffset);
  }
} // Make sure the cursor isn't directly before one or more ignored
// nodes.


function skipIgnoredNodesRight(view) {
  var sel = view.root.getSelection();
  var node = sel.focusNode,
      offset = sel.focusOffset;

  if (!node) {
    return;
  }

  var len = nodeLen(node);
  var moveNode, moveOffset;

  for (;;) {
    if (offset < len) {
      if (node.nodeType != 1) {
        break;
      }

      var after = node.childNodes[offset];

      if (isIgnorable(after)) {
        moveNode = node;
        moveOffset = ++offset;
      } else {
        break;
      }
    } else if (isBlockNode(node)) {
      break;
    } else {
      var next = node.nextSibling;

      while (next && isIgnorable(next)) {
        moveNode = next.parentNode;
        moveOffset = domIndex(next) + 1;
        next = next.nextSibling;
      }

      if (!next) {
        node = node.parentNode;

        if (node == view.dom) {
          break;
        }

        offset = len = 0;
      } else {
        node = next;
        offset = 0;
        len = nodeLen(node);
      }
    }
  }

  if (moveNode) {
    setSelFocus(view, sel, moveNode, moveOffset);
  }
}

function isBlockNode(dom) {
  var desc = dom.pmViewDesc;
  return desc && desc.node && desc.node.isBlock;
}

function setSelFocus(view, sel, node, offset) {
  if (selectionCollapsed(sel)) {
    var range = document.createRange();
    range.setEnd(node, offset);
    range.setStart(node, offset);
    sel.removeAllRanges();
    sel.addRange(range);
  } else if (sel.extend) {
    sel.extend(node, offset);
  }

  view.domObserver.setCurSelection();
} // : (EditorState, number)
// Check whether vertical selection motion would involve node
// selections. If so, apply it (if not, the result is left to the
// browser)


function selectVertically(view, dir, mods) {
  var sel = view.state.selection;

  if (sel instanceof _prosemirrorState.TextSelection && !sel.empty || mods.indexOf("s") > -1) {
    return false;
  }

  var $from = sel.$from;
  var $to = sel.$to;

  if (!$from.parent.inlineContent || view.endOfTextblock(dir < 0 ? "up" : "down")) {
    var next = moveSelectionBlock(view.state, dir);

    if (next && next instanceof _prosemirrorState.NodeSelection) {
      return apply(view, next);
    }
  }

  if (!$from.parent.inlineContent) {
    var beyond = _prosemirrorState.Selection.findFrom(dir < 0 ? $from : $to, dir);

    return beyond ? apply(view, beyond) : true;
  }

  return false;
}

function stopNativeHorizontalDelete(view, dir) {
  if (!(view.state.selection instanceof _prosemirrorState.TextSelection)) {
    return true;
  }

  var ref = view.state.selection;
  var $head = ref.$head;
  var $anchor = ref.$anchor;
  var empty = ref.empty;

  if (!$head.sameParent($anchor)) {
    return true;
  }

  if (!empty) {
    return false;
  }

  if (view.endOfTextblock(dir > 0 ? "forward" : "backward")) {
    return true;
  }

  var nextNode = !$head.textOffset && (dir < 0 ? $head.nodeBefore : $head.nodeAfter);

  if (nextNode && !nextNode.isText) {
    var tr = view.state.tr;

    if (dir < 0) {
      tr.delete($head.pos - nextNode.nodeSize, $head.pos);
    } else {
      tr.delete($head.pos, $head.pos + nextNode.nodeSize);
    }

    view.dispatch(tr);
    return true;
  }

  return false;
}

function switchEditable(view, node, state) {
  view.domObserver.stop();
  node.contentEditable = state;
  view.domObserver.start();
} // Issue #867 / https://bugs.chromium.org/p/chromium/issues/detail?id=903821
// In which Chrome does really wrong things when the down arrow is
// pressed when the cursor is directly at the start of a textblock and
// has an uneditable node after it


function chromeDownArrowBug(view) {
  if (!result.chrome || view.state.selection.$head.parentOffset > 0) {
    return;
  }

  var ref = view.root.getSelection();
  var focusNode = ref.focusNode;
  var focusOffset = ref.focusOffset;

  if (focusNode && focusNode.nodeType == 1 && focusOffset == 0 && focusNode.firstChild && focusNode.firstChild.contentEditable == "false") {
    var child = focusNode.firstChild;
    switchEditable(view, child, true);
    setTimeout(function () {
      return switchEditable(view, child, false);
    }, 20);
  }
} // A backdrop key mapping used to make sure we always suppress keys
// that have a dangerous default effect, even if the commands they are
// bound to return false, and to make sure that cursor-motion keys
// find a cursor (as opposed to a node selection) when pressed. For
// cursor-motion keys, the code in the handlers also takes care of
// block selections.


function getMods(event) {
  var result = "";

  if (event.ctrlKey) {
    result += "c";
  }

  if (event.metaKey) {
    result += "m";
  }

  if (event.altKey) {
    result += "a";
  }

  if (event.shiftKey) {
    result += "s";
  }

  return result;
}

function captureKeyDown(view, event) {
  var code = event.keyCode,
      mods = getMods(event);

  if (code == 8 || result.mac && code == 72 && mods == "c") {
    // Backspace, Ctrl-h on Mac
    return stopNativeHorizontalDelete(view, -1) || skipIgnoredNodesLeft(view);
  } else if (code == 46 || result.mac && code == 68 && mods == "c") {
    // Delete, Ctrl-d on Mac
    return stopNativeHorizontalDelete(view, 1) || skipIgnoredNodesRight(view);
  } else if (code == 13 || code == 27) {
    // Enter, Esc
    return true;
  } else if (code == 37) {
    // Left arrow
    return selectHorizontally(view, -1, mods) || skipIgnoredNodesLeft(view);
  } else if (code == 39) {
    // Right arrow
    return selectHorizontally(view, 1, mods) || skipIgnoredNodesRight(view);
  } else if (code == 38) {
    // Up arrow
    return selectVertically(view, -1, mods) || skipIgnoredNodesLeft(view);
  } else if (code == 40) {
    // Down arrow
    return chromeDownArrowBug(view) || selectVertically(view, 1, mods) || skipIgnoredNodesRight(view);
  } else if (mods == (result.mac ? "m" : "c") && (code == 66 || code == 73 || code == 89 || code == 90)) {
    // Mod-[biyz]
    return true;
  }

  return false;
}

function selectionFromDOM(view, origin) {
  var domSel = view.root.getSelection(),
      doc = view.state.doc;
  var nearestDesc = view.docView.nearestDesc(domSel.focusNode),
      inWidget = nearestDesc && nearestDesc.size == 0;
  var head = view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset);
  var $head = doc.resolve(head),
      $anchor,
      selection;

  if (selectionCollapsed(domSel)) {
    $anchor = $head;

    while (nearestDesc && !nearestDesc.node) {
      nearestDesc = nearestDesc.parent;
    }

    if (nearestDesc && nearestDesc.node.isAtom && _prosemirrorState.NodeSelection.isSelectable(nearestDesc.node) && nearestDesc.parent && !(nearestDesc.node.isInline && isOnEdge(domSel.focusNode, domSel.focusOffset, nearestDesc.dom))) {
      var pos = nearestDesc.posBefore;
      selection = new _prosemirrorState.NodeSelection(head == pos ? $head : doc.resolve(pos));
    }
  } else {
    $anchor = doc.resolve(view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset));
  }

  if (!selection) {
    var bias = origin == "pointer" || view.state.selection.head < $head.pos && !inWidget ? 1 : -1;
    selection = selectionBetween(view, $anchor, $head, bias);
  }

  return selection;
}

function selectionToDOM(view, force) {
  var sel = view.state.selection;
  syncNodeSelection(view, sel);

  if (view.editable ? !view.hasFocus() : !(hasSelection(view) && document.activeElement && document.activeElement.contains(view.dom))) {
    return;
  }

  view.domObserver.disconnectSelection();

  if (view.cursorWrapper) {
    selectCursorWrapper(view);
  } else {
    var anchor = sel.anchor;
    var head = sel.head;
    var resetEditableFrom, resetEditableTo;

    if (brokenSelectBetweenUneditable && !(sel instanceof _prosemirrorState.TextSelection)) {
      if (!sel.$from.parent.inlineContent) {
        resetEditableFrom = temporarilyEditableNear(view, sel.from);
      }

      if (!sel.empty && !sel.$from.parent.inlineContent) {
        resetEditableTo = temporarilyEditableNear(view, sel.to);
      }
    }

    view.docView.setSelection(anchor, head, view.root, force);

    if (brokenSelectBetweenUneditable) {
      if (resetEditableFrom) {
        resetEditable(resetEditableFrom);
      }

      if (resetEditableTo) {
        resetEditable(resetEditableTo);
      }
    }

    if (sel.visible) {
      view.dom.classList.remove("ProseMirror-hideselection");
    } else {
      view.dom.classList.add("ProseMirror-hideselection");

      if ("onselectionchange" in document) {
        removeClassOnSelectionChange(view);
      }
    }
  }

  view.domObserver.setCurSelection();
  view.domObserver.connectSelection();
} // Kludge to work around Webkit not allowing a selection to start/end
// between non-editable block nodes. We briefly make something
// editable, set the selection, then set it uneditable again.


var brokenSelectBetweenUneditable = result.safari || result.chrome && result.chrome_version < 63;

function temporarilyEditableNear(view, pos) {
  var ref = view.docView.domFromPos(pos);
  var node = ref.node;
  var offset = ref.offset;
  var after = offset < node.childNodes.length ? node.childNodes[offset] : null;
  var before = offset ? node.childNodes[offset - 1] : null;

  if (result.safari && after && after.contentEditable == "false") {
    return setEditable(after);
  }

  if ((!after || after.contentEditable == "false") && (!before || before.contentEditable == "false")) {
    if (after) {
      return setEditable(after);
    } else if (before) {
      return setEditable(before);
    }
  }
}

function setEditable(element) {
  element.contentEditable = "true";

  if (result.safari && element.draggable) {
    element.draggable = false;
    element.wasDraggable = true;
  }

  return element;
}

function resetEditable(element) {
  element.contentEditable = "false";

  if (element.wasDraggable) {
    element.draggable = true;
    element.wasDraggable = null;
  }
}

function removeClassOnSelectionChange(view) {
  var doc = view.dom.ownerDocument;
  doc.removeEventListener("selectionchange", view.hideSelectionGuard);
  var domSel = view.root.getSelection();
  var node = domSel.anchorNode,
      offset = domSel.anchorOffset;
  doc.addEventListener("selectionchange", view.hideSelectionGuard = function () {
    if (domSel.anchorNode != node || domSel.anchorOffset != offset) {
      doc.removeEventListener("selectionchange", view.hideSelectionGuard);
      view.dom.classList.remove("ProseMirror-hideselection");
    }
  });
}

function selectCursorWrapper(view) {
  var domSel = view.root.getSelection(),
      range = document.createRange();
  var node = view.cursorWrapper.dom,
      img = node.nodeName == "IMG";

  if (img) {
    range.setEnd(node.parentNode, domIndex(node) + 1);
  } else {
    range.setEnd(node, 0);
  }

  range.collapse(false);
  domSel.removeAllRanges();
  domSel.addRange(range); // Kludge to kill 'control selection' in IE11 when selecting an
  // invisible cursor wrapper, since that would result in those weird
  // resize handles and a selection that considers the absolutely
  // positioned wrapper, rather than the root editable node, the
  // focused element.

  if (!img && !view.state.selection.visible && result.ie && result.ie_version <= 11) {
    node.disabled = true;
    node.disabled = false;
  }
}

function syncNodeSelection(view, sel) {
  if (sel instanceof _prosemirrorState.NodeSelection) {
    var desc = view.docView.descAt(sel.from);

    if (desc != view.lastSelectedViewDesc) {
      clearNodeSelection(view);

      if (desc) {
        desc.selectNode();
      }

      view.lastSelectedViewDesc = desc;
    }
  } else {
    clearNodeSelection(view);
  }
} // Clear all DOM statefulness of the last node selection.


function clearNodeSelection(view) {
  if (view.lastSelectedViewDesc) {
    if (view.lastSelectedViewDesc.parent) {
      view.lastSelectedViewDesc.deselectNode();
    }

    view.lastSelectedViewDesc = null;
  }
}

function selectionBetween(view, $anchor, $head, bias) {
  return view.someProp("createSelectionBetween", function (f) {
    return f(view, $anchor, $head);
  }) || _prosemirrorState.TextSelection.between($anchor, $head, bias);
}

function hasFocusAndSelection(view) {
  if (view.editable && view.root.activeElement != view.dom) {
    return false;
  }

  return hasSelection(view);
}

function hasSelection(view) {
  var sel = view.root.getSelection();

  if (!sel.anchorNode) {
    return false;
  }

  try {
    // Firefox will raise 'permission denied' errors when accessing
    // properties of `sel.anchorNode` when it's in a generated CSS
    // element.
    return view.dom.contains(sel.anchorNode.nodeType == 3 ? sel.anchorNode.parentNode : sel.anchorNode) && (view.editable || view.dom.contains(sel.focusNode.nodeType == 3 ? sel.focusNode.parentNode : sel.focusNode));
  } catch (_) {
    return false;
  }
}

function anchorInRightPlace(view) {
  var anchorDOM = view.docView.domFromPos(view.state.selection.anchor);
  var domSel = view.root.getSelection();
  return isEquivalentPosition(anchorDOM.node, anchorDOM.offset, domSel.anchorNode, domSel.anchorOffset);
} // Note that all referencing and parsing is done with the
// start-of-operation selection and document, since that's the one
// that the DOM represents. If any changes came in in the meantime,
// the modification is mapped over those before it is applied, in
// readDOMChange.


function parseBetween(view, from_, to_) {
  var ref = view.docView.parseRange(from_, to_);
  var parent = ref.node;
  var fromOffset = ref.fromOffset;
  var toOffset = ref.toOffset;
  var from = ref.from;
  var to = ref.to;
  var domSel = view.root.getSelection(),
      find = null,
      anchor = domSel.anchorNode;

  if (anchor && view.dom.contains(anchor.nodeType == 1 ? anchor : anchor.parentNode)) {
    find = [{
      node: anchor,
      offset: domSel.anchorOffset
    }];

    if (!selectionCollapsed(domSel)) {
      find.push({
        node: domSel.focusNode,
        offset: domSel.focusOffset
      });
    }
  } // Work around issue in Chrome where backspacing sometimes replaces
  // the deleted content with a random BR node (issues #799, #831)


  if (result.chrome && view.lastKeyCode === 8) {
    for (var off = toOffset; off > fromOffset; off--) {
      var node = parent.childNodes[off - 1],
          desc = node.pmViewDesc;

      if (node.nodeType == "BR" && !desc) {
        toOffset = off;
        break;
      }

      if (!desc || desc.size) {
        break;
      }
    }
  }

  var startDoc = view.state.doc;

  var parser = view.someProp("domParser") || _prosemirrorModel.DOMParser.fromSchema(view.state.schema);

  var $from = startDoc.resolve(from);
  var sel = null,
      doc = parser.parse(parent, {
    topNode: $from.parent,
    topMatch: $from.parent.contentMatchAt($from.index()),
    topOpen: true,
    from: fromOffset,
    to: toOffset,
    preserveWhitespace: $from.parent.type.spec.code ? "full" : true,
    editableContent: true,
    findPositions: find,
    ruleFromNode: ruleFromNode,
    context: $from
  });

  if (find && find[0].pos != null) {
    var anchor$1 = find[0].pos,
        head = find[1] && find[1].pos;

    if (head == null) {
      head = anchor$1;
    }

    sel = {
      anchor: anchor$1 + from,
      head: head + from
    };
  }

  return {
    doc: doc,
    sel: sel,
    from: from,
    to: to
  };
}

function ruleFromNode(dom) {
  var desc = dom.pmViewDesc;

  if (desc) {
    return desc.parseRule();
  } else if (dom.nodeName == "BR" && dom.parentNode) {
    // Safari replaces the list item or table cell with a BR
    // directly in the list node (?!) if you delete the last
    // character in a list item or table cell (#708, #862)
    if (result.safari && /^(ul|ol)$/i.test(dom.parentNode.nodeName)) {
      var skip = document.createElement("div");
      skip.appendChild(document.createElement("li"));
      return {
        skip: skip
      };
    } else if (dom.parentNode.lastChild == dom || result.safari && /^(tr|table)$/i.test(dom.parentNode.nodeName)) {
      return {
        ignore: true
      };
    }
  } else if (dom.nodeName == "IMG" && dom.getAttribute("mark-placeholder")) {
    return {
      ignore: true
    };
  }
}

function readDOMChange(view, from, to, typeOver, addedNodes) {
  if (from < 0) {
    var origin = view.lastSelectionTime > Date.now() - 50 ? view.lastSelectionOrigin : null;
    var newSel = selectionFromDOM(view, origin);

    if (!view.state.selection.eq(newSel)) {
      var tr$1 = view.state.tr.setSelection(newSel);

      if (origin == "pointer") {
        tr$1.setMeta("pointer", true);
      } else if (origin == "key") {
        tr$1.scrollIntoView();
      }

      view.dispatch(tr$1);
    }

    return;
  }

  var $before = view.state.doc.resolve(from);
  var shared = $before.sharedDepth(to);
  from = $before.before(shared + 1);
  to = view.state.doc.resolve(to).after(shared + 1);
  var sel = view.state.selection;
  var parse = parseBetween(view, from, to);
  var doc = view.state.doc,
      compare = doc.slice(parse.from, parse.to);
  var preferredPos, preferredSide; // Prefer anchoring to end when Backspace is pressed

  if (view.lastKeyCode === 8 && Date.now() - 100 < view.lastKeyCodeTime) {
    preferredPos = view.state.selection.to;
    preferredSide = "end";
  } else {
    preferredPos = view.state.selection.from;
    preferredSide = "start";
  }

  view.lastKeyCode = null;
  var change = findDiff(compare.content, parse.doc.content, parse.from, preferredPos, preferredSide);

  if (!change) {
    if (typeOver && sel instanceof _prosemirrorState.TextSelection && !sel.empty && sel.$head.sameParent(sel.$anchor) && !view.composing && !(parse.sel && parse.sel.anchor != parse.sel.head)) {
      change = {
        start: sel.from,
        endA: sel.to,
        endB: sel.to
      };
    } else {
      if (parse.sel) {
        var sel$1 = resolveSelection(view, view.state.doc, parse.sel);

        if (sel$1 && !sel$1.eq(view.state.selection)) {
          view.dispatch(view.state.tr.setSelection(sel$1));
        }
      }

      return;
    }
  }

  view.domChangeCount++; // Handle the case where overwriting a selection by typing matches
  // the start or end of the selected content, creating a change
  // that's smaller than what was actually overwritten.

  if (view.state.selection.from < view.state.selection.to && change.start == change.endB && view.state.selection instanceof _prosemirrorState.TextSelection) {
    if (change.start > view.state.selection.from && change.start <= view.state.selection.from + 2) {
      change.start = view.state.selection.from;
    } else if (change.endA < view.state.selection.to && change.endA >= view.state.selection.to - 2) {
      change.endB += view.state.selection.to - change.endA;
      change.endA = view.state.selection.to;
    }
  } // IE11 will insert a non-breaking space _ahead_ of the space after
  // the cursor space when adding a space before another space. When
  // that happened, adjust the change to cover the space instead.


  if (result.ie && result.ie_version <= 11 && change.endB == change.start + 1 && change.endA == change.start && change.start > parse.from && parse.doc.textBetween(change.start - parse.from - 1, change.start - parse.from + 1) == " \u00a0") {
    change.start--;
    change.endA--;
    change.endB--;
  }

  var $from = parse.doc.resolveNoCache(change.start - parse.from);
  var $to = parse.doc.resolveNoCache(change.endB - parse.from);
  var inlineChange = $from.sameParent($to) && $from.parent.inlineContent;
  var nextSel; // If this looks like the effect of pressing Enter (or was recorded
  // as being an iOS enter press), just dispatch an Enter key instead.

  if ((result.ios && view.lastIOSEnter > Date.now() - 100 && (!inlineChange || addedNodes.some(function (n) {
    return n.nodeName == "DIV" || n.nodeName == "P";
  })) || !inlineChange && $from.pos < parse.doc.content.size && (nextSel = _prosemirrorState.Selection.findFrom(parse.doc.resolve($from.pos + 1), 1, true)) && nextSel.head == $to.pos) && view.someProp("handleKeyDown", function (f) {
    return f(view, keyEvent(13, "Enter"));
  })) {
    view.lastIOSEnter = 0;
    return;
  } // Same for backspace


  if (view.state.selection.anchor > change.start && looksLikeJoin(doc, change.start, change.endA, $from, $to) && view.someProp("handleKeyDown", function (f) {
    return f(view, keyEvent(8, "Backspace"));
  })) {
    if (result.android && result.chrome) {
      view.domObserver.suppressSelectionUpdates();
    } // #820


    return;
  }

  var chFrom = change.start,
      chTo = change.endA;
  var tr, storedMarks, markChange, $from1;

  if (inlineChange) {
    if ($from.pos == $to.pos) {
      // Deletion
      // IE11 sometimes weirdly moves the DOM selection around after
      // backspacing out the first element in a textblock
      if (result.ie && result.ie_version <= 11 && $from.parentOffset == 0) {
        view.domObserver.suppressSelectionUpdates();
        setTimeout(function () {
          return selectionToDOM(view);
        }, 20);
      }

      tr = view.state.tr.delete(chFrom, chTo);
      storedMarks = doc.resolve(change.start).marksAcross(doc.resolve(change.endA));
    } else if ( // Adding or removing a mark
    change.endA == change.endB && ($from1 = doc.resolve(change.start)) && (markChange = isMarkChange($from.parent.content.cut($from.parentOffset, $to.parentOffset), $from1.parent.content.cut($from1.parentOffset, change.endA - $from1.start())))) {
      tr = view.state.tr;

      if (markChange.type == "add") {
        tr.addMark(chFrom, chTo, markChange.mark);
      } else {
        tr.removeMark(chFrom, chTo, markChange.mark);
      }
    } else if ($from.parent.child($from.index()).isText && $from.index() == $to.index() - ($to.textOffset ? 0 : 1)) {
      // Both positions in the same text node -- simply insert text
      var text = $from.parent.textBetween($from.parentOffset, $to.parentOffset);

      if (view.someProp("handleTextInput", function (f) {
        return f(view, chFrom, chTo, text);
      })) {
        return;
      }

      tr = view.state.tr.insertText(text, chFrom, chTo);
    }
  }

  if (!tr) {
    tr = view.state.tr.replace(chFrom, chTo, parse.doc.slice(change.start - parse.from, change.endB - parse.from));
  }

  if (parse.sel) {
    var sel$2 = resolveSelection(view, tr.doc, parse.sel); // Chrome Android will sometimes, during composition, report the
    // selection in the wrong place. If it looks like that is
    // happening, don't update the selection.
    // Edge just doesn't move the cursor forward when you start typing
    // in an empty block or between br nodes.

    if (sel$2 && !(result.chrome && result.android && view.composing && sel$2.empty && (sel$2.head == chFrom || sel$2.head == tr.mapping.map(chTo) - 1) || result.ie && sel$2.empty && sel$2.head == chFrom)) {
      tr.setSelection(sel$2);
    }
  }

  if (storedMarks) {
    tr.ensureMarks(storedMarks);
  }

  view.dispatch(tr.scrollIntoView());
}

function resolveSelection(view, doc, parsedSel) {
  if (Math.max(parsedSel.anchor, parsedSel.head) > doc.content.size) {
    return null;
  }

  return selectionBetween(view, doc.resolve(parsedSel.anchor), doc.resolve(parsedSel.head));
} // : (Fragment, Fragment) → ?{mark: Mark, type: string}
// Given two same-length, non-empty fragments of inline content,
// determine whether the first could be created from the second by
// removing or adding a single mark type.


function isMarkChange(cur, prev) {
  var curMarks = cur.firstChild.marks,
      prevMarks = prev.firstChild.marks;
  var added = curMarks,
      removed = prevMarks,
      type,
      mark,
      update;

  for (var i = 0; i < prevMarks.length; i++) {
    added = prevMarks[i].removeFromSet(added);
  }

  for (var i$1 = 0; i$1 < curMarks.length; i$1++) {
    removed = curMarks[i$1].removeFromSet(removed);
  }

  if (added.length == 1 && removed.length == 0) {
    mark = added[0];
    type = "add";

    update = function (node) {
      return node.mark(mark.addToSet(node.marks));
    };
  } else if (added.length == 0 && removed.length == 1) {
    mark = removed[0];
    type = "remove";

    update = function (node) {
      return node.mark(mark.removeFromSet(node.marks));
    };
  } else {
    return null;
  }

  var updated = [];

  for (var i$2 = 0; i$2 < prev.childCount; i$2++) {
    updated.push(update(prev.child(i$2)));
  }

  if (_prosemirrorModel.Fragment.from(updated).eq(cur)) {
    return {
      mark: mark,
      type: type
    };
  }
}

function looksLikeJoin(old, start, end, $newStart, $newEnd) {
  if (!$newStart.parent.isTextblock || // The content must have shrunk
  end - start <= $newEnd.pos - $newStart.pos || // newEnd must point directly at or after the end of the block that newStart points into
  skipClosingAndOpening($newStart, true, false) < $newEnd.pos) {
    return false;
  }

  var $start = old.resolve(start); // Start must be at the end of a block

  if ($start.parentOffset < $start.parent.content.size || !$start.parent.isTextblock) {
    return false;
  }

  var $next = old.resolve(skipClosingAndOpening($start, true, true)); // The next textblock must start before end and end near it

  if (!$next.parent.isTextblock || $next.pos > end || skipClosingAndOpening($next, true, false) < end) {
    return false;
  } // The fragments after the join point must match


  return $newStart.parent.content.cut($newStart.parentOffset).eq($next.parent.content);
}

function skipClosingAndOpening($pos, fromEnd, mayOpen) {
  var depth = $pos.depth,
      end = fromEnd ? $pos.end() : $pos.pos;

  while (depth > 0 && (fromEnd || $pos.indexAfter(depth) == $pos.node(depth).childCount)) {
    depth--;
    end++;
    fromEnd = false;
  }

  if (mayOpen) {
    var next = $pos.node(depth).maybeChild($pos.indexAfter(depth));

    while (next && !next.isLeaf) {
      next = next.firstChild;
      end++;
    }
  }

  return end;
}

function findDiff(a, b, pos, preferredPos, preferredSide) {
  var start = a.findDiffStart(b, pos);

  if (start == null) {
    return null;
  }

  var ref = a.findDiffEnd(b, pos + a.size, pos + b.size);
  var endA = ref.a;
  var endB = ref.b;

  if (preferredSide == "end") {
    var adjust = Math.max(0, start - Math.min(endA, endB));
    preferredPos -= endA + adjust - start;
  }

  if (endA < start && a.size < b.size) {
    var move = preferredPos <= start && preferredPos >= endA ? start - preferredPos : 0;
    start -= move;
    endB = start + (endB - endA);
    endA = start;
  } else if (endB < start) {
    var move$1 = preferredPos <= start && preferredPos >= endB ? start - preferredPos : 0;
    start -= move$1;
    endA = start + (endA - endB);
    endB = start;
  }

  return {
    start: start,
    endA: endA,
    endB: endB
  };
}

function serializeForClipboard(view, slice) {
  var context = [];
  var content = slice.content;
  var openStart = slice.openStart;
  var openEnd = slice.openEnd;

  while (openStart > 1 && openEnd > 1 && content.childCount == 1 && content.firstChild.childCount == 1) {
    openStart--;
    openEnd--;
    var node = content.firstChild;
    context.push(node.type.name, node.type.hasRequiredAttrs() ? node.attrs : null);
    content = node.content;
  }

  var serializer = view.someProp("clipboardSerializer") || _prosemirrorModel.DOMSerializer.fromSchema(view.state.schema);

  var doc = detachedDoc(),
      wrap = doc.createElement("div");
  wrap.appendChild(serializer.serializeFragment(content, {
    document: doc
  }));
  var firstChild = wrap.firstChild,
      needsWrap;

  while (firstChild && firstChild.nodeType == 1 && (needsWrap = wrapMap[firstChild.nodeName.toLowerCase()])) {
    for (var i = needsWrap.length - 1; i >= 0; i--) {
      var wrapper = doc.createElement(needsWrap[i]);

      while (wrap.firstChild) {
        wrapper.appendChild(wrap.firstChild);
      }

      wrap.appendChild(wrapper);
    }

    firstChild = wrap.firstChild;
  }

  if (firstChild && firstChild.nodeType == 1) {
    firstChild.setAttribute("data-pm-slice", openStart + " " + openEnd + " " + JSON.stringify(context));
  }

  var text = view.someProp("clipboardTextSerializer", function (f) {
    return f(slice);
  }) || slice.content.textBetween(0, slice.content.size, "\n\n");
  return {
    dom: wrap,
    text: text
  };
} // : (EditorView, string, string, ?bool, ResolvedPos) → ?Slice
// Read a slice of content from the clipboard (or drop data).


function parseFromClipboard(view, text, html, plainText, $context) {
  var dom,
      inCode = $context.parent.type.spec.code,
      slice;

  if (!html && !text) {
    return null;
  }

  var asText = text && (plainText || inCode || !html);

  if (asText) {
    view.someProp("transformPastedText", function (f) {
      text = f(text);
    });

    if (inCode) {
      return new _prosemirrorModel.Slice(_prosemirrorModel.Fragment.from(view.state.schema.text(text)), 0, 0);
    }

    var parsed = view.someProp("clipboardTextParser", function (f) {
      return f(text, $context);
    });

    if (parsed) {
      slice = parsed;
    } else {
      dom = document.createElement("div");
      text.trim().split(/(?:\r\n?|\n)+/).forEach(function (block) {
        dom.appendChild(document.createElement("p")).textContent = block;
      });
    }
  } else {
    view.someProp("transformPastedHTML", function (f) {
      html = f(html);
    });
    dom = readHTML(html);
  }

  var contextNode = dom && dom.querySelector("[data-pm-slice]");
  var sliceData = contextNode && /^(\d+) (\d+) (.*)/.exec(contextNode.getAttribute("data-pm-slice"));

  if (!slice) {
    var parser = view.someProp("clipboardParser") || view.someProp("domParser") || _prosemirrorModel.DOMParser.fromSchema(view.state.schema);

    slice = parser.parseSlice(dom, {
      preserveWhitespace: !!(asText || sliceData),
      context: $context
    });
  }

  if (sliceData) {
    slice = addContext(closeSlice(slice, +sliceData[1], +sliceData[2]), sliceData[3]);
  } else // HTML wasn't created by ProseMirror. Make sure top-level siblings are coherent
    {
      slice = _prosemirrorModel.Slice.maxOpen(normalizeSiblings(slice.content, $context), false);
    }

  view.someProp("transformPasted", function (f) {
    slice = f(slice);
  });
  return slice;
} // Takes a slice parsed with parseSlice, which means there hasn't been
// any content-expression checking done on the top nodes, tries to
// find a parent node in the current context that might fit the nodes,
// and if successful, rebuilds the slice so that it fits into that parent.
//
// This addresses the problem that Transform.replace expects a
// coherent slice, and will fail to place a set of siblings that don't
// fit anywhere in the schema.


function normalizeSiblings(fragment, $context) {
  if (fragment.childCount < 2) {
    return fragment;
  }

  var loop = function (d) {
    var parent = $context.node(d);
    var match = parent.contentMatchAt($context.index(d));
    var lastWrap = void 0,
        result = [];
    fragment.forEach(function (node) {
      if (!result) {
        return;
      }

      var wrap = match.findWrapping(node.type),
          inLast;

      if (!wrap) {
        return result = null;
      }

      if (inLast = result.length && lastWrap.length && addToSibling(wrap, lastWrap, node, result[result.length - 1], 0)) {
        result[result.length - 1] = inLast;
      } else {
        if (result.length) {
          result[result.length - 1] = closeRight(result[result.length - 1], lastWrap.length);
        }

        var wrapped = withWrappers(node, wrap);
        result.push(wrapped);
        match = match.matchType(wrapped.type, wrapped.attrs);
        lastWrap = wrap;
      }
    });

    if (result) {
      return {
        v: _prosemirrorModel.Fragment.from(result)
      };
    }
  };

  for (var d = $context.depth; d >= 0; d--) {
    var returned = loop(d);
    if (returned) return returned.v;
  }

  return fragment;
}

function withWrappers(node, wrap, from) {
  if (from === void 0) from = 0;

  for (var i = wrap.length - 1; i >= from; i--) {
    node = wrap[i].create(null, _prosemirrorModel.Fragment.from(node));
  }

  return node;
} // Used to group adjacent nodes wrapped in similar parents by
// normalizeSiblings into the same parent node


function addToSibling(wrap, lastWrap, node, sibling, depth) {
  if (depth < wrap.length && depth < lastWrap.length && wrap[depth] == lastWrap[depth]) {
    var inner = addToSibling(wrap, lastWrap, node, sibling.lastChild, depth + 1);

    if (inner) {
      return sibling.copy(sibling.content.replaceChild(sibling.childCount - 1, inner));
    }

    var match = sibling.contentMatchAt(sibling.childCount);

    if (match.matchType(depth == wrap.length - 1 ? node.type : wrap[depth + 1])) {
      return sibling.copy(sibling.content.append(_prosemirrorModel.Fragment.from(withWrappers(node, wrap, depth + 1))));
    }
  }
}

function closeRight(node, depth) {
  if (depth == 0) {
    return node;
  }

  var fragment = node.content.replaceChild(node.childCount - 1, closeRight(node.lastChild, depth - 1));
  var fill = node.contentMatchAt(node.childCount).fillBefore(_prosemirrorModel.Fragment.empty, true);
  return node.copy(fragment.append(fill));
}

function closeRange(fragment, side, from, to, depth, openEnd) {
  var node = side < 0 ? fragment.firstChild : fragment.lastChild,
      inner = node.content;

  if (depth < to - 1) {
    inner = closeRange(inner, side, from, to, depth + 1, openEnd);
  }

  if (depth >= from) {
    inner = side < 0 ? node.contentMatchAt(0).fillBefore(inner, fragment.childCount > 1 || openEnd <= depth).append(inner) : inner.append(node.contentMatchAt(node.childCount).fillBefore(_prosemirrorModel.Fragment.empty, true));
  }

  return fragment.replaceChild(side < 0 ? 0 : fragment.childCount - 1, node.copy(inner));
}

function closeSlice(slice, openStart, openEnd) {
  if (openStart < slice.openStart) {
    slice = new _prosemirrorModel.Slice(closeRange(slice.content, -1, openStart, slice.openStart, 0, slice.openEnd), openStart, slice.openEnd);
  }

  if (openEnd < slice.openEnd) {
    slice = new _prosemirrorModel.Slice(closeRange(slice.content, 1, openEnd, slice.openEnd, 0, 0), slice.openStart, openEnd);
  }

  return slice;
} // Trick from jQuery -- some elements must be wrapped in other
// elements for innerHTML to work. I.e. if you do `div.innerHTML =
// "<td>..</td>"` the table cells are ignored.


var wrapMap = {
  thead: ["table"],
  tbody: ["table"],
  tfoot: ["table"],
  caption: ["table"],
  colgroup: ["table"],
  col: ["table", "colgroup"],
  tr: ["table", "tbody"],
  td: ["table", "tbody", "tr"],
  th: ["table", "tbody", "tr"]
};
var _detachedDoc = null;

function detachedDoc() {
  return _detachedDoc || (_detachedDoc = document.implementation.createHTMLDocument("title"));
}

function readHTML(html) {
  var metas = /(\s*<meta [^>]*>)*/.exec(html);

  if (metas) {
    html = html.slice(metas[0].length);
  }

  var elt = detachedDoc().createElement("div");
  var firstTag = /(?:<meta [^>]*>)*<([a-z][^>\s]+)/i.exec(html),
      wrap,
      depth = 0;

  if (wrap = firstTag && wrapMap[firstTag[1].toLowerCase()]) {
    html = wrap.map(function (n) {
      return "<" + n + ">";
    }).join("") + html + wrap.map(function (n) {
      return "</" + n + ">";
    }).reverse().join("");
    depth = wrap.length;
  }

  elt.innerHTML = html;

  for (var i = 0; i < depth; i++) {
    elt = elt.firstChild;
  }

  return elt;
}

function addContext(slice, context) {
  if (!slice.size) {
    return slice;
  }

  var schema = slice.content.firstChild.type.schema,
      array;

  try {
    array = JSON.parse(context);
  } catch (e) {
    return slice;
  }

  var content = slice.content;
  var openStart = slice.openStart;
  var openEnd = slice.openEnd;

  for (var i = array.length - 2; i >= 0; i -= 2) {
    var type = schema.nodes[array[i]];

    if (!type || type.hasRequiredAttrs()) {
      break;
    }

    content = _prosemirrorModel.Fragment.from(type.create(array[i + 1], content));
    openStart++;
    openEnd++;
  }

  return new _prosemirrorModel.Slice(content, openStart, openEnd);
}

var observeOptions = {
  childList: true,
  characterData: true,
  characterDataOldValue: true,
  attributes: true,
  attributeOldValue: true,
  subtree: true
}; // IE11 has very broken mutation observers, so we also listen to DOMCharacterDataModified

var useCharData = result.ie && result.ie_version <= 11;

var SelectionState = function SelectionState() {
  this.anchorNode = this.anchorOffset = this.focusNode = this.focusOffset = null;
};

SelectionState.prototype.set = function set(sel) {
  this.anchorNode = sel.anchorNode;
  this.anchorOffset = sel.anchorOffset;
  this.focusNode = sel.focusNode;
  this.focusOffset = sel.focusOffset;
};

SelectionState.prototype.eq = function eq(sel) {
  return sel.anchorNode == this.anchorNode && sel.anchorOffset == this.anchorOffset && sel.focusNode == this.focusNode && sel.focusOffset == this.focusOffset;
};

var DOMObserver = function DOMObserver(view, handleDOMChange) {
  var this$1 = this;
  this.view = view;
  this.handleDOMChange = handleDOMChange;
  this.queue = [];
  this.flushingSoon = -1;
  this.observer = window.MutationObserver && new window.MutationObserver(function (mutations) {
    for (var i = 0; i < mutations.length; i++) {
      this$1.queue.push(mutations[i]);
    } // IE11 will sometimes (on backspacing out a single character
    // text node after a BR node) call the observer callback
    // before actually updating the DOM, which will cause
    // ProseMirror to miss the change (see #930)


    if (result.ie && result.ie_version <= 11 && mutations.some(function (m) {
      return m.type == "childList" && m.removedNodes.length || m.type == "characterData" && m.oldValue.length > m.target.nodeValue.length;
    })) {
      this$1.flushSoon();
    } else {
      this$1.flush();
    }
  });
  this.currentSelection = new SelectionState();

  if (useCharData) {
    this.onCharData = function (e) {
      this$1.queue.push({
        target: e.target,
        type: "characterData",
        oldValue: e.prevValue
      });
      this$1.flushSoon();
    };
  }

  this.onSelectionChange = this.onSelectionChange.bind(this);
  this.suppressingSelectionUpdates = false;
};

DOMObserver.prototype.flushSoon = function flushSoon() {
  var this$1 = this;

  if (this.flushingSoon < 0) {
    this.flushingSoon = window.setTimeout(function () {
      this$1.flushingSoon = -1;
      this$1.flush();
    }, 20);
  }
};

DOMObserver.prototype.forceFlush = function forceFlush() {
  if (this.flushingSoon > -1) {
    window.clearTimeout(this.flushingSoon);
    this.flushingSoon = -1;
    this.flush();
  }
};

DOMObserver.prototype.start = function start() {
  if (this.observer) {
    this.observer.observe(this.view.dom, observeOptions);
  }

  if (useCharData) {
    this.view.dom.addEventListener("DOMCharacterDataModified", this.onCharData);
  }

  this.connectSelection();
};

DOMObserver.prototype.stop = function stop() {
  var this$1 = this;

  if (this.observer) {
    var take = this.observer.takeRecords();

    if (take.length) {
      for (var i = 0; i < take.length; i++) {
        this.queue.push(take[i]);
      }

      window.setTimeout(function () {
        return this$1.flush();
      }, 20);
    }

    this.observer.disconnect();
  }

  if (useCharData) {
    this.view.dom.removeEventListener("DOMCharacterDataModified", this.onCharData);
  }

  this.disconnectSelection();
};

DOMObserver.prototype.connectSelection = function connectSelection() {
  this.view.dom.ownerDocument.addEventListener("selectionchange", this.onSelectionChange);
};

DOMObserver.prototype.disconnectSelection = function disconnectSelection() {
  this.view.dom.ownerDocument.removeEventListener("selectionchange", this.onSelectionChange);
};

DOMObserver.prototype.suppressSelectionUpdates = function suppressSelectionUpdates() {
  var this$1 = this;
  this.suppressingSelectionUpdates = true;
  setTimeout(function () {
    return this$1.suppressingSelectionUpdates = false;
  }, 50);
};

DOMObserver.prototype.onSelectionChange = function onSelectionChange() {
  if (!hasFocusAndSelection(this.view)) {
    return;
  }

  if (this.suppressingSelectionUpdates) {
    return selectionToDOM(this.view);
  } // Deletions on IE11 fire their events in the wrong order, giving
  // us a selection change event before the DOM changes are
  // reported.


  if (result.ie && result.ie_version <= 11 && !this.view.state.selection.empty) {
    var sel = this.view.root.getSelection(); // Selection.isCollapsed isn't reliable on IE

    if (sel.focusNode && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset)) {
      return this.flushSoon();
    }
  }

  this.flush();
};

DOMObserver.prototype.setCurSelection = function setCurSelection() {
  this.currentSelection.set(this.view.root.getSelection());
};

DOMObserver.prototype.ignoreSelectionChange = function ignoreSelectionChange(sel) {
  if (sel.rangeCount == 0) {
    return true;
  }

  var container = sel.getRangeAt(0).commonAncestorContainer;
  var desc = this.view.docView.nearestDesc(container);

  if (desc && desc.ignoreMutation({
    type: "selection",
    target: container.nodeType == 3 ? container.parentNode : container
  })) {
    this.setCurSelection();
    return true;
  }
};

DOMObserver.prototype.flush = function flush() {
  if (!this.view.docView || this.flushingSoon > -1) {
    return;
  }

  var mutations = this.observer ? this.observer.takeRecords() : [];

  if (this.queue.length) {
    mutations = this.queue.concat(mutations);
    this.queue.length = 0;
  }

  var sel = this.view.root.getSelection();
  var newSel = !this.suppressingSelectionUpdates && !this.currentSelection.eq(sel) && hasSelection(this.view) && !this.ignoreSelectionChange(sel);
  var from = -1,
      to = -1,
      typeOver = false,
      added = [];

  if (this.view.editable) {
    for (var i = 0; i < mutations.length; i++) {
      var result$1 = this.registerMutation(mutations[i], added);

      if (result$1) {
        from = from < 0 ? result$1.from : Math.min(result$1.from, from);
        to = to < 0 ? result$1.to : Math.max(result$1.to, to);

        if (result$1.typeOver) {
          typeOver = true;
        }
      }
    }
  }

  if (result.gecko && added.length > 1) {
    var brs = added.filter(function (n) {
      return n.nodeName == "BR";
    });

    if (brs.length == 2) {
      var a = brs[0];
      var b = brs[1];

      if (a.parentNode && a.parentNode.parentNode == b.parentNode) {
        b.remove();
      } else {
        a.remove();
      }
    }
  }

  if (from > -1 || newSel) {
    if (from > -1) {
      this.view.docView.markDirty(from, to);
      checkCSS(this.view);
    }

    this.handleDOMChange(from, to, typeOver, added);

    if (this.view.docView.dirty) {
      this.view.updateState(this.view.state);
    } else if (!this.currentSelection.eq(sel)) {
      selectionToDOM(this.view);
    }
  }
};

DOMObserver.prototype.registerMutation = function registerMutation(mut, added) {
  // Ignore mutations inside nodes that were already noted as inserted
  if (added.indexOf(mut.target) > -1) {
    return null;
  }

  var desc = this.view.docView.nearestDesc(mut.target);

  if (mut.type == "attributes" && (desc == this.view.docView || mut.attributeName == "contenteditable" || // Firefox sometimes fires spurious events for null/empty styles
  mut.attributeName == "style" && !mut.oldValue && !mut.target.getAttribute("style"))) {
    return null;
  }

  if (!desc || desc.ignoreMutation(mut)) {
    return null;
  }

  if (mut.type == "childList") {
    var prev = mut.previousSibling,
        next = mut.nextSibling;

    if (result.ie && result.ie_version <= 11 && mut.addedNodes.length) {
      // IE11 gives us incorrect next/prev siblings for some
      // insertions, so if there are added nodes, recompute those
      for (var i = 0; i < mut.addedNodes.length; i++) {
        var ref = mut.addedNodes[i];
        var previousSibling = ref.previousSibling;
        var nextSibling = ref.nextSibling;

        if (!previousSibling || Array.prototype.indexOf.call(mut.addedNodes, previousSibling) < 0) {
          prev = previousSibling;
        }

        if (!nextSibling || Array.prototype.indexOf.call(mut.addedNodes, nextSibling) < 0) {
          next = nextSibling;
        }
      }
    }

    var fromOffset = prev && prev.parentNode == mut.target ? domIndex(prev) + 1 : 0;
    var from = desc.localPosFromDOM(mut.target, fromOffset, -1);
    var toOffset = next && next.parentNode == mut.target ? domIndex(next) : mut.target.childNodes.length;

    for (var i$1 = 0; i$1 < mut.addedNodes.length; i$1++) {
      added.push(mut.addedNodes[i$1]);
    }

    var to = desc.localPosFromDOM(mut.target, toOffset, 1);
    return {
      from: from,
      to: to
    };
  } else if (mut.type == "attributes") {
    return {
      from: desc.posAtStart - desc.border,
      to: desc.posAtEnd + desc.border
    };
  } else {
    // "characterData"
    return {
      from: desc.posAtStart,
      to: desc.posAtEnd,
      // An event was generated for a text change that didn't change
      // any text. Mark the dom change to fall back to assuming the
      // selection was typed over with an identical value if it can't
      // find another change.
      typeOver: mut.target.nodeValue == mut.oldValue
    };
  }
};

var cssChecked = false;

function checkCSS(view) {
  if (cssChecked) {
    return;
  }

  cssChecked = true;

  if (getComputedStyle(view.dom).whiteSpace == "normal") {
    console["warn"]("ProseMirror expects the CSS white-space property to be set, preferably to 'pre-wrap'. It is recommended to load style/prosemirror.css from the prosemirror-view package.");
  }
} // A collection of DOM events that occur within the editor, and callback functions
// to invoke when the event fires.


var handlers = {},
    editHandlers = {};

function initInput(view) {
  view.shiftKey = false;
  view.mouseDown = null;
  view.lastKeyCode = null;
  view.lastKeyCodeTime = 0;
  view.lastClick = {
    time: 0,
    x: 0,
    y: 0,
    type: ""
  };
  view.lastSelectionOrigin = null;
  view.lastSelectionTime = 0;
  view.lastIOSEnter = 0;
  view.composing = false;
  view.composingTimeout = null;
  view.compositionNodes = [];
  view.compositionEndedAt = -2e8;
  view.domObserver = new DOMObserver(view, function (from, to, typeOver, added) {
    return readDOMChange(view, from, to, typeOver, added);
  });
  view.domObserver.start(); // Used by hacks like the beforeinput handler to check whether anything happened in the DOM

  view.domChangeCount = 0;
  view.eventHandlers = Object.create(null);

  var loop = function (event) {
    var handler = handlers[event];
    view.dom.addEventListener(event, view.eventHandlers[event] = function (event) {
      if (eventBelongsToView(view, event) && !runCustomHandler(view, event) && (view.editable || !(event.type in editHandlers))) {
        handler(view, event);
      }
    });
  };

  for (var event in handlers) loop(event); // On Safari, for reasons beyond my understanding, adding an input
  // event handler makes an issue where the composition vanishes when
  // you press enter go away.


  if (result.safari) {
    view.dom.addEventListener("input", function () {
      return null;
    });
  }

  ensureListeners(view);
}

function setSelectionOrigin(view, origin) {
  view.lastSelectionOrigin = origin;
  view.lastSelectionTime = Date.now();
}

function destroyInput(view) {
  view.domObserver.stop();

  for (var type in view.eventHandlers) {
    view.dom.removeEventListener(type, view.eventHandlers[type]);
  }

  clearTimeout(view.composingTimeout);
}

function ensureListeners(view) {
  view.someProp("handleDOMEvents", function (currentHandlers) {
    for (var type in currentHandlers) {
      if (!view.eventHandlers[type]) {
        view.dom.addEventListener(type, view.eventHandlers[type] = function (event) {
          return runCustomHandler(view, event);
        });
      }
    }
  });
}

function runCustomHandler(view, event) {
  return view.someProp("handleDOMEvents", function (handlers) {
    var handler = handlers[event.type];
    return handler ? handler(view, event) || event.defaultPrevented : false;
  });
}

function eventBelongsToView(view, event) {
  if (!event.bubbles) {
    return true;
  }

  if (event.defaultPrevented) {
    return false;
  }

  for (var node = event.target; node != view.dom; node = node.parentNode) {
    if (!node || node.nodeType == 11 || node.pmViewDesc && node.pmViewDesc.stopEvent(event)) {
      return false;
    }
  }

  return true;
}

function dispatchEvent(view, event) {
  if (!runCustomHandler(view, event) && handlers[event.type] && (view.editable || !(event.type in editHandlers))) {
    handlers[event.type](view, event);
  }
}

editHandlers.keydown = function (view, event) {
  view.shiftKey = event.keyCode == 16 || event.shiftKey;

  if (inOrNearComposition(view, event)) {
    return;
  }

  view.domObserver.forceFlush();
  view.lastKeyCode = event.keyCode;
  view.lastKeyCodeTime = Date.now(); // On iOS, if we preventDefault enter key presses, the virtual
  // keyboard gets confused. So the hack here is to set a flag that
  // makes the DOM change code recognize that what just happens should
  // be replaced by whatever the Enter key handlers do.

  if (result.ios && event.keyCode == 13 && !event.ctrlKey && !event.altKey && !event.metaKey) {
    var now = Date.now();
    view.lastIOSEnter = now;
    setTimeout(function () {
      if (view.lastIOSEnter == now) {
        view.someProp("handleKeyDown", function (f) {
          return f(view, keyEvent(13, "Enter"));
        });
        view.lastIOSEnter = 0;
      }
    }, 50);
  } else if (view.someProp("handleKeyDown", function (f) {
    return f(view, event);
  }) || captureKeyDown(view, event)) {
    event.preventDefault();
  } else {
    setSelectionOrigin(view, "key");
  }
};

editHandlers.keyup = function (view, e) {
  if (e.keyCode == 16) {
    view.shiftKey = false;
  }
};

editHandlers.keypress = function (view, event) {
  if (inOrNearComposition(view, event) || !event.charCode || event.ctrlKey && !event.altKey || result.mac && event.metaKey) {
    return;
  }

  if (view.someProp("handleKeyPress", function (f) {
    return f(view, event);
  })) {
    event.preventDefault();
    return;
  }

  var sel = view.state.selection;

  if (!(sel instanceof _prosemirrorState.TextSelection) || !sel.$from.sameParent(sel.$to)) {
    var text = String.fromCharCode(event.charCode);

    if (!view.someProp("handleTextInput", function (f) {
      return f(view, sel.$from.pos, sel.$to.pos, text);
    })) {
      view.dispatch(view.state.tr.insertText(text).scrollIntoView());
    }

    event.preventDefault();
  }
};

function eventCoords(event) {
  return {
    left: event.clientX,
    top: event.clientY
  };
}

function isNear(event, click) {
  var dx = click.x - event.clientX,
      dy = click.y - event.clientY;
  return dx * dx + dy * dy < 100;
}

function runHandlerOnContext(view, propName, pos, inside, event) {
  if (inside == -1) {
    return false;
  }

  var $pos = view.state.doc.resolve(inside);

  var loop = function (i) {
    if (view.someProp(propName, function (f) {
      return i > $pos.depth ? f(view, pos, $pos.nodeAfter, $pos.before(i), event, true) : f(view, pos, $pos.node(i), $pos.before(i), event, false);
    })) {
      return {
        v: true
      };
    }
  };

  for (var i = $pos.depth + 1; i > 0; i--) {
    var returned = loop(i);
    if (returned) return returned.v;
  }

  return false;
}

function updateSelection(view, selection, origin) {
  if (!view.focused) {
    view.focus();
  }

  var tr = view.state.tr.setSelection(selection);

  if (origin == "pointer") {
    tr.setMeta("pointer", true);
  }

  view.dispatch(tr);
}

function selectClickedLeaf(view, inside) {
  if (inside == -1) {
    return false;
  }

  var $pos = view.state.doc.resolve(inside),
      node = $pos.nodeAfter;

  if (node && node.isAtom && _prosemirrorState.NodeSelection.isSelectable(node)) {
    updateSelection(view, new _prosemirrorState.NodeSelection($pos), "pointer");
    return true;
  }

  return false;
}

function selectClickedNode(view, inside) {
  if (inside == -1) {
    return false;
  }

  var sel = view.state.selection,
      selectedNode,
      selectAt;

  if (sel instanceof _prosemirrorState.NodeSelection) {
    selectedNode = sel.node;
  }

  var $pos = view.state.doc.resolve(inside);

  for (var i = $pos.depth + 1; i > 0; i--) {
    var node = i > $pos.depth ? $pos.nodeAfter : $pos.node(i);

    if (_prosemirrorState.NodeSelection.isSelectable(node)) {
      if (selectedNode && sel.$from.depth > 0 && i >= sel.$from.depth && $pos.before(sel.$from.depth + 1) == sel.$from.pos) {
        selectAt = $pos.before(sel.$from.depth);
      } else {
        selectAt = $pos.before(i);
      }

      break;
    }
  }

  if (selectAt != null) {
    updateSelection(view, _prosemirrorState.NodeSelection.create(view.state.doc, selectAt), "pointer");
    return true;
  } else {
    return false;
  }
}

function handleSingleClick(view, pos, inside, event, selectNode) {
  return runHandlerOnContext(view, "handleClickOn", pos, inside, event) || view.someProp("handleClick", function (f) {
    return f(view, pos, event);
  }) || (selectNode ? selectClickedNode(view, inside) : selectClickedLeaf(view, inside));
}

function handleDoubleClick(view, pos, inside, event) {
  return runHandlerOnContext(view, "handleDoubleClickOn", pos, inside, event) || view.someProp("handleDoubleClick", function (f) {
    return f(view, pos, event);
  });
}

function handleTripleClick(view, pos, inside, event) {
  return runHandlerOnContext(view, "handleTripleClickOn", pos, inside, event) || view.someProp("handleTripleClick", function (f) {
    return f(view, pos, event);
  }) || defaultTripleClick(view, inside);
}

function defaultTripleClick(view, inside) {
  var doc = view.state.doc;

  if (inside == -1) {
    if (doc.inlineContent) {
      updateSelection(view, _prosemirrorState.TextSelection.create(doc, 0, doc.content.size), "pointer");
      return true;
    }

    return false;
  }

  var $pos = doc.resolve(inside);

  for (var i = $pos.depth + 1; i > 0; i--) {
    var node = i > $pos.depth ? $pos.nodeAfter : $pos.node(i);
    var nodePos = $pos.before(i);

    if (node.inlineContent) {
      updateSelection(view, _prosemirrorState.TextSelection.create(doc, nodePos + 1, nodePos + 1 + node.content.size), "pointer");
    } else if (_prosemirrorState.NodeSelection.isSelectable(node)) {
      updateSelection(view, _prosemirrorState.NodeSelection.create(doc, nodePos), "pointer");
    } else {
      continue;
    }

    return true;
  }
}

function forceDOMFlush(view) {
  return endComposition(view);
}

var selectNodeModifier = result.mac ? "metaKey" : "ctrlKey";

handlers.mousedown = function (view, event) {
  view.shiftKey = event.shiftKey;
  var flushed = forceDOMFlush(view);
  var now = Date.now(),
      type = "singleClick";

  if (now - view.lastClick.time < 500 && isNear(event, view.lastClick) && !event[selectNodeModifier]) {
    if (view.lastClick.type == "singleClick") {
      type = "doubleClick";
    } else if (view.lastClick.type == "doubleClick") {
      type = "tripleClick";
    }
  }

  view.lastClick = {
    time: now,
    x: event.clientX,
    y: event.clientY,
    type: type
  };
  var pos = view.posAtCoords(eventCoords(event));

  if (!pos) {
    return;
  }

  if (type == "singleClick") {
    view.mouseDown = new MouseDown(view, pos, event, flushed);
  } else if ((type == "doubleClick" ? handleDoubleClick : handleTripleClick)(view, pos.pos, pos.inside, event)) {
    event.preventDefault();
  } else {
    setSelectionOrigin(view, "pointer");
  }
};

var MouseDown = function MouseDown(view, pos, event, flushed) {
  var this$1 = this;
  this.view = view;
  this.startDoc = view.state.doc;
  this.pos = pos;
  this.event = event;
  this.flushed = flushed;
  this.selectNode = event[selectNodeModifier];
  this.allowDefault = event.shiftKey;
  var targetNode, targetPos;

  if (pos.inside > -1) {
    targetNode = view.state.doc.nodeAt(pos.inside);
    targetPos = pos.inside;
  } else {
    var $pos = view.state.doc.resolve(pos.pos);
    targetNode = $pos.parent;
    targetPos = $pos.depth ? $pos.before() : 0;
  }

  this.mightDrag = null;
  var target = flushed ? null : event.target;
  var targetDesc = target ? view.docView.nearestDesc(target, true) : null;
  this.target = targetDesc ? targetDesc.dom : null;

  if (targetNode.type.spec.draggable && targetNode.type.spec.selectable !== false || view.state.selection instanceof _prosemirrorState.NodeSelection && targetPos == view.state.selection.from) {
    this.mightDrag = {
      node: targetNode,
      pos: targetPos,
      addAttr: this.target && !this.target.draggable,
      setUneditable: this.target && result.gecko && !this.target.hasAttribute("contentEditable")
    };
  }

  if (this.target && this.mightDrag && (this.mightDrag.addAttr || this.mightDrag.setUneditable)) {
    this.view.domObserver.stop();

    if (this.mightDrag.addAttr) {
      this.target.draggable = true;
    }

    if (this.mightDrag.setUneditable) {
      setTimeout(function () {
        return this$1.target.setAttribute("contentEditable", "false");
      }, 20);
    }

    this.view.domObserver.start();
  }

  view.root.addEventListener("mouseup", this.up = this.up.bind(this));
  view.root.addEventListener("mousemove", this.move = this.move.bind(this));
  setSelectionOrigin(view, "pointer");
};

MouseDown.prototype.done = function done() {
  this.view.root.removeEventListener("mouseup", this.up);
  this.view.root.removeEventListener("mousemove", this.move);

  if (this.mightDrag && this.target) {
    this.view.domObserver.stop();

    if (this.mightDrag.addAttr) {
      this.target.removeAttribute("draggable");
    }

    if (this.mightDrag.setUneditable) {
      this.target.removeAttribute("contentEditable");
    }

    this.view.domObserver.start();
  }

  this.view.mouseDown = null;
};

MouseDown.prototype.up = function up(event) {
  this.done();

  if (!this.view.dom.contains(event.target.nodeType == 3 ? event.target.parentNode : event.target)) {
    return;
  }

  var pos = this.pos;

  if (this.view.state.doc != this.startDoc) {
    pos = this.view.posAtCoords(eventCoords(event));
  }

  if (this.allowDefault || !pos) {
    setSelectionOrigin(this.view, "pointer");
  } else if (handleSingleClick(this.view, pos.pos, pos.inside, event, this.selectNode)) {
    event.preventDefault();
  } else if (this.flushed || // Safari ignores clicks on draggable elements
  result.safari && this.mightDrag && !this.mightDrag.node.isAtom || // Chrome will sometimes treat a node selection as a
  // cursor, but still report that the node is selected
  // when asked through getSelection. You'll then get a
  // situation where clicking at the point where that
  // (hidden) cursor is doesn't change the selection, and
  // thus doesn't get a reaction from ProseMirror. This
  // works around that.
  result.chrome && !(this.view.state.selection instanceof _prosemirrorState.TextSelection) && (pos.pos == this.view.state.selection.from || pos.pos == this.view.state.selection.to)) {
    updateSelection(this.view, _prosemirrorState.Selection.near(this.view.state.doc.resolve(pos.pos)), "pointer");
    event.preventDefault();
  } else {
    setSelectionOrigin(this.view, "pointer");
  }
};

MouseDown.prototype.move = function move(event) {
  if (!this.allowDefault && (Math.abs(this.event.x - event.clientX) > 4 || Math.abs(this.event.y - event.clientY) > 4)) {
    this.allowDefault = true;
  }

  setSelectionOrigin(this.view, "pointer");
};

handlers.touchdown = function (view) {
  forceDOMFlush(view);
  setSelectionOrigin(view, "pointer");
};

handlers.contextmenu = function (view) {
  return forceDOMFlush(view);
};

function inOrNearComposition(view, event) {
  if (view.composing) {
    return true;
  } // See https://www.stum.de/2016/06/24/handling-ime-events-in-javascript/.
  // On Japanese input method editors (IMEs), the Enter key is used to confirm character
  // selection. On Safari, when Enter is pressed, compositionend and keydown events are
  // emitted. The keydown event triggers newline insertion, which we don't want.
  // This method returns true if the keydown event should be ignored.
  // We only ignore it once, as pressing Enter a second time *should* insert a newline.
  // Furthermore, the keydown event timestamp must be close to the compositionEndedAt timestamp.
  // This guards against the case where compositionend is triggered without the keyboard
  // (e.g. character confirmation may be done with the mouse), and keydown is triggered
  // afterwards- we wouldn't want to ignore the keydown event in this case.


  if (result.safari && Math.abs(event.timeStamp - view.compositionEndedAt) < 500) {
    view.compositionEndedAt = -2e8;
    return true;
  }

  return false;
} // Drop active composition after 5 seconds of inactivity on Android


var timeoutComposition = result.android ? 5000 : -1;

editHandlers.compositionstart = editHandlers.compositionupdate = function (view) {
  if (!view.composing) {
    view.domObserver.flush();
    var state = view.state;
    var $pos = state.selection.$from;

    if (state.selection.empty && (state.storedMarks || !$pos.textOffset && $pos.parentOffset && $pos.nodeBefore.marks.some(function (m) {
      return m.type.spec.inclusive === false;
    }))) {
      // Need to wrap the cursor in mark nodes different from the ones in the DOM context
      view.markCursor = view.state.storedMarks || $pos.marks();
      endComposition(view, true);
      view.markCursor = null;
    } else {
      endComposition(view); // In firefox, if the cursor is after but outside a marked node,
      // the inserted text won't inherit the marks. So this moves it
      // inside if necessary.

      if (result.gecko && state.selection.empty && $pos.parentOffset && !$pos.textOffset && $pos.nodeBefore.marks.length) {
        var sel = view.root.getSelection();

        for (var node = sel.focusNode, offset = sel.focusOffset; node && node.nodeType == 1 && offset != 0;) {
          var before = offset < 0 ? node.lastChild : node.childNodes[offset - 1];

          if (!before) {
            break;
          }

          if (before.nodeType == 3) {
            sel.collapse(before, before.nodeValue.length);
            break;
          } else {
            node = before;
            offset = -1;
          }
        }
      }
    }

    view.composing = true;
  }

  scheduleComposeEnd(view, timeoutComposition);
};

editHandlers.compositionend = function (view, event) {
  if (view.composing) {
    view.composing = false;
    view.compositionEndedAt = event.timeStamp;
    scheduleComposeEnd(view, 20);
  }
};

function scheduleComposeEnd(view, delay) {
  clearTimeout(view.composingTimeout);

  if (delay > -1) {
    view.composingTimeout = setTimeout(function () {
      return endComposition(view);
    }, delay);
  }
}

function endComposition(view, forceUpdate) {
  view.domObserver.forceFlush();
  view.composing = false;

  while (view.compositionNodes.length > 0) {
    view.compositionNodes.pop().markParentsDirty();
  }

  if (forceUpdate || view.docView.dirty) {
    var sel = selectionFromDOM(view);

    if (!sel.eq(view.state.selection)) {
      view.dispatch(view.state.tr.setSelection(sel));
    } else {
      view.updateState(view.state);
    }

    return true;
  }

  return false;
}

function captureCopy(view, dom) {
  // The extra wrapper is somehow necessary on IE/Edge to prevent the
  // content from being mangled when it is put onto the clipboard
  var doc = view.dom.ownerDocument;
  var wrap = doc.body.appendChild(doc.createElement("div"));
  wrap.appendChild(dom);
  wrap.style.cssText = "position: fixed; left: -10000px; top: 10px";
  var sel = getSelection(),
      range = doc.createRange();
  range.selectNodeContents(dom); // Done because IE will fire a selectionchange moving the selection
  // to its start when removeAllRanges is called and the editor still
  // has focus (which will mess up the editor's selection state).

  view.dom.blur();
  sel.removeAllRanges();
  sel.addRange(range);
  setTimeout(function () {
    doc.body.removeChild(wrap);
    view.focus();
  }, 50);
} // This is very crude, but unfortunately both these browsers _pretend_
// that they have a clipboard API—all the objects and methods are
// there, they just don't work, and they are hard to test.


var brokenClipboardAPI = result.ie && result.ie_version < 15 || result.ios && result.webkit_version < 604;

handlers.copy = editHandlers.cut = function (view, e) {
  var sel = view.state.selection,
      cut = e.type == "cut";

  if (sel.empty) {
    return;
  } // IE and Edge's clipboard interface is completely broken


  var data = brokenClipboardAPI ? null : e.clipboardData;
  var slice = sel.content();
  var ref = serializeForClipboard(view, slice);
  var dom = ref.dom;
  var text = ref.text;

  if (data) {
    e.preventDefault();
    data.clearData();
    data.setData("text/html", dom.innerHTML);
    data.setData("text/plain", text);
  } else {
    captureCopy(view, dom);
  }

  if (cut) {
    view.dispatch(view.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent", "cut"));
  }
};

function sliceSingleNode(slice) {
  return slice.openStart == 0 && slice.openEnd == 0 && slice.content.childCount == 1 ? slice.content.firstChild : null;
}

function capturePaste(view, e) {
  var doc = view.dom.ownerDocument;
  var plainText = view.shiftKey || view.state.selection.$from.parent.type.spec.code;
  var target = doc.body.appendChild(doc.createElement(plainText ? "textarea" : "div"));

  if (!plainText) {
    target.contentEditable = "true";
  }

  target.style.cssText = "position: fixed; left: -10000px; top: 10px";
  target.focus();
  setTimeout(function () {
    view.focus();
    doc.body.removeChild(target);

    if (plainText) {
      doPaste(view, target.value, null, e);
    } else {
      doPaste(view, target.textContent, target.innerHTML, e);
    }
  }, 50);
}

function doPaste(view, text, html, e) {
  var slice = parseFromClipboard(view, text, html, view.shiftKey, view.state.selection.$from);

  if (view.someProp("handlePaste", function (f) {
    return f(view, e, slice || _prosemirrorModel.Slice.empty);
  }) || !slice) {
    return;
  }

  var singleNode = sliceSingleNode(slice);
  var tr = singleNode ? view.state.tr.replaceSelectionWith(singleNode, view.shiftKey) : view.state.tr.replaceSelection(slice);
  view.dispatch(tr.scrollIntoView().setMeta("paste", true).setMeta("uiEvent", "paste"));
}

editHandlers.paste = function (view, e) {
  var data = brokenClipboardAPI ? null : e.clipboardData;
  var html = data && data.getData("text/html"),
      text = data && data.getData("text/plain");

  if (data && (html || text || data.files.length)) {
    doPaste(view, text, html, e);
    e.preventDefault();
  } else {
    capturePaste(view, e);
  }
};

var Dragging = function Dragging(slice, move) {
  this.slice = slice;
  this.move = move;
};

var dragCopyModifier = result.mac ? "altKey" : "ctrlKey";

handlers.dragstart = function (view, e) {
  var mouseDown = view.mouseDown;

  if (mouseDown) {
    mouseDown.done();
  }

  if (!e.dataTransfer) {
    return;
  }

  var sel = view.state.selection;
  var pos = sel.empty ? null : view.posAtCoords(eventCoords(e));
  if (pos && pos.pos >= sel.from && pos.pos <= (sel instanceof _prosemirrorState.NodeSelection ? sel.to - 1 : sel.to)) ;else if (mouseDown && mouseDown.mightDrag) {
    view.dispatch(view.state.tr.setSelection(_prosemirrorState.NodeSelection.create(view.state.doc, mouseDown.mightDrag.pos)));
  } else if (e.target && e.target.nodeType == 1) {
    var desc = view.docView.nearestDesc(e.target, true);

    if (!desc || !desc.node.type.spec.draggable || desc == view.docView) {
      return;
    }

    view.dispatch(view.state.tr.setSelection(_prosemirrorState.NodeSelection.create(view.state.doc, desc.posBefore)));
  }
  var slice = view.state.selection.content();
  var ref = serializeForClipboard(view, slice);
  var dom = ref.dom;
  var text = ref.text;
  e.dataTransfer.clearData();
  e.dataTransfer.setData(brokenClipboardAPI ? "Text" : "text/html", dom.innerHTML);

  if (!brokenClipboardAPI) {
    e.dataTransfer.setData("text/plain", text);
  }

  view.dragging = new Dragging(slice, !e[dragCopyModifier]);
};

handlers.dragend = function (view) {
  window.setTimeout(function () {
    return view.dragging = null;
  }, 50);
};

editHandlers.dragover = editHandlers.dragenter = function (_, e) {
  return e.preventDefault();
};

editHandlers.drop = function (view, e) {
  var dragging = view.dragging;
  view.dragging = null;

  if (!e.dataTransfer) {
    return;
  }

  var eventPos = view.posAtCoords(eventCoords(e));

  if (!eventPos) {
    return;
  }

  var $mouse = view.state.doc.resolve(eventPos.pos);

  if (!$mouse) {
    return;
  }

  var slice = dragging && dragging.slice || parseFromClipboard(view, e.dataTransfer.getData(brokenClipboardAPI ? "Text" : "text/plain"), brokenClipboardAPI ? null : e.dataTransfer.getData("text/html"), false, $mouse);

  if (view.someProp("handleDrop", function (f) {
    return f(view, e, slice || _prosemirrorModel.Slice.empty, dragging && dragging.move);
  })) {
    e.preventDefault();
    return;
  }

  if (!slice) {
    return;
  }

  e.preventDefault();
  var insertPos = slice ? (0, _prosemirrorTransform.dropPoint)(view.state.doc, $mouse.pos, slice) : $mouse.pos;

  if (insertPos == null) {
    insertPos = $mouse.pos;
  }

  var tr = view.state.tr;

  if (dragging && dragging.move) {
    tr.deleteSelection();
  }

  var pos = tr.mapping.map(insertPos);
  var isNode = slice.openStart == 0 && slice.openEnd == 0 && slice.content.childCount == 1;
  var beforeInsert = tr.doc;

  if (isNode) {
    tr.replaceRangeWith(pos, pos, slice.content.firstChild);
  } else {
    tr.replaceRange(pos, pos, slice);
  }

  if (tr.doc.eq(beforeInsert)) {
    return;
  }

  var $pos = tr.doc.resolve(pos);

  if (isNode && _prosemirrorState.NodeSelection.isSelectable(slice.content.firstChild) && $pos.nodeAfter && $pos.nodeAfter.sameMarkup(slice.content.firstChild)) {
    tr.setSelection(new _prosemirrorState.NodeSelection($pos));
  } else {
    tr.setSelection(selectionBetween(view, $pos, tr.doc.resolve(tr.mapping.map(insertPos))));
  }

  view.focus();
  view.dispatch(tr.setMeta("uiEvent", "drop"));
};

handlers.focus = function (view) {
  if (!view.focused) {
    view.domObserver.stop();
    view.dom.classList.add("ProseMirror-focused");
    view.domObserver.start();
    view.focused = true;
    setTimeout(function () {
      if (view.docView && view.hasFocus() && !view.domObserver.currentSelection.eq(view.root.getSelection())) {
        selectionToDOM(view);
      }
    }, 20);
  }
};

handlers.blur = function (view) {
  if (view.focused) {
    view.domObserver.stop();
    view.dom.classList.remove("ProseMirror-focused");
    view.domObserver.start();
    view.domObserver.currentSelection.set({});
    view.focused = false;
  }
};

handlers.beforeinput = function (view, event) {
  // We should probably do more with beforeinput events, but support
  // is so spotty that I'm still waiting to see where they are going.
  // Very specific hack to deal with backspace sometimes failing on
  // Chrome Android when after an uneditable node.
  if (result.chrome && result.android && event.inputType == "deleteContentBackward") {
    var domChangeCount = view.domChangeCount;
    setTimeout(function () {
      if (view.domChangeCount != domChangeCount) {
        return;
      } // Event already had some effect
      // This bug tends to close the virtual keyboard, so we refocus


      view.dom.blur();
      view.focus();

      if (view.someProp("handleKeyDown", function (f) {
        return f(view, keyEvent(8, "Backspace"));
      })) {
        return;
      }

      var ref = view.state.selection;
      var $cursor = ref.$cursor; // Crude approximation of backspace behavior when no command handled it

      if ($cursor && $cursor.pos > 0) {
        view.dispatch(view.state.tr.delete($cursor.pos - 1, $cursor.pos).scrollIntoView());
      }
    }, 50);
  }
}; // Make sure all handlers get registered


for (var prop in editHandlers) {
  handlers[prop] = editHandlers[prop];
}

function compareObjs(a, b) {
  if (a == b) {
    return true;
  }

  for (var p in a) {
    if (a[p] !== b[p]) {
      return false;
    }
  }

  for (var p$1 in b) {
    if (!(p$1 in a)) {
      return false;
    }
  }

  return true;
}

var WidgetType = function WidgetType(toDOM, spec) {
  this.spec = spec || noSpec;
  this.side = this.spec.side || 0;
  this.toDOM = toDOM;
};

WidgetType.prototype.map = function map(mapping, span, offset, oldOffset) {
  var ref = mapping.mapResult(span.from + oldOffset, this.side < 0 ? -1 : 1);
  var pos = ref.pos;
  var deleted = ref.deleted;
  return deleted ? null : new Decoration(pos - offset, pos - offset, this);
};

WidgetType.prototype.valid = function valid() {
  return true;
};

WidgetType.prototype.eq = function eq(other) {
  return this == other || other instanceof WidgetType && (this.spec.key && this.spec.key == other.spec.key || this.toDOM == other.toDOM && compareObjs(this.spec, other.spec));
};

var InlineType = function InlineType(attrs, spec) {
  this.spec = spec || noSpec;
  this.attrs = attrs;
};

InlineType.prototype.map = function map(mapping, span, offset, oldOffset) {
  var from = mapping.map(span.from + oldOffset, this.spec.inclusiveStart ? -1 : 1) - offset;
  var to = mapping.map(span.to + oldOffset, this.spec.inclusiveEnd ? 1 : -1) - offset;
  return from >= to ? null : new Decoration(from, to, this);
};

InlineType.prototype.valid = function valid(_, span) {
  return span.from < span.to;
};

InlineType.prototype.eq = function eq(other) {
  return this == other || other instanceof InlineType && compareObjs(this.attrs, other.attrs) && compareObjs(this.spec, other.spec);
};

InlineType.is = function is(span) {
  return span.type instanceof InlineType;
};

var NodeType = function NodeType(attrs, spec) {
  this.spec = spec || noSpec;
  this.attrs = attrs;
};

NodeType.prototype.map = function map(mapping, span, offset, oldOffset) {
  var from = mapping.mapResult(span.from + oldOffset, 1);

  if (from.deleted) {
    return null;
  }

  var to = mapping.mapResult(span.to + oldOffset, -1);

  if (to.deleted || to.pos <= from.pos) {
    return null;
  }

  return new Decoration(from.pos - offset, to.pos - offset, this);
};

NodeType.prototype.valid = function valid(node, span) {
  var ref = node.content.findIndex(span.from);
  var index = ref.index;
  var offset = ref.offset;
  return offset == span.from && offset + node.child(index).nodeSize == span.to;
};

NodeType.prototype.eq = function eq(other) {
  return this == other || other instanceof NodeType && compareObjs(this.attrs, other.attrs) && compareObjs(this.spec, other.spec);
}; // ::- Decoration objects can be provided to the view through the
// [`decorations` prop](#view.EditorProps.decorations). They come in
// several variants—see the static members of this class for details.


var Decoration = function Decoration(from, to, type) {
  // :: number
  // The start position of the decoration.
  this.from = from; // :: number
  // The end position. Will be the same as `from` for [widget
  // decorations](#view.Decoration^widget).

  this.to = to;
  this.type = type;
};

exports.Decoration = Decoration;
var prototypeAccessors$1 = {
  spec: {
    configurable: true
  }
};

Decoration.prototype.copy = function copy(from, to) {
  return new Decoration(from, to, this.type);
};

Decoration.prototype.eq = function eq(other, offset) {
  if (offset === void 0) offset = 0;
  return this.type.eq(other.type) && this.from + offset == other.from && this.to + offset == other.to;
};

Decoration.prototype.map = function map(mapping, offset, oldOffset) {
  return this.type.map(mapping, this, offset, oldOffset);
}; // :: (number, union<(view: EditorView, getPos: () → number) → dom.Node, dom.Node>, ?Object) → Decoration
// Creates a widget decoration, which is a DOM node that's shown in
// the document at the given position. It is recommended that you
// delay rendering the widget by passing a function that will be
// called when the widget is actually drawn in a view, but you can
// also directly pass a DOM node. `getPos` can be used to find the
// widget's current document position.
//
// spec::- These options are supported:
//
//   side:: ?number
//   Controls which side of the document position this widget is
//   associated with. When negative, it is drawn before a cursor
//   at its position, and content inserted at that position ends
//   up after the widget. When zero (the default) or positive, the
//   widget is drawn after the cursor and content inserted there
//   ends up before the widget.
//
//   When there are multiple widgets at a given position, their
//   `side` values determine the order in which they appear. Those
//   with lower values appear first. The ordering of widgets with
//   the same `side` value is unspecified.
//
//   When `marks` is null, `side` also determines the marks that
//   the widget is wrapped in—those of the node before when
//   negative, those of the node after when positive.
//
//   marks:: ?[Mark]
//   The precise set of marks to draw around the widget.
//
//   stopEvent:: ?(event: dom.Event) → bool
//   Can be used to control which DOM events, when they bubble out
//   of this widget, the editor view should ignore.
//
//   ignoreSelection:: ?bool
//   When set (defaults to false), selection changes inside the
//   widget are ignored, and don't cause ProseMirror to try and
//   re-sync the selection with its selection state.
//
//   key:: ?string
//   When comparing decorations of this type (in order to decide
//   whether it needs to be redrawn), ProseMirror will by default
//   compare the widget DOM node by identity. If you pass a key,
//   that key will be compared instead, which can be useful when
//   you generate decorations on the fly and don't want to store
//   and reuse DOM nodes. Make sure that any widgets with the same
//   key are interchangeable—if widgets differ in, for example,
//   the behavior of some event handler, they should get
//   different keys.


Decoration.widget = function widget(pos, toDOM, spec) {
  return new Decoration(pos, pos, new WidgetType(toDOM, spec));
}; // :: (number, number, DecorationAttrs, ?Object) → Decoration
// Creates an inline decoration, which adds the given attributes to
// each inline node between `from` and `to`.
//
// spec::- These options are recognized:
//
//   inclusiveStart:: ?bool
//   Determines how the left side of the decoration is
//   [mapped](#transform.Position_Mapping) when content is
//   inserted directly at that position. By default, the decoration
//   won't include the new content, but you can set this to `true`
//   to make it inclusive.
//
//   inclusiveEnd:: ?bool
//   Determines how the right side of the decoration is mapped.
//   See
//   [`inclusiveStart`](#view.Decoration^inline^spec.inclusiveStart).


Decoration.inline = function inline(from, to, attrs, spec) {
  return new Decoration(from, to, new InlineType(attrs, spec));
}; // :: (number, number, DecorationAttrs, ?Object) → Decoration
// Creates a node decoration. `from` and `to` should point precisely
// before and after a node in the document. That node, and only that
// node, will receive the given attributes.
//
// spec::-
//
// Optional information to store with the decoration. It
// is also used when comparing decorators for equality.


Decoration.node = function node(from, to, attrs, spec) {
  return new Decoration(from, to, new NodeType(attrs, spec));
}; // :: Object
// The spec provided when creating this decoration. Can be useful
// if you've stored extra information in that object.


prototypeAccessors$1.spec.get = function () {
  return this.type.spec;
};

Object.defineProperties(Decoration.prototype, prototypeAccessors$1); // DecorationAttrs:: interface
// A set of attributes to add to a decorated node. Most properties
// simply directly correspond to DOM attributes of the same name,
// which will be set to the property's value. These are exceptions:
//
//   class:: ?string
//   A CSS class name or a space-separated set of class names to be
//   _added_ to the classes that the node already had.
//
//   style:: ?string
//   A string of CSS to be _added_ to the node's existing `style` property.
//
//   nodeName:: ?string
//   When non-null, the target node is wrapped in a DOM element of
//   this type (and the other attributes are applied to this element).

var none = [],
    noSpec = {}; // ::- A collection of [decorations](#view.Decoration), organized in
// such a way that the drawing algorithm can efficiently use and
// compare them. This is a persistent data structure—it is not
// modified, updates create a new value.

var DecorationSet = function DecorationSet(local, children) {
  this.local = local && local.length ? local : none;
  this.children = children && children.length ? children : none;
}; // :: (Node, [Decoration]) → DecorationSet
// Create a set of decorations, using the structure of the given
// document.


exports.DecorationSet = DecorationSet;

DecorationSet.create = function create(doc, decorations) {
  return decorations.length ? buildTree(decorations, doc, 0, noSpec) : empty;
}; // :: (?number, ?number, ?(spec: Object) → bool) → [Decoration]
// Find all decorations in this set which touch the given range
// (including decorations that start or end directly at the
// boundaries) and match the given predicate on their spec. When
// `start` and `end` are omitted, all decorations in the set are
// considered. When `predicate` isn't given, all decorations are
// assumed to match.


DecorationSet.prototype.find = function find(start, end, predicate) {
  var result = [];
  this.findInner(start == null ? 0 : start, end == null ? 1e9 : end, result, 0, predicate);
  return result;
};

DecorationSet.prototype.findInner = function findInner(start, end, result, offset, predicate) {
  for (var i = 0; i < this.local.length; i++) {
    var span = this.local[i];

    if (span.from <= end && span.to >= start && (!predicate || predicate(span.spec))) {
      result.push(span.copy(span.from + offset, span.to + offset));
    }
  }

  for (var i$1 = 0; i$1 < this.children.length; i$1 += 3) {
    if (this.children[i$1] < end && this.children[i$1 + 1] > start) {
      var childOff = this.children[i$1] + 1;
      this.children[i$1 + 2].findInner(start - childOff, end - childOff, result, offset + childOff, predicate);
    }
  }
}; // :: (Mapping, Node, ?Object) → DecorationSet
// Map the set of decorations in response to a change in the
// document.
//
// options::- An optional set of options.
//
//   onRemove:: ?(decorationSpec: Object)
//   When given, this function will be called for each decoration
//   that gets dropped as a result of the mapping, passing the
//   spec of that decoration.


DecorationSet.prototype.map = function map(mapping, doc, options) {
  if (this == empty || mapping.maps.length == 0) {
    return this;
  }

  return this.mapInner(mapping, doc, 0, 0, options || noSpec);
};

DecorationSet.prototype.mapInner = function mapInner(mapping, node, offset, oldOffset, options) {
  var newLocal;

  for (var i = 0; i < this.local.length; i++) {
    var mapped = this.local[i].map(mapping, offset, oldOffset);

    if (mapped && mapped.type.valid(node, mapped)) {
      (newLocal || (newLocal = [])).push(mapped);
    } else if (options.onRemove) {
      options.onRemove(this.local[i].spec);
    }
  }

  if (this.children.length) {
    return mapChildren(this.children, newLocal, mapping, node, offset, oldOffset, options);
  } else {
    return newLocal ? new DecorationSet(newLocal.sort(byPos)) : empty;
  }
}; // :: (Node, [Decoration]) → DecorationSet
// Add the given array of decorations to the ones in the set,
// producing a new set. Needs access to the current document to
// create the appropriate tree structure.


DecorationSet.prototype.add = function add(doc, decorations) {
  if (!decorations.length) {
    return this;
  }

  if (this == empty) {
    return DecorationSet.create(doc, decorations);
  }

  return this.addInner(doc, decorations, 0);
};

DecorationSet.prototype.addInner = function addInner(doc, decorations, offset) {
  var this$1 = this;
  var children,
      childIndex = 0;
  doc.forEach(function (childNode, childOffset) {
    var baseOffset = childOffset + offset,
        found;

    if (!(found = takeSpansForNode(decorations, childNode, baseOffset))) {
      return;
    }

    if (!children) {
      children = this$1.children.slice();
    }

    while (childIndex < children.length && children[childIndex] < childOffset) {
      childIndex += 3;
    }

    if (children[childIndex] == childOffset) {
      children[childIndex + 2] = children[childIndex + 2].addInner(childNode, found, baseOffset + 1);
    } else {
      children.splice(childIndex, 0, childOffset, childOffset + childNode.nodeSize, buildTree(found, childNode, baseOffset + 1, noSpec));
    }

    childIndex += 3;
  });
  var local = moveSpans(childIndex ? withoutNulls(decorations) : decorations, -offset);
  return new DecorationSet(local.length ? this.local.concat(local).sort(byPos) : this.local, children || this.children);
}; // :: ([Decoration]) → DecorationSet
// Create a new set that contains the decorations in this set, minus
// the ones in the given array.


DecorationSet.prototype.remove = function remove(decorations) {
  if (decorations.length == 0 || this == empty) {
    return this;
  }

  return this.removeInner(decorations, 0);
};

DecorationSet.prototype.removeInner = function removeInner(decorations, offset) {
  var children = this.children,
      local = this.local;

  for (var i = 0; i < children.length; i += 3) {
    var found = void 0,
        from = children[i] + offset,
        to = children[i + 1] + offset;

    for (var j = 0, span = void 0; j < decorations.length; j++) {
      if (span = decorations[j]) {
        if (span.from > from && span.to < to) {
          decorations[j] = null;
          (found || (found = [])).push(span);
        }
      }
    }

    if (!found) {
      continue;
    }

    if (children == this.children) {
      children = this.children.slice();
    }

    var removed = children[i + 2].removeInner(found, from + 1);

    if (removed != empty) {
      children[i + 2] = removed;
    } else {
      children.splice(i, 3);
      i -= 3;
    }
  }

  if (local.length) {
    for (var i$1 = 0, span$1 = void 0; i$1 < decorations.length; i$1++) {
      if (span$1 = decorations[i$1]) {
        for (var j$1 = 0; j$1 < local.length; j$1++) {
          if (local[j$1].eq(span$1, offset)) {
            if (local == this.local) {
              local = this.local.slice();
            }

            local.splice(j$1--, 1);
          }
        }
      }
    }
  }

  if (children == this.children && local == this.local) {
    return this;
  }

  return local.length || children.length ? new DecorationSet(local, children) : empty;
};

DecorationSet.prototype.forChild = function forChild(offset, node) {
  if (this == empty) {
    return this;
  }

  if (node.isLeaf) {
    return DecorationSet.empty;
  }

  var child, local;

  for (var i = 0; i < this.children.length; i += 3) {
    if (this.children[i] >= offset) {
      if (this.children[i] == offset) {
        child = this.children[i + 2];
      }

      break;
    }
  }

  var start = offset + 1,
      end = start + node.content.size;

  for (var i$1 = 0; i$1 < this.local.length; i$1++) {
    var dec = this.local[i$1];

    if (dec.from < end && dec.to > start && dec.type instanceof InlineType) {
      var from = Math.max(start, dec.from) - start,
          to = Math.min(end, dec.to) - start;

      if (from < to) {
        (local || (local = [])).push(dec.copy(from, to));
      }
    }
  }

  if (local) {
    var localSet = new DecorationSet(local.sort(byPos));
    return child ? new DecorationGroup([localSet, child]) : localSet;
  }

  return child || empty;
};

DecorationSet.prototype.eq = function eq(other) {
  if (this == other) {
    return true;
  }

  if (!(other instanceof DecorationSet) || this.local.length != other.local.length || this.children.length != other.children.length) {
    return false;
  }

  for (var i = 0; i < this.local.length; i++) {
    if (!this.local[i].eq(other.local[i])) {
      return false;
    }
  }

  for (var i$1 = 0; i$1 < this.children.length; i$1 += 3) {
    if (this.children[i$1] != other.children[i$1] || this.children[i$1 + 1] != other.children[i$1 + 1] || !this.children[i$1 + 2].eq(other.children[i$1 + 2])) {
      return false;
    }
  }

  return true;
};

DecorationSet.prototype.locals = function locals(node) {
  return removeOverlap(this.localsInner(node));
};

DecorationSet.prototype.localsInner = function localsInner(node) {
  if (this == empty) {
    return none;
  }

  if (node.inlineContent || !this.local.some(InlineType.is)) {
    return this.local;
  }

  var result = [];

  for (var i = 0; i < this.local.length; i++) {
    if (!(this.local[i].type instanceof InlineType)) {
      result.push(this.local[i]);
    }
  }

  return result;
};

var empty = new DecorationSet(); // :: DecorationSet
// The empty set of decorations.

DecorationSet.empty = empty;
DecorationSet.removeOverlap = removeOverlap; // :- An abstraction that allows the code dealing with decorations to
// treat multiple DecorationSet objects as if it were a single object
// with (a subset of) the same interface.

var DecorationGroup = function DecorationGroup(members) {
  this.members = members;
};

DecorationGroup.prototype.forChild = function forChild(offset, child) {
  if (child.isLeaf) {
    return DecorationSet.empty;
  }

  var found = [];

  for (var i = 0; i < this.members.length; i++) {
    var result = this.members[i].forChild(offset, child);

    if (result == empty) {
      continue;
    }

    if (result instanceof DecorationGroup) {
      found = found.concat(result.members);
    } else {
      found.push(result);
    }
  }

  return DecorationGroup.from(found);
};

DecorationGroup.prototype.eq = function eq(other) {
  if (!(other instanceof DecorationGroup) || other.members.length != this.members.length) {
    return false;
  }

  for (var i = 0; i < this.members.length; i++) {
    if (!this.members[i].eq(other.members[i])) {
      return false;
    }
  }

  return true;
};

DecorationGroup.prototype.locals = function locals(node) {
  var result,
      sorted = true;

  for (var i = 0; i < this.members.length; i++) {
    var locals = this.members[i].localsInner(node);

    if (!locals.length) {
      continue;
    }

    if (!result) {
      result = locals;
    } else {
      if (sorted) {
        result = result.slice();
        sorted = false;
      }

      for (var j = 0; j < locals.length; j++) {
        result.push(locals[j]);
      }
    }
  }

  return result ? removeOverlap(sorted ? result : result.sort(byPos)) : none;
}; // : ([DecorationSet]) → union<DecorationSet, DecorationGroup>
// Create a group for the given array of decoration sets, or return
// a single set when possible.


DecorationGroup.from = function from(members) {
  switch (members.length) {
    case 0:
      return empty;

    case 1:
      return members[0];

    default:
      return new DecorationGroup(members);
  }
};

function mapChildren(oldChildren, newLocal, mapping, node, offset, oldOffset, options) {
  var children = oldChildren.slice(); // Mark the children that are directly touched by changes, and
  // move those that are after the changes.

  var shift = function (oldStart, oldEnd, newStart, newEnd) {
    for (var i = 0; i < children.length; i += 3) {
      var end = children[i + 1],
          dSize = void 0;

      if (end == -1 || oldStart > end + oldOffset) {
        continue;
      }

      if (oldEnd >= children[i] + oldOffset) {
        children[i + 1] = -1;
      } else if (newStart >= offset && (dSize = newEnd - newStart - (oldEnd - oldStart))) {
        children[i] += dSize;
        children[i + 1] += dSize;
      }
    }
  };

  for (var i = 0; i < mapping.maps.length; i++) {
    mapping.maps[i].forEach(shift);
  } // Find the child nodes that still correspond to a single node,
  // recursively call mapInner on them and update their positions.


  var mustRebuild = false;

  for (var i$1 = 0; i$1 < children.length; i$1 += 3) {
    if (children[i$1 + 1] == -1) {
      // Touched nodes
      var from = mapping.map(children[i$1] + oldOffset),
          fromLocal = from - offset;

      if (fromLocal < 0 || fromLocal >= node.content.size) {
        mustRebuild = true;
        continue;
      } // Must read oldChildren because children was tagged with -1


      var to = mapping.map(oldChildren[i$1 + 1] + oldOffset, -1),
          toLocal = to - offset;
      var ref = node.content.findIndex(fromLocal);
      var index = ref.index;
      var childOffset = ref.offset;
      var childNode = node.maybeChild(index);

      if (childNode && childOffset == fromLocal && childOffset + childNode.nodeSize == toLocal) {
        var mapped = children[i$1 + 2].mapInner(mapping, childNode, from + 1, children[i$1] + oldOffset + 1, options);

        if (mapped != empty) {
          children[i$1] = fromLocal;
          children[i$1 + 1] = toLocal;
          children[i$1 + 2] = mapped;
        } else {
          children[i$1 + 1] = -2;
          mustRebuild = true;
        }
      } else {
        mustRebuild = true;
      }
    }
  } // Remaining children must be collected and rebuilt into the appropriate structure


  if (mustRebuild) {
    var decorations = mapAndGatherRemainingDecorations(children, oldChildren, newLocal || [], mapping, offset, oldOffset, options);
    var built = buildTree(decorations, node, 0, options);
    newLocal = built.local;

    for (var i$2 = 0; i$2 < children.length; i$2 += 3) {
      if (children[i$2 + 1] < 0) {
        children.splice(i$2, 3);
        i$2 -= 3;
      }
    }

    for (var i$3 = 0, j = 0; i$3 < built.children.length; i$3 += 3) {
      var from$1 = built.children[i$3];

      while (j < children.length && children[j] < from$1) {
        j += 3;
      }

      children.splice(j, 0, built.children[i$3], built.children[i$3 + 1], built.children[i$3 + 2]);
    }
  }

  return new DecorationSet(newLocal && newLocal.sort(byPos), children);
}

function moveSpans(spans, offset) {
  if (!offset || !spans.length) {
    return spans;
  }

  var result = [];

  for (var i = 0; i < spans.length; i++) {
    var span = spans[i];
    result.push(new Decoration(span.from + offset, span.to + offset, span.type));
  }

  return result;
}

function mapAndGatherRemainingDecorations(children, oldChildren, decorations, mapping, offset, oldOffset, options) {
  // Gather all decorations from the remaining marked children
  function gather(set, oldOffset) {
    for (var i = 0; i < set.local.length; i++) {
      var mapped = set.local[i].map(mapping, offset, oldOffset);

      if (mapped) {
        decorations.push(mapped);
      } else if (options.onRemove) {
        options.onRemove(set.local[i].spec);
      }
    }

    for (var i$1 = 0; i$1 < set.children.length; i$1 += 3) {
      gather(set.children[i$1 + 2], set.children[i$1] + oldOffset + 1);
    }
  }

  for (var i = 0; i < children.length; i += 3) {
    if (children[i + 1] == -1) {
      gather(children[i + 2], oldChildren[i] + oldOffset + 1);
    }
  }

  return decorations;
}

function takeSpansForNode(spans, node, offset) {
  if (node.isLeaf) {
    return null;
  }

  var end = offset + node.nodeSize,
      found = null;

  for (var i = 0, span = void 0; i < spans.length; i++) {
    if ((span = spans[i]) && span.from > offset && span.to < end) {
      (found || (found = [])).push(span);
      spans[i] = null;
    }
  }

  return found;
}

function withoutNulls(array) {
  var result = [];

  for (var i = 0; i < array.length; i++) {
    if (array[i] != null) {
      result.push(array[i]);
    }
  }

  return result;
} // : ([Decoration], Node, number) → DecorationSet
// Build up a tree that corresponds to a set of decorations. `offset`
// is a base offset that should be subtractet from the `from` and `to`
// positions in the spans (so that we don't have to allocate new spans
// for recursive calls).


function buildTree(spans, node, offset, options) {
  var children = [],
      hasNulls = false;
  node.forEach(function (childNode, localStart) {
    var found = takeSpansForNode(spans, childNode, localStart + offset);

    if (found) {
      hasNulls = true;
      var subtree = buildTree(found, childNode, offset + localStart + 1, options);

      if (subtree != empty) {
        children.push(localStart, localStart + childNode.nodeSize, subtree);
      }
    }
  });
  var locals = moveSpans(hasNulls ? withoutNulls(spans) : spans, -offset).sort(byPos);

  for (var i = 0; i < locals.length; i++) {
    if (!locals[i].type.valid(node, locals[i])) {
      if (options.onRemove) {
        options.onRemove(locals[i].spec);
      }

      locals.splice(i--, 1);
    }
  }

  return locals.length || children.length ? new DecorationSet(locals, children) : empty;
} // : (Decoration, Decoration) → number
// Used to sort decorations so that ones with a low start position
// come first, and within a set with the same start position, those
// with an smaller end position come first.


function byPos(a, b) {
  return a.from - b.from || a.to - b.to;
} // : ([Decoration]) → [Decoration]
// Scan a sorted array of decorations for partially overlapping spans,
// and split those so that only fully overlapping spans are left (to
// make subsequent rendering easier). Will return the input array if
// no partially overlapping spans are found (the common case).


function removeOverlap(spans) {
  var working = spans;

  for (var i = 0; i < working.length - 1; i++) {
    var span = working[i];

    if (span.from != span.to) {
      for (var j = i + 1; j < working.length; j++) {
        var next = working[j];

        if (next.from == span.from) {
          if (next.to != span.to) {
            if (working == spans) {
              working = spans.slice();
            } // Followed by a partially overlapping larger span. Split that
            // span.


            working[j] = next.copy(next.from, span.to);
            insertAhead(working, j + 1, next.copy(span.to, next.to));
          }

          continue;
        } else {
          if (next.from < span.to) {
            if (working == spans) {
              working = spans.slice();
            } // The end of this one overlaps with a subsequent span. Split
            // this one.


            working[i] = span.copy(span.from, next.from);
            insertAhead(working, j, span.copy(next.from, span.to));
          }

          break;
        }
      }
    }
  }

  return working;
}

function insertAhead(array, i, deco) {
  while (i < array.length && byPos(deco, array[i]) > 0) {
    i++;
  }

  array.splice(i, 0, deco);
} // : (EditorView) → union<DecorationSet, DecorationGroup>
// Get the decorations associated with the current props of a view.


function viewDecorations(view) {
  var found = [];
  view.someProp("decorations", function (f) {
    var result = f(view.state);

    if (result && result != empty) {
      found.push(result);
    }
  });

  if (view.cursorWrapper) {
    found.push(DecorationSet.create(view.state.doc, [view.cursorWrapper.deco]));
  }

  return DecorationGroup.from(found);
} // ::- An editor view manages the DOM structure that represents an
// editable document. Its state and behavior are determined by its
// [props](#view.DirectEditorProps).


var EditorView = function EditorView(place, props) {
  this._props = props; // :: EditorState
  // The view's current [state](#state.EditorState).

  this.state = props.state;
  this.dispatch = this.dispatch.bind(this);
  this._root = null;
  this.focused = false; // :: dom.Element
  // An editable DOM node containing the document. (You probably
  // should not directly interfere with its content.)

  this.dom = place && place.mount || document.createElement("div");

  if (place) {
    if (place.appendChild) {
      place.appendChild(this.dom);
    } else if (place.apply) {
      place(this.dom);
    } else if (place.mount) {
      this.mounted = true;
    }
  } // :: bool
  // Indicates whether the editor is currently [editable](#view.EditorProps.editable).


  this.editable = getEditable(this);
  this.markCursor = null;
  this.cursorWrapper = null;
  updateCursorWrapper(this);
  this.nodeViews = buildNodeViews(this);
  this.docView = docViewDesc(this.state.doc, computeDocDeco(this), viewDecorations(this), this.dom, this);
  this.lastSelectedViewDesc = null; // :: ?{slice: Slice, move: bool}
  // When editor content is being dragged, this object contains
  // information about the dragged slice and whether it is being
  // copied or moved. At any other time, it is null.

  this.dragging = null;
  initInput(this);
  this.pluginViews = [];
  this.updatePluginViews();
};

exports.EditorView = EditorView;
var prototypeAccessors$2 = {
  props: {
    configurable: true
  },
  root: {
    configurable: true
  }
}; // composing:: boolean
// Holds `true` when a
// [composition](https://developer.mozilla.org/en-US/docs/Mozilla/IME_handling_guide)
// is active.
// :: DirectEditorProps
// The view's current [props](#view.EditorProps).

prototypeAccessors$2.props.get = function () {
  if (this._props.state != this.state) {
    var prev = this._props;
    this._props = {};

    for (var name in prev) {
      this._props[name] = prev[name];
    }

    this._props.state = this.state;
  }

  return this._props;
}; // :: (DirectEditorProps)
// Update the view's props. Will immediately cause an update to
// the DOM.


EditorView.prototype.update = function update(props) {
  if (props.handleDOMEvents != this._props.handleDOMEvents) {
    ensureListeners(this);
  }

  this._props = props;
  this.updateStateInner(props.state, true);
}; // :: (DirectEditorProps)
// Update the view by updating existing props object with the object
// given as argument. Equivalent to `view.update(Object.assign({},
// view.props, props))`.


EditorView.prototype.setProps = function setProps(props) {
  var updated = {};

  for (var name in this._props) {
    updated[name] = this._props[name];
  }

  updated.state = this.state;

  for (var name$1 in props) {
    updated[name$1] = props[name$1];
  }

  this.update(updated);
}; // :: (EditorState)
// Update the editor's `state` prop, without touching any of the
// other props.


EditorView.prototype.updateState = function updateState(state) {
  this.updateStateInner(state, this.state.plugins != state.plugins);
};

EditorView.prototype.updateStateInner = function updateStateInner(state, reconfigured) {
  var this$1 = this;
  var prev = this.state,
      redraw = false;
  this.state = state;

  if (reconfigured) {
    var nodeViews = buildNodeViews(this);

    if (changedNodeViews(nodeViews, this.nodeViews)) {
      this.nodeViews = nodeViews;
      redraw = true;
    }

    ensureListeners(this);
  }

  this.editable = getEditable(this);
  updateCursorWrapper(this);
  var innerDeco = viewDecorations(this),
      outerDeco = computeDocDeco(this);
  var scroll = reconfigured ? "reset" : state.scrollToSelection > prev.scrollToSelection ? "to selection" : "preserve";
  var updateDoc = redraw || !this.docView.matchesNode(state.doc, outerDeco, innerDeco);
  var updateSel = updateDoc || !state.selection.eq(prev.selection);
  var oldScrollPos = scroll == "preserve" && updateSel && this.dom.style.overflowAnchor == null && storeScrollPos(this);

  if (updateSel) {
    this.domObserver.stop(); // Work around an issue in Chrome, IE, and Edge where changing
    // the DOM around an active selection puts it into a broken
    // state where the thing the user sees differs from the
    // selection reported by the Selection object (#710, #973,
    // #1011, #1013, #1035).

    var forceSelUpdate = updateDoc && (result.ie || result.chrome) && !this.composing && !prev.selection.empty && !state.selection.empty && selectionContextChanged(prev.selection, state.selection);

    if (updateDoc) {
      var selContext = result.chrome && selectionContext(this.root);

      if (redraw || !this.docView.update(state.doc, outerDeco, innerDeco, this)) {
        this.docView.updateOuterDeco([]);
        this.docView.destroy();
        this.docView = docViewDesc(state.doc, outerDeco, innerDeco, this.dom, this);
      }

      if (selContext && needChromeSelectionReset(selContext, this.root)) {
        forceSelUpdate = true;
      }
    } // Work around for an issue where an update arriving right between
    // a DOM selection change and the "selectionchange" event for it
    // can cause a spurious DOM selection update, disrupting mouse
    // drag selection.


    if (forceSelUpdate || !(this.mouseDown && this.domObserver.currentSelection.eq(this.root.getSelection()) && anchorInRightPlace(this))) {
      selectionToDOM(this, forceSelUpdate);
    } else {
      syncNodeSelection(this, state.selection);
      this.domObserver.setCurSelection();
    }

    this.domObserver.start();
  }

  this.updatePluginViews(prev);

  if (scroll == "reset") {
    this.dom.scrollTop = 0;
  } else if (scroll == "to selection") {
    var startDOM = this.root.getSelection().focusNode;
    if (this.someProp("handleScrollToSelection", function (f) {
      return f(this$1);
    })) ; // Handled
    else if (state.selection instanceof _prosemirrorState.NodeSelection) {
        scrollRectIntoView(this, this.docView.domAfterPos(state.selection.from).getBoundingClientRect(), startDOM);
      } else {
        scrollRectIntoView(this, this.coordsAtPos(state.selection.head), startDOM);
      }
  } else if (oldScrollPos) {
    resetScrollPos(oldScrollPos);
  }
};

EditorView.prototype.destroyPluginViews = function destroyPluginViews() {
  var view;

  while (view = this.pluginViews.pop()) {
    if (view.destroy) {
      view.destroy();
    }
  }
};

EditorView.prototype.updatePluginViews = function updatePluginViews(prevState) {
  if (!prevState || prevState.plugins != this.state.plugins) {
    this.destroyPluginViews();

    for (var i = 0; i < this.state.plugins.length; i++) {
      var plugin = this.state.plugins[i];

      if (plugin.spec.view) {
        this.pluginViews.push(plugin.spec.view(this));
      }
    }
  } else {
    for (var i$1 = 0; i$1 < this.pluginViews.length; i$1++) {
      var pluginView = this.pluginViews[i$1];

      if (pluginView.update) {
        pluginView.update(this, prevState);
      }
    }
  }
}; // :: (string, ?(prop: *) → *) → *
// Goes over the values of a prop, first those provided directly,
// then those from plugins (in order), and calls `f` every time a
// non-undefined value is found. When `f` returns a truthy value,
// that is immediately returned. When `f` isn't provided, it is
// treated as the identity function (the prop value is returned
// directly).


EditorView.prototype.someProp = function someProp(propName, f) {
  var prop = this._props && this._props[propName],
      value;

  if (prop != null && (value = f ? f(prop) : prop)) {
    return value;
  }

  var plugins = this.state.plugins;

  if (plugins) {
    for (var i = 0; i < plugins.length; i++) {
      var prop$1 = plugins[i].props[propName];

      if (prop$1 != null && (value = f ? f(prop$1) : prop$1)) {
        return value;
      }
    }
  }
}; // :: () → bool
// Query whether the view has focus.


EditorView.prototype.hasFocus = function hasFocus() {
  return this.root.activeElement == this.dom;
}; // :: ()
// Focus the editor.


EditorView.prototype.focus = function focus() {
  this.domObserver.stop();

  if (this.editable) {
    focusPreventScroll(this.dom);
  }

  selectionToDOM(this);
  this.domObserver.start();
}; // :: union<dom.Document, dom.DocumentFragment>
// Get the document root in which the editor exists. This will
// usually be the top-level `document`, but might be a [shadow
// DOM](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Shadow_DOM)
// root if the editor is inside one.


prototypeAccessors$2.root.get = function () {
  var cached = this._root;

  if (cached == null) {
    for (var search = this.dom.parentNode; search; search = search.parentNode) {
      if (search.nodeType == 9 || search.nodeType == 11 && search.host) {
        if (!search.getSelection) {
          Object.getPrototypeOf(search).getSelection = function () {
            return document.getSelection();
          };
        }

        return this._root = search;
      }
    }
  }

  return cached || document;
}; // :: ({left: number, top: number}) → ?{pos: number, inside: number}
// Given a pair of viewport coordinates, return the document
// position that corresponds to them. May return null if the given
// coordinates aren't inside of the editor. When an object is
// returned, its `pos` property is the position nearest to the
// coordinates, and its `inside` property holds the position of the
// inner node that the position falls inside of, or -1 if it is at
// the top level, not in any node.


EditorView.prototype.posAtCoords = function posAtCoords$1(coords) {
  return posAtCoords(this, coords);
}; // :: (number) → {left: number, right: number, top: number, bottom: number}
// Returns the viewport rectangle at a given document position. `left`
// and `right` will be the same number, as this returns a flat
// cursor-ish rectangle.


EditorView.prototype.coordsAtPos = function coordsAtPos$1(pos) {
  return coordsAtPos(this, pos);
}; // :: (number) → {node: dom.Node, offset: number}
// Find the DOM position that corresponds to the given document
// position. Note that you should **not** mutate the editor's
// internal DOM, only inspect it (and even that is usually not
// necessary).


EditorView.prototype.domAtPos = function domAtPos(pos) {
  return this.docView.domFromPos(pos);
}; // :: (number) → ?dom.Node
// Find the DOM node that represents the document node after the
// given position. May return `null` when the position doesn't point
// in front of a node or if the node is inside an opaque node view.
//
// This is intended to be able to call things like
// `getBoundingClientRect` on that DOM node. Do **not** mutate the
// editor DOM directly, or add styling this way, since that will be
// immediately overriden by the editor as it redraws the node.


EditorView.prototype.nodeDOM = function nodeDOM(pos) {
  var desc = this.docView.descAt(pos);
  return desc ? desc.nodeDOM : null;
}; // :: (dom.Node, number, ?number) → number
// Find the document position that corresponds to a given DOM
// position. (Whenever possible, it is preferable to inspect the
// document structure directly, rather than poking around in the
// DOM, but sometimes—for example when interpreting an event
// target—you don't have a choice.)
//
// The `bias` parameter can be used to influence which side of a DOM
// node to use when the position is inside a leaf node.


EditorView.prototype.posAtDOM = function posAtDOM(node, offset, bias) {
  if (bias === void 0) bias = -1;
  var pos = this.docView.posFromDOM(node, offset, bias);

  if (pos == null) {
    throw new RangeError("DOM position not inside the editor");
  }

  return pos;
}; // :: (union<"up", "down", "left", "right", "forward", "backward">, ?EditorState) → bool
// Find out whether the selection is at the end of a textblock when
// moving in a given direction. When, for example, given `"left"`,
// it will return true if moving left from the current cursor
// position would leave that position's parent textblock. Will apply
// to the view's current state by default, but it is possible to
// pass a different state.


EditorView.prototype.endOfTextblock = function endOfTextblock$1(dir, state) {
  return endOfTextblock(this, state || this.state, dir);
}; // :: ()
// Removes the editor from the DOM and destroys all [node
// views](#view.NodeView).


EditorView.prototype.destroy = function destroy() {
  if (!this.docView) {
    return;
  }

  destroyInput(this);
  this.destroyPluginViews();

  if (this.mounted) {
    this.docView.update(this.state.doc, [], viewDecorations(this), this);
    this.dom.textContent = "";
  } else if (this.dom.parentNode) {
    this.dom.parentNode.removeChild(this.dom);
  }

  this.docView.destroy();
  this.docView = null;
}; // Used for testing.


EditorView.prototype.dispatchEvent = function dispatchEvent$1(event) {
  return dispatchEvent(this, event);
}; // :: (Transaction)
// Dispatch a transaction. Will call
// [`dispatchTransaction`](#view.DirectEditorProps.dispatchTransaction)
// when given, and otherwise defaults to applying the transaction to
// the current state and calling
// [`updateState`](#view.EditorView.updateState) with the result.
// This method is bound to the view instance, so that it can be
// easily passed around.


EditorView.prototype.dispatch = function dispatch(tr) {
  var dispatchTransaction = this._props.dispatchTransaction;

  if (dispatchTransaction) {
    dispatchTransaction.call(this, tr);
  } else {
    this.updateState(this.state.apply(tr));
  }
};

Object.defineProperties(EditorView.prototype, prototypeAccessors$2);

function computeDocDeco(view) {
  var attrs = Object.create(null);
  attrs.class = "ProseMirror";
  attrs.contenteditable = String(view.editable);
  view.someProp("attributes", function (value) {
    if (typeof value == "function") {
      value = value(view.state);
    }

    if (value) {
      for (var attr in value) {
        if (attr == "class") {
          attrs.class += " " + value[attr];
        } else if (!attrs[attr] && attr != "contenteditable" && attr != "nodeName") {
          attrs[attr] = String(value[attr]);
        }
      }
    }
  });
  return [Decoration.node(0, view.state.doc.content.size, attrs)];
}

function updateCursorWrapper(view) {
  if (view.markCursor) {
    var dom = document.createElement("img");
    dom.setAttribute("mark-placeholder", "true");
    view.cursorWrapper = {
      dom: dom,
      deco: Decoration.widget(view.state.selection.head, dom, {
        raw: true,
        marks: view.markCursor
      })
    };
  } else {
    view.cursorWrapper = null;
  }
}

function getEditable(view) {
  return !view.someProp("editable", function (value) {
    return value(view.state) === false;
  });
}

function selectionContextChanged(sel1, sel2) {
  var depth = Math.min(sel1.$anchor.sharedDepth(sel1.head), sel2.$anchor.sharedDepth(sel2.head));
  return sel1.$anchor.start(depth) != sel2.$anchor.start(depth);
}

function buildNodeViews(view) {
  var result = {};
  view.someProp("nodeViews", function (obj) {
    for (var prop in obj) {
      if (!Object.prototype.hasOwnProperty.call(result, prop)) {
        result[prop] = obj[prop];
      }
    }
  });
  return result;
}

function changedNodeViews(a, b) {
  var nA = 0,
      nB = 0;

  for (var prop in a) {
    if (a[prop] != b[prop]) {
      return true;
    }

    nA++;
  }

  for (var _ in b) {
    nB++;
  }

  return nA != nB;
}

function selectionContext(root) {
  var ref = root.getSelection();
  var offset = ref.focusOffset;
  var node = ref.focusNode;
  return node && node.nodeType == 1 ? [node, offset, node.childNodes[offset - 1], node.childNodes[offset]] : null;
}

function needChromeSelectionReset(context, root) {
  var newContext = selectionContext(root);

  if (!newContext || newContext[0].nodeType == 3) {
    return false;
  }

  for (var i = 0; i < context.length; i++) {
    if (newContext[i] != context[i]) {
      return true;
    }
  }

  return false;
} // EditorProps:: interface
//
// Props are configuration values that can be passed to an editor view
// or included in a plugin. This interface lists the supported props.
//
// The various event-handling functions may all return `true` to
// indicate that they handled the given event. The view will then take
// care to call `preventDefault` on the event, except with
// `handleDOMEvents`, where the handler itself is responsible for that.
//
// How a prop is resolved depends on the prop. Handler functions are
// called one at a time, starting with the base props and then
// searching through the plugins (in order of appearance) until one of
// them returns true. For some props, the first plugin that yields a
// value gets precedence.
//
//   handleDOMEvents:: ?Object<(view: EditorView, event: dom.Event) → bool>
//   Can be an object mapping DOM event type names to functions that
//   handle them. Such functions will be called before any handling
//   ProseMirror does of events fired on the editable DOM element.
//   Contrary to the other event handling props, when returning true
//   from such a function, you are responsible for calling
//   `preventDefault` yourself (or not, if you want to allow the
//   default behavior).
//
//   handleKeyDown:: ?(view: EditorView, event: dom.KeyboardEvent) → bool
//   Called when the editor receives a `keydown` event.
//
//   handleKeyPress:: ?(view: EditorView, event: dom.KeyboardEvent) → bool
//   Handler for `keypress` events.
//
//   handleTextInput:: ?(view: EditorView, from: number, to: number, text: string) → bool
//   Whenever the user directly input text, this handler is called
//   before the input is applied. If it returns `true`, the default
//   behavior of actually inserting the text is suppressed.
//
//   handleClickOn:: ?(view: EditorView, pos: number, node: Node, nodePos: number, event: dom.MouseEvent, direct: bool) → bool
//   Called for each node around a click, from the inside out. The
//   `direct` flag will be true for the inner node.
//
//   handleClick:: ?(view: EditorView, pos: number, event: dom.MouseEvent) → bool
//   Called when the editor is clicked, after `handleClickOn` handlers
//   have been called.
//
//   handleDoubleClickOn:: ?(view: EditorView, pos: number, node: Node, nodePos: number, event: dom.MouseEvent, direct: bool) → bool
//   Called for each node around a double click.
//
//   handleDoubleClick:: ?(view: EditorView, pos: number, event: dom.MouseEvent) → bool
//   Called when the editor is double-clicked, after `handleDoubleClickOn`.
//
//   handleTripleClickOn:: ?(view: EditorView, pos: number, node: Node, nodePos: number, event: dom.MouseEvent, direct: bool) → bool
//   Called for each node around a triple click.
//
//   handleTripleClick:: ?(view: EditorView, pos: number, event: dom.MouseEvent) → bool
//   Called when the editor is triple-clicked, after `handleTripleClickOn`.
//
//   handlePaste:: ?(view: EditorView, event: dom.ClipboardEvent, slice: Slice) → bool
//   Can be used to override the behavior of pasting. `slice` is the
//   pasted content parsed by the editor, but you can directly access
//   the event to get at the raw content.
//
//   handleDrop:: ?(view: EditorView, event: dom.Event, slice: Slice, moved: bool) → bool
//   Called when something is dropped on the editor. `moved` will be
//   true if this drop moves from the current selection (which should
//   thus be deleted).
//
//   handleScrollToSelection:: ?(view: EditorView) → bool
//   Called when the view, after updating its state, tries to scroll
//   the selection into view. A handler function may return false to
//   indicate that it did not handle the scrolling and further
//   handlers or the default behavior should be tried.
//
//   createSelectionBetween:: ?(view: EditorView, anchor: ResolvedPos, head: ResolvedPos) → ?Selection
//   Can be used to override the way a selection is created when
//   reading a DOM selection between the given anchor and head.
//
//   domParser:: ?DOMParser
//   The [parser](#model.DOMParser) to use when reading editor changes
//   from the DOM. Defaults to calling
//   [`DOMParser.fromSchema`](#model.DOMParser^fromSchema) on the
//   editor's schema.
//
//   transformPastedHTML:: ?(html: string) → string
//   Can be used to transform pasted HTML text, _before_ it is parsed,
//   for example to clean it up.
//
//   clipboardParser:: ?DOMParser
//   The [parser](#model.DOMParser) to use when reading content from
//   the clipboard. When not given, the value of the
//   [`domParser`](#view.EditorProps.domParser) prop is used.
//
//   transformPastedText:: ?(text: string) → string
//   Transform pasted plain text.
//
//   clipboardTextParser:: ?(text: string, $context: ResolvedPos) → Slice
//   A function to parse text from the clipboard into a document
//   slice. Called after
//   [`transformPastedText`](#view.EditorProps.transformPastedText).
//   The default behavior is to split the text into lines, wrap them
//   in `<p>` tags, and call
//   [`clipboardParser`](#view.EditorProps.clipboardParser) on it.
//
//   transformPasted:: ?(Slice) → Slice
//   Can be used to transform pasted content before it is applied to
//   the document.
//
//   nodeViews:: ?Object<(node: Node, view: EditorView, getPos: () → number, decorations: [Decoration]) → NodeView>
//   Allows you to pass custom rendering and behavior logic for nodes
//   and marks. Should map node and mark names to constructor
//   functions that produce a [`NodeView`](#view.NodeView) object
//   implementing the node's display behavior. For nodes, the third
//   argument `getPos` is a function that can be called to get the
//   node's current position, which can be useful when creating
//   transactions to update it. For marks, the third argument is a
//   boolean that indicates whether the mark's content is inline.
//
//   `decorations` is an array of node or inline decorations that are
//   active around the node. They are automatically drawn in the
//   normal way, and you will usually just want to ignore this, but
//   they can also be used as a way to provide context information to
//   the node view without adding it to the document itself.
//
//   clipboardSerializer:: ?DOMSerializer
//   The DOM serializer to use when putting content onto the
//   clipboard. If not given, the result of
//   [`DOMSerializer.fromSchema`](#model.DOMSerializer^fromSchema)
//   will be used.
//
//   clipboardTextSerializer:: ?(Slice) → string
//   A function that will be called to get the text for the current
//   selection when copying text to the clipboard. By default, the
//   editor will use [`textBetween`](#model.Node.textBetween) on the
//   selected range.
//
//   decorations:: ?(state: EditorState) → ?DecorationSet
//   A set of [document decorations](#view.Decoration) to show in the
//   view.
//
//   editable:: ?(state: EditorState) → bool
//   When this returns false, the content of the view is not directly
//   editable.
//
//   attributes:: ?union<Object<string>, (EditorState) → ?Object<string>>
//   Control the DOM attributes of the editable element. May be either
//   an object or a function going from an editor state to an object.
//   By default, the element will get a class `"ProseMirror"`, and
//   will have its `contentEditable` attribute determined by the
//   [`editable` prop](#view.EditorProps.editable). Additional classes
//   provided here will be added to the class. For other attributes,
//   the value provided first (as in
//   [`someProp`](#view.EditorView.someProp)) will be used.
//
//   scrollThreshold:: ?union<number, {top: number, right: number, bottom: number, left: number}>
//   Determines the distance (in pixels) between the cursor and the
//   end of the visible viewport at which point, when scrolling the
//   cursor into view, scrolling takes place. Defaults to 0.
//
//   scrollMargin:: ?union<number, {top: number, right: number, bottom: number, left: number}>
//   Determines the extra space (in pixels) that is left above or
//   below the cursor when it is scrolled into view. Defaults to 5.
// DirectEditorProps:: interface extends EditorProps
//
// The props object given directly to the editor view supports two
// fields that can't be used in plugins:
//
//   state:: EditorState
//   The current state of the editor.
//
//   dispatchTransaction:: ?(tr: Transaction)
//   The callback over which to send transactions (state updates)
//   produced by the view. If you specify this, you probably want to
//   make sure this ends up calling the view's
//   [`updateState`](#view.EditorView.updateState) method with a new
//   state that has the transaction
//   [applied](#state.EditorState.apply). The callback will be bound to have
//   the view instance as its `this` binding.
},{"prosemirror-state":"../node_modules/prosemirror-state/dist/index.es.js","prosemirror-model":"../node_modules/prosemirror-model/dist/index.es.js","prosemirror-transform":"../node_modules/prosemirror-transform/dist/index.es.js"}],"../node_modules/prosemirror-schema-basic/dist/index.es.js":[function(require,module,exports) {
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.schema = exports.nodes = exports.marks = void 0;

var _prosemirrorModel = require("prosemirror-model");

var pDOM = ["p", 0],
    blockquoteDOM = ["blockquote", 0],
    hrDOM = ["hr"],
    preDOM = ["pre", ["code", 0]],
    brDOM = ["br"]; // :: Object
// [Specs](#model.NodeSpec) for the nodes defined in this schema.

var nodes = {
  // :: NodeSpec The top level document node.
  doc: {
    content: "block+"
  },
  // :: NodeSpec A plain paragraph textblock. Represented in the DOM
  // as a `<p>` element.
  paragraph: {
    content: "inline*",
    group: "block",
    parseDOM: [{
      tag: "p"
    }],
    toDOM: function toDOM() {
      return pDOM;
    }
  },
  // :: NodeSpec A blockquote (`<blockquote>`) wrapping one or more blocks.
  blockquote: {
    content: "block+",
    group: "block",
    defining: true,
    parseDOM: [{
      tag: "blockquote"
    }],
    toDOM: function toDOM() {
      return blockquoteDOM;
    }
  },
  // :: NodeSpec A horizontal rule (`<hr>`).
  horizontal_rule: {
    group: "block",
    parseDOM: [{
      tag: "hr"
    }],
    toDOM: function toDOM() {
      return hrDOM;
    }
  },
  // :: NodeSpec A heading textblock, with a `level` attribute that
  // should hold the number 1 to 6. Parsed and serialized as `<h1>` to
  // `<h6>` elements.
  heading: {
    attrs: {
      level: {
        default: 1
      }
    },
    content: "inline*",
    group: "block",
    defining: true,
    parseDOM: [{
      tag: "h1",
      attrs: {
        level: 1
      }
    }, {
      tag: "h2",
      attrs: {
        level: 2
      }
    }, {
      tag: "h3",
      attrs: {
        level: 3
      }
    }, {
      tag: "h4",
      attrs: {
        level: 4
      }
    }, {
      tag: "h5",
      attrs: {
        level: 5
      }
    }, {
      tag: "h6",
      attrs: {
        level: 6
      }
    }],
    toDOM: function toDOM(node) {
      return ["h" + node.attrs.level, 0];
    }
  },
  // :: NodeSpec A code listing. Disallows marks or non-text inline
  // nodes by default. Represented as a `<pre>` element with a
  // `<code>` element inside of it.
  code_block: {
    content: "text*",
    marks: "",
    group: "block",
    code: true,
    defining: true,
    parseDOM: [{
      tag: "pre",
      preserveWhitespace: "full"
    }],
    toDOM: function toDOM() {
      return preDOM;
    }
  },
  // :: NodeSpec The text node.
  text: {
    group: "inline"
  },
  // :: NodeSpec An inline image (`<img>`) node. Supports `src`,
  // `alt`, and `href` attributes. The latter two default to the empty
  // string.
  image: {
    inline: true,
    attrs: {
      src: {},
      alt: {
        default: null
      },
      title: {
        default: null
      }
    },
    group: "inline",
    draggable: true,
    parseDOM: [{
      tag: "img[src]",
      getAttrs: function getAttrs(dom) {
        return {
          src: dom.getAttribute("src"),
          title: dom.getAttribute("title"),
          alt: dom.getAttribute("alt")
        };
      }
    }],
    toDOM: function toDOM(node) {
      var ref = node.attrs;
      var src = ref.src;
      var alt = ref.alt;
      var title = ref.title;
      return ["img", {
        src: src,
        alt: alt,
        title: title
      }];
    }
  },
  // :: NodeSpec A hard line break, represented in the DOM as `<br>`.
  hard_break: {
    inline: true,
    group: "inline",
    selectable: false,
    parseDOM: [{
      tag: "br"
    }],
    toDOM: function toDOM() {
      return brDOM;
    }
  }
};
exports.nodes = nodes;
var emDOM = ["em", 0],
    strongDOM = ["strong", 0],
    codeDOM = ["code", 0]; // :: Object [Specs](#model.MarkSpec) for the marks in the schema.

var marks = {
  // :: MarkSpec A link. Has `href` and `title` attributes. `title`
  // defaults to the empty string. Rendered and parsed as an `<a>`
  // element.
  link: {
    attrs: {
      href: {},
      title: {
        default: null
      }
    },
    inclusive: false,
    parseDOM: [{
      tag: "a[href]",
      getAttrs: function getAttrs(dom) {
        return {
          href: dom.getAttribute("href"),
          title: dom.getAttribute("title")
        };
      }
    }],
    toDOM: function toDOM(node) {
      var ref = node.attrs;
      var href = ref.href;
      var title = ref.title;
      return ["a", {
        href: href,
        title: title
      }, 0];
    }
  },
  // :: MarkSpec An emphasis mark. Rendered as an `<em>` element.
  // Has parse rules that also match `<i>` and `font-style: italic`.
  em: {
    parseDOM: [{
      tag: "i"
    }, {
      tag: "em"
    }, {
      style: "font-style=italic"
    }],
    toDOM: function toDOM() {
      return emDOM;
    }
  },
  // :: MarkSpec A strong mark. Rendered as `<strong>`, parse rules
  // also match `<b>` and `font-weight: bold`.
  strong: {
    parseDOM: [{
      tag: "strong"
    }, // This works around a Google Docs misbehavior where
    // pasted content will be inexplicably wrapped in `<b>`
    // tags with a font-weight normal.
    {
      tag: "b",
      getAttrs: function (node) {
        return node.style.fontWeight != "normal" && null;
      }
    }, {
      style: "font-weight",
      getAttrs: function (value) {
        return /^(bold(er)?|[5-9]\d{2,})$/.test(value) && null;
      }
    }],
    toDOM: function toDOM() {
      return strongDOM;
    }
  },
  // :: MarkSpec Code font mark. Represented as a `<code>` element.
  code: {
    parseDOM: [{
      tag: "code"
    }],
    toDOM: function toDOM() {
      return codeDOM;
    }
  }
}; // :: Schema
// This schema roughly corresponds to the document schema used by
// [CommonMark](http://commonmark.org/), minus the list elements,
// which are defined in the [`prosemirror-schema-list`](#schema-list)
// module.
//
// To reuse elements from this schema, extend or read from its
// `spec.nodes` and `spec.marks` [properties](#model.Schema.spec).

exports.marks = marks;
var schema = new _prosemirrorModel.Schema({
  nodes: nodes,
  marks: marks
});
exports.schema = schema;
},{"prosemirror-model":"../node_modules/prosemirror-model/dist/index.es.js"}],"../node_modules/w3c-keyname/index.es.js":[function(require,module,exports) {
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.keyName = keyName;
exports.shift = exports.base = void 0;
var base = {
  8: "Backspace",
  9: "Tab",
  10: "Enter",
  12: "NumLock",
  13: "Enter",
  16: "Shift",
  17: "Control",
  18: "Alt",
  20: "CapsLock",
  27: "Escape",
  32: " ",
  33: "PageUp",
  34: "PageDown",
  35: "End",
  36: "Home",
  37: "ArrowLeft",
  38: "ArrowUp",
  39: "ArrowRight",
  40: "ArrowDown",
  44: "PrintScreen",
  45: "Insert",
  46: "Delete",
  59: ";",
  61: "=",
  91: "Meta",
  92: "Meta",
  106: "*",
  107: "+",
  108: ",",
  109: "-",
  110: ".",
  111: "/",
  144: "NumLock",
  145: "ScrollLock",
  160: "Shift",
  161: "Shift",
  162: "Control",
  163: "Control",
  164: "Alt",
  165: "Alt",
  173: "-",
  186: ";",
  187: "=",
  188: ",",
  189: "-",
  190: ".",
  191: "/",
  192: "`",
  219: "[",
  220: "\\",
  221: "]",
  222: "'",
  229: "q"
};
exports.base = base;
var shift = {
  48: ")",
  49: "!",
  50: "@",
  51: "#",
  52: "$",
  53: "%",
  54: "^",
  55: "&",
  56: "*",
  57: "(",
  59: ":",
  61: "+",
  173: "_",
  186: ":",
  187: "+",
  188: "<",
  189: "_",
  190: ">",
  191: "?",
  192: "~",
  219: "{",
  220: "|",
  221: "}",
  222: "\"",
  229: "Q"
};
exports.shift = shift;
var chrome = typeof navigator != "undefined" && /Chrome\/(\d+)/.exec(navigator.userAgent);
var safari = typeof navigator != "undefined" && /Apple Computer/.test(navigator.vendor);
var gecko = typeof navigator != "undefined" && /Gecko\/\d+/.test(navigator.userAgent);
var mac = typeof navigator != "undefined" && /Mac/.test(navigator.platform);
var ie = typeof navigator != "undefined" && /MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);
var brokenModifierNames = chrome && (mac || +chrome[1] < 57) || gecko && mac; // Fill in the digit keys

for (var i = 0; i < 10; i++) base[48 + i] = base[96 + i] = String(i); // The function keys


for (var i = 1; i <= 24; i++) base[i + 111] = "F" + i; // And the alphabetic keys


for (var i = 65; i <= 90; i++) {
  base[i] = String.fromCharCode(i + 32);
  shift[i] = String.fromCharCode(i);
} // For each code that doesn't have a shift-equivalent, copy the base name


for (var code in base) if (!shift.hasOwnProperty(code)) shift[code] = base[code];

function keyName(event) {
  // Don't trust event.key in Chrome when there are modifiers until
  // they fix https://bugs.chromium.org/p/chromium/issues/detail?id=633838
  var ignoreKey = brokenModifierNames && (event.ctrlKey || event.altKey || event.metaKey) || (safari || ie) && event.shiftKey && event.key && event.key.length == 1;
  var name = !ignoreKey && event.key || (event.shiftKey ? shift : base)[event.keyCode] || event.key || "Unidentified"; // Edge sometimes produces wrong names (Issue #3)

  if (name == "Esc") name = "Escape";
  if (name == "Del") name = "Delete"; // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8860571/

  if (name == "Left") name = "ArrowLeft";
  if (name == "Up") name = "ArrowUp";
  if (name == "Right") name = "ArrowRight";
  if (name == "Down") name = "ArrowDown";
  return name;
}
},{}],"../node_modules/prosemirror-keymap/dist/index.es.js":[function(require,module,exports) {
"use strict";

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

var _w3cKeyname = require("w3c-keyname");

var _prosemirrorState = require("prosemirror-state");

// declare global: navigator
var mac = typeof navigator != "undefined" ? /Mac/.test(navigator.platform) : false;

function normalizeKeyName(name) {
  var parts = name.split(/-(?!$)/),
      result = parts[parts.length - 1];

  if (result == "Space") {
    result = " ";
  }

  var alt, ctrl, shift, meta;

  for (var i = 0; i < parts.length - 1; i++) {
    var mod = parts[i];

    if (/^(cmd|meta|m)$/i.test(mod)) {
      meta = true;
    } else if (/^a(lt)?$/i.test(mod)) {
      alt = true;
    } else if (/^(c|ctrl|control)$/i.test(mod)) {
      ctrl = true;
    } else if (/^s(hift)?$/i.test(mod)) {
      shift = true;
    } else if (/^mod$/i.test(mod)) {
      if (mac) {
        meta = true;
      } else {
        ctrl = true;
      }
    } else {
      throw new Error("Unrecognized modifier name: " + mod);
    }
  }

  if (alt) {
    result = "Alt-" + result;
  }

  if (ctrl) {
    result = "Ctrl-" + result;
  }

  if (meta) {
    result = "Meta-" + result;
  }

  if (shift) {
    result = "Shift-" + result;
  }

  return result;
}

function normalize(map) {
  var copy = Object.create(null);

  for (var prop in map) {
    copy[normalizeKeyName(prop)] = map[prop];
  }

  return copy;
}

function modifiers(name, event, shift) {
  if (event.altKey) {
    name = "Alt-" + name;
  }

  if (event.ctrlKey) {
    name = "Ctrl-" + name;
  }

  if (event.metaKey) {
    name = "Meta-" + name;
  }

  if (shift !== false && event.shiftKey) {
    name = "Shift-" + name;
  }

  return name;
} // :: (Object) → Plugin
// Create a keymap plugin for the given set of bindings.
//
// Bindings should map key names to [command](#commands)-style
// functions, which will be called with `(EditorState, dispatch,
// EditorView)` arguments, and should return true when they've handled
// the key. Note that the view argument isn't part of the command
// protocol, but can be used as an escape hatch if a binding needs to
// directly interact with the UI.
//
// Key names may be strings like `"Shift-Ctrl-Enter"`—a key
// identifier prefixed with zero or more modifiers. Key identifiers
// are based on the strings that can appear in
// [`KeyEvent.key`](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key).
// Use lowercase letters to refer to letter keys (or uppercase letters
// if you want shift to be held). You may use `"Space"` as an alias
// for the `" "` name.
//
// Modifiers can be given in any order. `Shift-` (or `s-`), `Alt-` (or
// `a-`), `Ctrl-` (or `c-` or `Control-`) and `Cmd-` (or `m-` or
// `Meta-`) are recognized. For characters that are created by holding
// shift, the `Shift-` prefix is implied, and should not be added
// explicitly.
//
// You can use `Mod-` as a shorthand for `Cmd-` on Mac and `Ctrl-` on
// other platforms.
//
// You can add multiple keymap plugins to an editor. The order in
// which they appear determines their precedence (the ones early in
// the array get to dispatch first).


function keymap(bindings) {
  return new _prosemirrorState.Plugin({
    props: {
      handleKeyDown: keydownHandler(bindings)
    }
  });
} // :: (Object) → (view: EditorView, event: dom.Event) → bool
// Given a set of bindings (using the same format as
// [`keymap`](#keymap.keymap), return a [keydown
// handler](#view.EditorProps.handleKeyDown) that handles them.


function keydownHandler(bindings) {
  var map = normalize(bindings);
  return function (view, event) {
    var name = (0, _w3cKeyname.keyName)(event),
        isChar = name.length == 1 && name != " ",
        baseName;
    var direct = map[modifiers(name, event, !isChar)];

    if (direct && direct(view.state, view.dispatch, view)) {
      return true;
    }

    if (isChar && (event.shiftKey || event.altKey || event.metaKey) && (baseName = _w3cKeyname.base[event.keyCode]) && baseName != name) {
      var fromCode = map[modifiers(baseName, event, true)];

      if (fromCode && fromCode(view.state, view.dispatch, view)) {
        return true;
      }
    } else if (isChar && event.shiftKey) {
      var withShift = map[modifiers(name, event, true)];

      if (withShift && withShift(view.state, view.dispatch, view)) {
        return true;
      }
    }

    return false;
  };
}
},{"w3c-keyname":"../node_modules/w3c-keyname/index.es.js","prosemirror-state":"../node_modules/prosemirror-state/dist/index.es.js"}],"../node_modules/rope-sequence/dist/index.es.js":[function(require,module,exports) {
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var GOOD_LEAF_SIZE = 200; // :: class<T> A rope sequence is a persistent sequence data structure
// that supports appending, prepending, and slicing without doing a
// full copy. It is represented as a mostly-balanced tree.

var RopeSequence = function RopeSequence() {};

RopeSequence.prototype.append = function append(other) {
  if (!other.length) {
    return this;
  }

  other = RopeSequence.from(other);
  return !this.length && other || other.length < GOOD_LEAF_SIZE && this.leafAppend(other) || this.length < GOOD_LEAF_SIZE && other.leafPrepend(this) || this.appendInner(other);
}; // :: (union<[T], RopeSequence<T>>) → RopeSequence<T>
// Prepend an array or other rope to this one, returning a new rope.


RopeSequence.prototype.prepend = function prepend(other) {
  if (!other.length) {
    return this;
  }

  return RopeSequence.from(other).append(this);
};

RopeSequence.prototype.appendInner = function appendInner(other) {
  return new Append(this, other);
}; // :: (?number, ?number) → RopeSequence<T>
// Create a rope repesenting a sub-sequence of this rope.


RopeSequence.prototype.slice = function slice(from, to) {
  if (from === void 0) from = 0;
  if (to === void 0) to = this.length;

  if (from >= to) {
    return RopeSequence.empty;
  }

  return this.sliceInner(Math.max(0, from), Math.min(this.length, to));
}; // :: (number) → T
// Retrieve the element at the given position from this rope.


RopeSequence.prototype.get = function get(i) {
  if (i < 0 || i >= this.length) {
    return undefined;
  }

  return this.getInner(i);
}; // :: ((element: T, index: number) → ?bool, ?number, ?number)
// Call the given function for each element between the given
// indices. This tends to be more efficient than looping over the
// indices and calling `get`, because it doesn't have to descend the
// tree for every element.


RopeSequence.prototype.forEach = function forEach(f, from, to) {
  if (from === void 0) from = 0;
  if (to === void 0) to = this.length;

  if (from <= to) {
    this.forEachInner(f, from, to, 0);
  } else {
    this.forEachInvertedInner(f, from, to, 0);
  }
}; // :: ((element: T, index: number) → U, ?number, ?number) → [U]
// Map the given functions over the elements of the rope, producing
// a flat array.


RopeSequence.prototype.map = function map(f, from, to) {
  if (from === void 0) from = 0;
  if (to === void 0) to = this.length;
  var result = [];
  this.forEach(function (elt, i) {
    return result.push(f(elt, i));
  }, from, to);
  return result;
}; // :: (?union<[T], RopeSequence<T>>) → RopeSequence<T>
// Create a rope representing the given array, or return the rope
// itself if a rope was given.


RopeSequence.from = function from(values) {
  if (values instanceof RopeSequence) {
    return values;
  }

  return values && values.length ? new Leaf(values) : RopeSequence.empty;
};

var Leaf = /*@__PURE__*/function (RopeSequence) {
  function Leaf(values) {
    RopeSequence.call(this);
    this.values = values;
  }

  if (RopeSequence) Leaf.__proto__ = RopeSequence;
  Leaf.prototype = Object.create(RopeSequence && RopeSequence.prototype);
  Leaf.prototype.constructor = Leaf;
  var prototypeAccessors = {
    length: {
      configurable: true
    },
    depth: {
      configurable: true
    }
  };

  Leaf.prototype.flatten = function flatten() {
    return this.values;
  };

  Leaf.prototype.sliceInner = function sliceInner(from, to) {
    if (from == 0 && to == this.length) {
      return this;
    }

    return new Leaf(this.values.slice(from, to));
  };

  Leaf.prototype.getInner = function getInner(i) {
    return this.values[i];
  };

  Leaf.prototype.forEachInner = function forEachInner(f, from, to, start) {
    for (var i = from; i < to; i++) {
      if (f(this.values[i], start + i) === false) {
        return false;
      }
    }
  };

  Leaf.prototype.forEachInvertedInner = function forEachInvertedInner(f, from, to, start) {
    for (var i = from - 1; i >= to; i--) {
      if (f(this.values[i], start + i) === false) {
        return false;
      }
    }
  };

  Leaf.prototype.leafAppend = function leafAppend(other) {
    if (this.length + other.length <= GOOD_LEAF_SIZE) {
      return new Leaf(this.values.concat(other.flatten()));
    }
  };

  Leaf.prototype.leafPrepend = function leafPrepend(other) {
    if (this.length + other.length <= GOOD_LEAF_SIZE) {
      return new Leaf(other.flatten().concat(this.values));
    }
  };

  prototypeAccessors.length.get = function () {
    return this.values.length;
  };

  prototypeAccessors.depth.get = function () {
    return 0;
  };

  Object.defineProperties(Leaf.prototype, prototypeAccessors);
  return Leaf;
}(RopeSequence); // :: RopeSequence
// The empty rope sequence.


RopeSequence.empty = new Leaf([]);

var Append = /*@__PURE__*/function (RopeSequence) {
  function Append(left, right) {
    RopeSequence.call(this);
    this.left = left;
    this.right = right;
    this.length = left.length + right.length;
    this.depth = Math.max(left.depth, right.depth) + 1;
  }

  if (RopeSequence) Append.__proto__ = RopeSequence;
  Append.prototype = Object.create(RopeSequence && RopeSequence.prototype);
  Append.prototype.constructor = Append;

  Append.prototype.flatten = function flatten() {
    return this.left.flatten().concat(this.right.flatten());
  };

  Append.prototype.getInner = function getInner(i) {
    return i < this.left.length ? this.left.get(i) : this.right.get(i - this.left.length);
  };

  Append.prototype.forEachInner = function forEachInner(f, from, to, start) {
    var leftLen = this.left.length;

    if (from < leftLen && this.left.forEachInner(f, from, Math.min(to, leftLen), start) === false) {
      return false;
    }

    if (to > leftLen && this.right.forEachInner(f, Math.max(from - leftLen, 0), Math.min(this.length, to) - leftLen, start + leftLen) === false) {
      return false;
    }
  };

  Append.prototype.forEachInvertedInner = function forEachInvertedInner(f, from, to, start) {
    var leftLen = this.left.length;

    if (from > leftLen && this.right.forEachInvertedInner(f, from - leftLen, Math.max(to, leftLen) - leftLen, start + leftLen) === false) {
      return false;
    }

    if (to < leftLen && this.left.forEachInvertedInner(f, Math.min(from, leftLen), to, start) === false) {
      return false;
    }
  };

  Append.prototype.sliceInner = function sliceInner(from, to) {
    if (from == 0 && to == this.length) {
      return this;
    }

    var leftLen = this.left.length;

    if (to <= leftLen) {
      return this.left.slice(from, to);
    }

    if (from >= leftLen) {
      return this.right.slice(from - leftLen, to - leftLen);
    }

    return this.left.slice(from, leftLen).append(this.right.slice(0, to - leftLen));
  };

  Append.prototype.leafAppend = function leafAppend(other) {
    var inner = this.right.leafAppend(other);

    if (inner) {
      return new Append(this.left, inner);
    }
  };

  Append.prototype.leafPrepend = function leafPrepend(other) {
    var inner = this.left.leafPrepend(other);

    if (inner) {
      return new Append(inner, this.right);
    }
  };

  Append.prototype.appendInner = function appendInner(other) {
    if (this.left.depth >= Math.max(this.right.depth, other.depth) + 1) {
      return new Append(this.left, new Append(this.right, other));
    }

    return new Append(this, other);
  };

  return Append;
}(RopeSequence);

var ropeSequence = RopeSequence;
var _default = ropeSequence;
exports.default = _default;
},{}],"../node_modules/prosemirror-history/dist/index.es.js":[function(require,module,exports) {
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.closeHistory = closeHistory;
exports.history = history;
exports.redo = redo;
exports.redoDepth = redoDepth;
exports.undo = undo;
exports.undoDepth = undoDepth;
exports.HistoryState = void 0;

var _ropeSequence = _interopRequireDefault(require("rope-sequence"));

var _prosemirrorTransform = require("prosemirror-transform");

var _prosemirrorState = require("prosemirror-state");

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

// ProseMirror's history isn't simply a way to roll back to a previous
// state, because ProseMirror supports applying changes without adding
// them to the history (for example during collaboration).
//
// To this end, each 'Branch' (one for the undo history and one for
// the redo history) keeps an array of 'Items', which can optionally
// hold a step (an actual undoable change), and always hold a position
// map (which is needed to move changes below them to apply to the
// current document).
//
// An item that has both a step and a selection bookmark is the start
// of an 'event' — a group of changes that will be undone or redone at
// once. (It stores only the bookmark, since that way we don't have to
// provide a document until the selection is actually applied, which
// is useful when compressing.)
// Used to schedule history compression
var max_empty_items = 500;

var Branch = function Branch(items, eventCount) {
  this.items = items;
  this.eventCount = eventCount;
}; // : (EditorState, bool) → ?{transform: Transform, selection: ?SelectionBookmark, remaining: Branch}
// Pop the latest event off the branch's history and apply it
// to a document transform.


Branch.prototype.popEvent = function popEvent(state, preserveItems) {
  var this$1 = this;

  if (this.eventCount == 0) {
    return null;
  }

  var end = this.items.length;

  for (;; end--) {
    var next = this.items.get(end - 1);

    if (next.selection) {
      --end;
      break;
    }
  }

  var remap, mapFrom;

  if (preserveItems) {
    remap = this.remapping(end, this.items.length);
    mapFrom = remap.maps.length;
  }

  var transform = state.tr;
  var selection, remaining;
  var addAfter = [],
      addBefore = [];
  this.items.forEach(function (item, i) {
    if (!item.step) {
      if (!remap) {
        remap = this$1.remapping(end, i + 1);
        mapFrom = remap.maps.length;
      }

      mapFrom--;
      addBefore.push(item);
      return;
    }

    if (remap) {
      addBefore.push(new Item(item.map));
      var step = item.step.map(remap.slice(mapFrom)),
          map;

      if (step && transform.maybeStep(step).doc) {
        map = transform.mapping.maps[transform.mapping.maps.length - 1];
        addAfter.push(new Item(map, null, null, addAfter.length + addBefore.length));
      }

      mapFrom--;

      if (map) {
        remap.appendMap(map, mapFrom);
      }
    } else {
      transform.maybeStep(item.step);
    }

    if (item.selection) {
      selection = remap ? item.selection.map(remap.slice(mapFrom)) : item.selection;
      remaining = new Branch(this$1.items.slice(0, end).append(addBefore.reverse().concat(addAfter)), this$1.eventCount - 1);
      return false;
    }
  }, this.items.length, 0);
  return {
    remaining: remaining,
    transform: transform,
    selection: selection
  };
}; // : (Transform, ?SelectionBookmark, Object) → Branch
// Create a new branch with the given transform added.


Branch.prototype.addTransform = function addTransform(transform, selection, histOptions, preserveItems) {
  var newItems = [],
      eventCount = this.eventCount;
  var oldItems = this.items,
      lastItem = !preserveItems && oldItems.length ? oldItems.get(oldItems.length - 1) : null;

  for (var i = 0; i < transform.steps.length; i++) {
    var step = transform.steps[i].invert(transform.docs[i]);
    var item = new Item(transform.mapping.maps[i], step, selection),
        merged = void 0;

    if (merged = lastItem && lastItem.merge(item)) {
      item = merged;

      if (i) {
        newItems.pop();
      } else {
        oldItems = oldItems.slice(0, oldItems.length - 1);
      }
    }

    newItems.push(item);

    if (selection) {
      eventCount++;
      selection = null;
    }

    if (!preserveItems) {
      lastItem = item;
    }
  }

  var overflow = eventCount - histOptions.depth;

  if (overflow > DEPTH_OVERFLOW) {
    oldItems = cutOffEvents(oldItems, overflow);
    eventCount -= overflow;
  }

  return new Branch(oldItems.append(newItems), eventCount);
};

Branch.prototype.remapping = function remapping(from, to) {
  var maps = new _prosemirrorTransform.Mapping();
  this.items.forEach(function (item, i) {
    var mirrorPos = item.mirrorOffset != null && i - item.mirrorOffset >= from ? maps.maps.length - item.mirrorOffset : null;
    maps.appendMap(item.map, mirrorPos);
  }, from, to);
  return maps;
};

Branch.prototype.addMaps = function addMaps(array) {
  if (this.eventCount == 0) {
    return this;
  }

  return new Branch(this.items.append(array.map(function (map) {
    return new Item(map);
  })), this.eventCount);
}; // : (Transform, number)
// When the collab module receives remote changes, the history has
// to know about those, so that it can adjust the steps that were
// rebased on top of the remote changes, and include the position
// maps for the remote changes in its array of items.


Branch.prototype.rebased = function rebased(rebasedTransform, rebasedCount) {
  if (!this.eventCount) {
    return this;
  }

  var rebasedItems = [],
      start = Math.max(0, this.items.length - rebasedCount);
  var mapping = rebasedTransform.mapping;
  var newUntil = rebasedTransform.steps.length;
  var eventCount = this.eventCount;
  this.items.forEach(function (item) {
    if (item.selection) {
      eventCount--;
    }
  }, start);
  var iRebased = rebasedCount;
  this.items.forEach(function (item) {
    var pos = mapping.getMirror(--iRebased);

    if (pos == null) {
      return;
    }

    newUntil = Math.min(newUntil, pos);
    var map = mapping.maps[pos];

    if (item.step) {
      var step = rebasedTransform.steps[pos].invert(rebasedTransform.docs[pos]);
      var selection = item.selection && item.selection.map(mapping.slice(iRebased + 1, pos));

      if (selection) {
        eventCount++;
      }

      rebasedItems.push(new Item(map, step, selection));
    } else {
      rebasedItems.push(new Item(map));
    }
  }, start);
  var newMaps = [];

  for (var i = rebasedCount; i < newUntil; i++) {
    newMaps.push(new Item(mapping.maps[i]));
  }

  var items = this.items.slice(0, start).append(newMaps).append(rebasedItems);
  var branch = new Branch(items, eventCount);

  if (branch.emptyItemCount() > max_empty_items) {
    branch = branch.compress(this.items.length - rebasedItems.length);
  }

  return branch;
};

Branch.prototype.emptyItemCount = function emptyItemCount() {
  var count = 0;
  this.items.forEach(function (item) {
    if (!item.step) {
      count++;
    }
  });
  return count;
}; // Compressing a branch means rewriting it to push the air (map-only
// items) out. During collaboration, these naturally accumulate
// because each remote change adds one. The `upto` argument is used
// to ensure that only the items below a given level are compressed,
// because `rebased` relies on a clean, untouched set of items in
// order to associate old items with rebased steps.


Branch.prototype.compress = function compress(upto) {
  if (upto === void 0) upto = this.items.length;
  var remap = this.remapping(0, upto),
      mapFrom = remap.maps.length;
  var items = [],
      events = 0;
  this.items.forEach(function (item, i) {
    if (i >= upto) {
      items.push(item);

      if (item.selection) {
        events++;
      }
    } else if (item.step) {
      var step = item.step.map(remap.slice(mapFrom)),
          map = step && step.getMap();
      mapFrom--;

      if (map) {
        remap.appendMap(map, mapFrom);
      }

      if (step) {
        var selection = item.selection && item.selection.map(remap.slice(mapFrom));

        if (selection) {
          events++;
        }

        var newItem = new Item(map.invert(), step, selection),
            merged,
            last = items.length - 1;

        if (merged = items.length && items[last].merge(newItem)) {
          items[last] = merged;
        } else {
          items.push(newItem);
        }
      }
    } else if (item.map) {
      mapFrom--;
    }
  }, this.items.length, 0);
  return new Branch(_ropeSequence.default.from(items.reverse()), events);
};

Branch.empty = new Branch(_ropeSequence.default.empty, 0);

function cutOffEvents(items, n) {
  var cutPoint;
  items.forEach(function (item, i) {
    if (item.selection && n-- == 0) {
      cutPoint = i;
      return false;
    }
  });
  return items.slice(cutPoint);
}

var Item = function Item(map, step, selection, mirrorOffset) {
  // The (forward) step map for this item.
  this.map = map; // The inverted step

  this.step = step; // If this is non-null, this item is the start of a group, and
  // this selection is the starting selection for the group (the one
  // that was active before the first step was applied)

  this.selection = selection; // If this item is the inverse of a previous mapping on the stack,
  // this points at the inverse's offset

  this.mirrorOffset = mirrorOffset;
};

Item.prototype.merge = function merge(other) {
  if (this.step && other.step && !other.selection) {
    var step = other.step.merge(this.step);

    if (step) {
      return new Item(step.getMap().invert(), step, this.selection);
    }
  }
}; // The value of the state field that tracks undo/redo history for that
// state. Will be stored in the plugin state when the history plugin
// is active.


var HistoryState = function HistoryState(done, undone, prevRanges, prevTime) {
  this.done = done;
  this.undone = undone;
  this.prevRanges = prevRanges;
  this.prevTime = prevTime;
};

exports.HistoryState = HistoryState;
var DEPTH_OVERFLOW = 20; // : (HistoryState, EditorState, Transaction, Object)
// Record a transformation in undo history.

function applyTransaction(history, state, tr, options) {
  var historyTr = tr.getMeta(historyKey),
      rebased;

  if (historyTr) {
    return historyTr.historyState;
  }

  if (tr.getMeta(closeHistoryKey)) {
    history = new HistoryState(history.done, history.undone, null, 0);
  }

  var appended = tr.getMeta("appendedTransaction");

  if (tr.steps.length == 0) {
    return history;
  } else if (appended && appended.getMeta(historyKey)) {
    if (appended.getMeta(historyKey).redo) {
      return new HistoryState(history.done.addTransform(tr, null, options, mustPreserveItems(state)), history.undone, rangesFor(tr.mapping.maps[tr.steps.length - 1]), history.prevTime);
    } else {
      return new HistoryState(history.done, history.undone.addTransform(tr, null, options, mustPreserveItems(state)), null, history.prevTime);
    }
  } else if (tr.getMeta("addToHistory") !== false && !(appended && appended.getMeta("addToHistory") === false)) {
    // Group transforms that occur in quick succession into one event.
    var newGroup = history.prevTime == 0 || !appended && (history.prevTime < (tr.time || 0) - options.newGroupDelay || !isAdjacentTo(tr, history.prevRanges));
    var prevRanges = appended ? mapRanges(history.prevRanges, tr.mapping) : rangesFor(tr.mapping.maps[tr.steps.length - 1]);
    return new HistoryState(history.done.addTransform(tr, newGroup ? state.selection.getBookmark() : null, options, mustPreserveItems(state)), Branch.empty, prevRanges, tr.time);
  } else if (rebased = tr.getMeta("rebased")) {
    // Used by the collab module to tell the history that some of its
    // content has been rebased.
    return new HistoryState(history.done.rebased(tr, rebased), history.undone.rebased(tr, rebased), mapRanges(history.prevRanges, tr.mapping), history.prevTime);
  } else {
    return new HistoryState(history.done.addMaps(tr.mapping.maps), history.undone.addMaps(tr.mapping.maps), mapRanges(history.prevRanges, tr.mapping), history.prevTime);
  }
}

function isAdjacentTo(transform, prevRanges) {
  if (!prevRanges) {
    return false;
  }

  if (!transform.docChanged) {
    return true;
  }

  var adjacent = false;
  transform.mapping.maps[0].forEach(function (start, end) {
    for (var i = 0; i < prevRanges.length; i += 2) {
      if (start <= prevRanges[i + 1] && end >= prevRanges[i]) {
        adjacent = true;
      }
    }
  });
  return adjacent;
}

function rangesFor(map) {
  var result = [];
  map.forEach(function (_from, _to, from, to) {
    return result.push(from, to);
  });
  return result;
}

function mapRanges(ranges, mapping) {
  if (!ranges) {
    return null;
  }

  var result = [];

  for (var i = 0; i < ranges.length; i += 2) {
    var from = mapping.map(ranges[i], 1),
        to = mapping.map(ranges[i + 1], -1);

    if (from <= to) {
      result.push(from, to);
    }
  }

  return result;
} // : (HistoryState, EditorState, (tr: Transaction), bool)
// Apply the latest event from one branch to the document and shift the event
// onto the other branch.


function histTransaction(history, state, dispatch, redo) {
  var preserveItems = mustPreserveItems(state),
      histOptions = historyKey.get(state).spec.config;
  var pop = (redo ? history.undone : history.done).popEvent(state, preserveItems);

  if (!pop) {
    return;
  }

  var selection = pop.selection.resolve(pop.transform.doc);
  var added = (redo ? history.done : history.undone).addTransform(pop.transform, state.selection.getBookmark(), histOptions, preserveItems);
  var newHist = new HistoryState(redo ? added : pop.remaining, redo ? pop.remaining : added, null, 0);
  dispatch(pop.transform.setSelection(selection).setMeta(historyKey, {
    redo: redo,
    historyState: newHist
  }).scrollIntoView());
}

var cachedPreserveItems = false,
    cachedPreserveItemsPlugins = null; // Check whether any plugin in the given state has a
// `historyPreserveItems` property in its spec, in which case we must
// preserve steps exactly as they came in, so that they can be
// rebased.

function mustPreserveItems(state) {
  var plugins = state.plugins;

  if (cachedPreserveItemsPlugins != plugins) {
    cachedPreserveItems = false;
    cachedPreserveItemsPlugins = plugins;

    for (var i = 0; i < plugins.length; i++) {
      if (plugins[i].spec.historyPreserveItems) {
        cachedPreserveItems = true;
        break;
      }
    }
  }

  return cachedPreserveItems;
} // :: (Transaction) → Transaction
// Set a flag on the given transaction that will prevent further steps
// from being appended to an existing history event (so that they
// require a separate undo command to undo).


function closeHistory(tr) {
  return tr.setMeta(closeHistoryKey, true);
}

var historyKey = new _prosemirrorState.PluginKey("history");
var closeHistoryKey = new _prosemirrorState.PluginKey("closeHistory"); // :: (?Object) → Plugin
// Returns a plugin that enables the undo history for an editor. The
// plugin will track undo and redo stacks, which can be used with the
// [`undo`](#history.undo) and [`redo`](#history.redo) commands.
//
// You can set an `"addToHistory"` [metadata
// property](#state.Transaction.setMeta) of `false` on a transaction
// to prevent it from being rolled back by undo.
//
//   config::-
//   Supports the following configuration options:
//
//     depth:: ?number
//     The amount of history events that are collected before the
//     oldest events are discarded. Defaults to 100.
//
//     newGroupDelay:: ?number
//     The delay between changes after which a new group should be
//     started. Defaults to 500 (milliseconds). Note that when changes
//     aren't adjacent, a new group is always started.

function history(config) {
  config = {
    depth: config && config.depth || 100,
    newGroupDelay: config && config.newGroupDelay || 500
  };
  return new _prosemirrorState.Plugin({
    key: historyKey,
    state: {
      init: function init() {
        return new HistoryState(Branch.empty, Branch.empty, null, 0);
      },
      apply: function apply(tr, hist, state) {
        return applyTransaction(hist, state, tr, config);
      }
    },
    config: config
  });
} // :: (EditorState, ?(tr: Transaction)) → bool
// A command function that undoes the last change, if any.


function undo(state, dispatch) {
  var hist = historyKey.getState(state);

  if (!hist || hist.done.eventCount == 0) {
    return false;
  }

  if (dispatch) {
    histTransaction(hist, state, dispatch, false);
  }

  return true;
} // :: (EditorState, ?(tr: Transaction)) → bool
// A command function that redoes the last undone change, if any.


function redo(state, dispatch) {
  var hist = historyKey.getState(state);

  if (!hist || hist.undone.eventCount == 0) {
    return false;
  }

  if (dispatch) {
    histTransaction(hist, state, dispatch, true);
  }

  return true;
} // :: (EditorState) → number
// The amount of undoable events available in a given state.


function undoDepth(state) {
  var hist = historyKey.getState(state);
  return hist ? hist.done.eventCount : 0;
} // :: (EditorState) → number
// The amount of redoable events available in a given editor state.


function redoDepth(state) {
  var hist = historyKey.getState(state);
  return hist ? hist.undone.eventCount : 0;
}
},{"rope-sequence":"../node_modules/rope-sequence/dist/index.es.js","prosemirror-transform":"../node_modules/prosemirror-transform/dist/index.es.js","prosemirror-state":"../node_modules/prosemirror-state/dist/index.es.js"}],"../node_modules/prosemirror-commands/dist/index.es.js":[function(require,module,exports) {
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.autoJoin = autoJoin;
exports.chainCommands = chainCommands;
exports.createParagraphNear = createParagraphNear;
exports.deleteSelection = deleteSelection;
exports.exitCode = exitCode;
exports.joinBackward = joinBackward;
exports.joinDown = joinDown;
exports.joinForward = joinForward;
exports.joinUp = joinUp;
exports.lift = lift;
exports.liftEmptyBlock = liftEmptyBlock;
exports.newlineInCode = newlineInCode;
exports.selectAll = selectAll;
exports.selectNodeBackward = selectNodeBackward;
exports.selectNodeForward = selectNodeForward;
exports.selectParentNode = selectParentNode;
exports.setBlockType = setBlockType;
exports.splitBlock = splitBlock;
exports.splitBlockKeepMarks = splitBlockKeepMarks;
exports.toggleMark = toggleMark;
exports.wrapIn = wrapIn;
exports.pcBaseKeymap = exports.macBaseKeymap = exports.baseKeymap = void 0;

var _prosemirrorTransform = require("prosemirror-transform");

var _prosemirrorModel = require("prosemirror-model");

var _prosemirrorState = require("prosemirror-state");

// :: (EditorState, ?(tr: Transaction)) → bool
// Delete the selection, if there is one.
function deleteSelection(state, dispatch) {
  if (state.selection.empty) {
    return false;
  }

  if (dispatch) {
    dispatch(state.tr.deleteSelection().scrollIntoView());
  }

  return true;
} // :: (EditorState, ?(tr: Transaction), ?EditorView) → bool
// If the selection is empty and at the start of a textblock, try to
// reduce the distance between that block and the one before it—if
// there's a block directly before it that can be joined, join them.
// If not, try to move the selected block closer to the next one in
// the document structure by lifting it out of its parent or moving it
// into a parent of the previous block. Will use the view for accurate
// (bidi-aware) start-of-textblock detection if given.


function joinBackward(state, dispatch, view) {
  var ref = state.selection;
  var $cursor = ref.$cursor;

  if (!$cursor || (view ? !view.endOfTextblock("backward", state) : $cursor.parentOffset > 0)) {
    return false;
  }

  var $cut = findCutBefore($cursor); // If there is no node before this, try to lift

  if (!$cut) {
    var range = $cursor.blockRange(),
        target = range && (0, _prosemirrorTransform.liftTarget)(range);

    if (target == null) {
      return false;
    }

    if (dispatch) {
      dispatch(state.tr.lift(range, target).scrollIntoView());
    }

    return true;
  }

  var before = $cut.nodeBefore; // Apply the joining algorithm

  if (!before.type.spec.isolating && deleteBarrier(state, $cut, dispatch)) {
    return true;
  } // If the node below has no content and the node above is
  // selectable, delete the node below and select the one above.


  if ($cursor.parent.content.size == 0 && (textblockAt(before, "end") || _prosemirrorState.NodeSelection.isSelectable(before))) {
    if (dispatch) {
      var tr = state.tr.deleteRange($cursor.before(), $cursor.after());
      tr.setSelection(textblockAt(before, "end") ? _prosemirrorState.Selection.findFrom(tr.doc.resolve(tr.mapping.map($cut.pos, -1)), -1) : _prosemirrorState.NodeSelection.create(tr.doc, $cut.pos - before.nodeSize));
      dispatch(tr.scrollIntoView());
    }

    return true;
  } // If the node before is an atom, delete it


  if (before.isAtom && $cut.depth == $cursor.depth - 1) {
    if (dispatch) {
      dispatch(state.tr.delete($cut.pos - before.nodeSize, $cut.pos).scrollIntoView());
    }

    return true;
  }

  return false;
}

function textblockAt(node, side) {
  for (; node; node = side == "start" ? node.firstChild : node.lastChild) {
    if (node.isTextblock) {
      return true;
    }
  }

  return false;
} // :: (EditorState, ?(tr: Transaction), ?EditorView) → bool
// When the selection is empty and at the start of a textblock, select
// the node before that textblock, if possible. This is intended to be
// bound to keys like backspace, after
// [`joinBackward`](#commands.joinBackward) or other deleting
// commands, as a fall-back behavior when the schema doesn't allow
// deletion at the selected point.


function selectNodeBackward(state, dispatch, view) {
  var ref = state.selection;
  var $head = ref.$head;
  var empty = ref.empty;
  var $cut = $head;

  if (!empty) {
    return false;
  }

  if ($head.parent.isTextblock) {
    if (view ? !view.endOfTextblock("backward", state) : $head.parentOffset > 0) {
      return false;
    }

    $cut = findCutBefore($head);
  }

  var node = $cut && $cut.nodeBefore;

  if (!node || !_prosemirrorState.NodeSelection.isSelectable(node)) {
    return false;
  }

  if (dispatch) {
    dispatch(state.tr.setSelection(_prosemirrorState.NodeSelection.create(state.doc, $cut.pos - node.nodeSize)).scrollIntoView());
  }

  return true;
}

function findCutBefore($pos) {
  if (!$pos.parent.type.spec.isolating) {
    for (var i = $pos.depth - 1; i >= 0; i--) {
      if ($pos.index(i) > 0) {
        return $pos.doc.resolve($pos.before(i + 1));
      }

      if ($pos.node(i).type.spec.isolating) {
        break;
      }
    }
  }

  return null;
} // :: (EditorState, ?(tr: Transaction), ?EditorView) → bool
// If the selection is empty and the cursor is at the end of a
// textblock, try to reduce or remove the boundary between that block
// and the one after it, either by joining them or by moving the other
// block closer to this one in the tree structure. Will use the view
// for accurate start-of-textblock detection if given.


function joinForward(state, dispatch, view) {
  var ref = state.selection;
  var $cursor = ref.$cursor;

  if (!$cursor || (view ? !view.endOfTextblock("forward", state) : $cursor.parentOffset < $cursor.parent.content.size)) {
    return false;
  }

  var $cut = findCutAfter($cursor); // If there is no node after this, there's nothing to do

  if (!$cut) {
    return false;
  }

  var after = $cut.nodeAfter; // Try the joining algorithm

  if (deleteBarrier(state, $cut, dispatch)) {
    return true;
  } // If the node above has no content and the node below is
  // selectable, delete the node above and select the one below.


  if ($cursor.parent.content.size == 0 && (textblockAt(after, "start") || _prosemirrorState.NodeSelection.isSelectable(after))) {
    if (dispatch) {
      var tr = state.tr.deleteRange($cursor.before(), $cursor.after());
      tr.setSelection(textblockAt(after, "start") ? _prosemirrorState.Selection.findFrom(tr.doc.resolve(tr.mapping.map($cut.pos)), 1) : _prosemirrorState.NodeSelection.create(tr.doc, tr.mapping.map($cut.pos)));
      dispatch(tr.scrollIntoView());
    }

    return true;
  } // If the next node is an atom, delete it


  if (after.isAtom && $cut.depth == $cursor.depth - 1) {
    if (dispatch) {
      dispatch(state.tr.delete($cut.pos, $cut.pos + after.nodeSize).scrollIntoView());
    }

    return true;
  }

  return false;
} // :: (EditorState, ?(tr: Transaction), ?EditorView) → bool
// When the selection is empty and at the end of a textblock, select
// the node coming after that textblock, if possible. This is intended
// to be bound to keys like delete, after
// [`joinForward`](#commands.joinForward) and similar deleting
// commands, to provide a fall-back behavior when the schema doesn't
// allow deletion at the selected point.


function selectNodeForward(state, dispatch, view) {
  var ref = state.selection;
  var $head = ref.$head;
  var empty = ref.empty;
  var $cut = $head;

  if (!empty) {
    return false;
  }

  if ($head.parent.isTextblock) {
    if (view ? !view.endOfTextblock("forward", state) : $head.parentOffset < $head.parent.content.size) {
      return false;
    }

    $cut = findCutAfter($head);
  }

  var node = $cut && $cut.nodeAfter;

  if (!node || !_prosemirrorState.NodeSelection.isSelectable(node)) {
    return false;
  }

  if (dispatch) {
    dispatch(state.tr.setSelection(_prosemirrorState.NodeSelection.create(state.doc, $cut.pos)).scrollIntoView());
  }

  return true;
}

function findCutAfter($pos) {
  if (!$pos.parent.type.spec.isolating) {
    for (var i = $pos.depth - 1; i >= 0; i--) {
      var parent = $pos.node(i);

      if ($pos.index(i) + 1 < parent.childCount) {
        return $pos.doc.resolve($pos.after(i + 1));
      }

      if (parent.type.spec.isolating) {
        break;
      }
    }
  }

  return null;
} // :: (EditorState, ?(tr: Transaction)) → bool
// Join the selected block or, if there is a text selection, the
// closest ancestor block of the selection that can be joined, with
// the sibling above it.


function joinUp(state, dispatch) {
  var sel = state.selection,
      nodeSel = sel instanceof _prosemirrorState.NodeSelection,
      point;

  if (nodeSel) {
    if (sel.node.isTextblock || !(0, _prosemirrorTransform.canJoin)(state.doc, sel.from)) {
      return false;
    }

    point = sel.from;
  } else {
    point = (0, _prosemirrorTransform.joinPoint)(state.doc, sel.from, -1);

    if (point == null) {
      return false;
    }
  }

  if (dispatch) {
    var tr = state.tr.join(point);

    if (nodeSel) {
      tr.setSelection(_prosemirrorState.NodeSelection.create(tr.doc, point - state.doc.resolve(point).nodeBefore.nodeSize));
    }

    dispatch(tr.scrollIntoView());
  }

  return true;
} // :: (EditorState, ?(tr: Transaction)) → bool
// Join the selected block, or the closest ancestor of the selection
// that can be joined, with the sibling after it.


function joinDown(state, dispatch) {
  var sel = state.selection,
      point;

  if (sel instanceof _prosemirrorState.NodeSelection) {
    if (sel.node.isTextblock || !(0, _prosemirrorTransform.canJoin)(state.doc, sel.to)) {
      return false;
    }

    point = sel.to;
  } else {
    point = (0, _prosemirrorTransform.joinPoint)(state.doc, sel.to, 1);

    if (point == null) {
      return false;
    }
  }

  if (dispatch) {
    dispatch(state.tr.join(point).scrollIntoView());
  }

  return true;
} // :: (EditorState, ?(tr: Transaction)) → bool
// Lift the selected block, or the closest ancestor block of the
// selection that can be lifted, out of its parent node.


function lift(state, dispatch) {
  var ref = state.selection;
  var $from = ref.$from;
  var $to = ref.$to;
  var range = $from.blockRange($to),
      target = range && (0, _prosemirrorTransform.liftTarget)(range);

  if (target == null) {
    return false;
  }

  if (dispatch) {
    dispatch(state.tr.lift(range, target).scrollIntoView());
  }

  return true;
} // :: (EditorState, ?(tr: Transaction)) → bool
// If the selection is in a node whose type has a truthy
// [`code`](#model.NodeSpec.code) property in its spec, replace the
// selection with a newline character.


function newlineInCode(state, dispatch) {
  var ref = state.selection;
  var $head = ref.$head;
  var $anchor = ref.$anchor;

  if (!$head.parent.type.spec.code || !$head.sameParent($anchor)) {
    return false;
  }

  if (dispatch) {
    dispatch(state.tr.insertText("\n").scrollIntoView());
  }

  return true;
}

function defaultBlockAt(match) {
  for (var i = 0; i < match.edgeCount; i++) {
    var ref = match.edge(i);
    var type = ref.type;

    if (type.isTextblock && !type.hasRequiredAttrs()) {
      return type;
    }
  }

  return null;
} // :: (EditorState, ?(tr: Transaction)) → bool
// When the selection is in a node with a truthy
// [`code`](#model.NodeSpec.code) property in its spec, create a
// default block after the code block, and move the cursor there.


function exitCode(state, dispatch) {
  var ref = state.selection;
  var $head = ref.$head;
  var $anchor = ref.$anchor;

  if (!$head.parent.type.spec.code || !$head.sameParent($anchor)) {
    return false;
  }

  var above = $head.node(-1),
      after = $head.indexAfter(-1),
      type = defaultBlockAt(above.contentMatchAt(after));

  if (!above.canReplaceWith(after, after, type)) {
    return false;
  }

  if (dispatch) {
    var pos = $head.after(),
        tr = state.tr.replaceWith(pos, pos, type.createAndFill());
    tr.setSelection(_prosemirrorState.Selection.near(tr.doc.resolve(pos), 1));
    dispatch(tr.scrollIntoView());
  }

  return true;
} // :: (EditorState, ?(tr: Transaction)) → bool
// If a block node is selected, create an empty paragraph before (if
// it is its parent's first child) or after it.


function createParagraphNear(state, dispatch) {
  var ref = state.selection;
  var $from = ref.$from;
  var $to = ref.$to;

  if ($from.parent.inlineContent || $to.parent.inlineContent) {
    return false;
  }

  var type = defaultBlockAt($from.parent.contentMatchAt($to.indexAfter()));

  if (!type || !type.isTextblock) {
    return false;
  }

  if (dispatch) {
    var side = (!$from.parentOffset && $to.index() < $to.parent.childCount ? $from : $to).pos;
    var tr = state.tr.insert(side, type.createAndFill());
    tr.setSelection(_prosemirrorState.TextSelection.create(tr.doc, side + 1));
    dispatch(tr.scrollIntoView());
  }

  return true;
} // :: (EditorState, ?(tr: Transaction)) → bool
// If the cursor is in an empty textblock that can be lifted, lift the
// block.


function liftEmptyBlock(state, dispatch) {
  var ref = state.selection;
  var $cursor = ref.$cursor;

  if (!$cursor || $cursor.parent.content.size) {
    return false;
  }

  if ($cursor.depth > 1 && $cursor.after() != $cursor.end(-1)) {
    var before = $cursor.before();

    if ((0, _prosemirrorTransform.canSplit)(state.doc, before)) {
      if (dispatch) {
        dispatch(state.tr.split(before).scrollIntoView());
      }

      return true;
    }
  }

  var range = $cursor.blockRange(),
      target = range && (0, _prosemirrorTransform.liftTarget)(range);

  if (target == null) {
    return false;
  }

  if (dispatch) {
    dispatch(state.tr.lift(range, target).scrollIntoView());
  }

  return true;
} // :: (EditorState, ?(tr: Transaction)) → bool
// Split the parent block of the selection. If the selection is a text
// selection, also delete its content.


function splitBlock(state, dispatch) {
  var ref = state.selection;
  var $from = ref.$from;
  var $to = ref.$to;

  if (state.selection instanceof _prosemirrorState.NodeSelection && state.selection.node.isBlock) {
    if (!$from.parentOffset || !(0, _prosemirrorTransform.canSplit)(state.doc, $from.pos)) {
      return false;
    }

    if (dispatch) {
      dispatch(state.tr.split($from.pos).scrollIntoView());
    }

    return true;
  }

  if (!$from.parent.isBlock) {
    return false;
  }

  if (dispatch) {
    var atEnd = $to.parentOffset == $to.parent.content.size;
    var tr = state.tr;

    if (state.selection instanceof _prosemirrorState.TextSelection) {
      tr.deleteSelection();
    }

    var deflt = $from.depth == 0 ? null : defaultBlockAt($from.node(-1).contentMatchAt($from.indexAfter(-1)));
    var types = atEnd && deflt ? [{
      type: deflt
    }] : null;
    var can = (0, _prosemirrorTransform.canSplit)(tr.doc, tr.mapping.map($from.pos), 1, types);

    if (!types && !can && (0, _prosemirrorTransform.canSplit)(tr.doc, tr.mapping.map($from.pos), 1, deflt && [{
      type: deflt
    }])) {
      types = [{
        type: deflt
      }];
      can = true;
    }

    if (can) {
      tr.split(tr.mapping.map($from.pos), 1, types);

      if (!atEnd && !$from.parentOffset && $from.parent.type != deflt && $from.node(-1).canReplace($from.index(-1), $from.indexAfter(-1), _prosemirrorModel.Fragment.from(deflt.create(), $from.parent))) {
        tr.setNodeMarkup(tr.mapping.map($from.before()), deflt);
      }
    }

    dispatch(tr.scrollIntoView());
  }

  return true;
} // :: (EditorState, ?(tr: Transaction)) → bool
// Acts like [`splitBlock`](#commands.splitBlock), but without
// resetting the set of active marks at the cursor.


function splitBlockKeepMarks(state, dispatch) {
  return splitBlock(state, dispatch && function (tr) {
    var marks = state.storedMarks || state.selection.$to.parentOffset && state.selection.$from.marks();

    if (marks) {
      tr.ensureMarks(marks);
    }

    dispatch(tr);
  });
} // :: (EditorState, ?(tr: Transaction)) → bool
// Move the selection to the node wrapping the current selection, if
// any. (Will not select the document node.)


function selectParentNode(state, dispatch) {
  var ref = state.selection;
  var $from = ref.$from;
  var to = ref.to;
  var pos;
  var same = $from.sharedDepth(to);

  if (same == 0) {
    return false;
  }

  pos = $from.before(same);

  if (dispatch) {
    dispatch(state.tr.setSelection(_prosemirrorState.NodeSelection.create(state.doc, pos)));
  }

  return true;
} // :: (EditorState, ?(tr: Transaction)) → bool
// Select the whole document.


function selectAll(state, dispatch) {
  if (dispatch) {
    dispatch(state.tr.setSelection(new _prosemirrorState.AllSelection(state.doc)));
  }

  return true;
}

function joinMaybeClear(state, $pos, dispatch) {
  var before = $pos.nodeBefore,
      after = $pos.nodeAfter,
      index = $pos.index();

  if (!before || !after || !before.type.compatibleContent(after.type)) {
    return false;
  }

  if (!before.content.size && $pos.parent.canReplace(index - 1, index)) {
    if (dispatch) {
      dispatch(state.tr.delete($pos.pos - before.nodeSize, $pos.pos).scrollIntoView());
    }

    return true;
  }

  if (!$pos.parent.canReplace(index, index + 1) || !(after.isTextblock || (0, _prosemirrorTransform.canJoin)(state.doc, $pos.pos))) {
    return false;
  }

  if (dispatch) {
    dispatch(state.tr.clearIncompatible($pos.pos, before.type, before.contentMatchAt(before.childCount)).join($pos.pos).scrollIntoView());
  }

  return true;
}

function deleteBarrier(state, $cut, dispatch) {
  var before = $cut.nodeBefore,
      after = $cut.nodeAfter,
      conn,
      match;

  if (before.type.spec.isolating || after.type.spec.isolating) {
    return false;
  }

  if (joinMaybeClear(state, $cut, dispatch)) {
    return true;
  }

  if ($cut.parent.canReplace($cut.index(), $cut.index() + 1) && (conn = (match = before.contentMatchAt(before.childCount)).findWrapping(after.type)) && match.matchType(conn[0] || after.type).validEnd) {
    if (dispatch) {
      var end = $cut.pos + after.nodeSize,
          wrap = _prosemirrorModel.Fragment.empty;

      for (var i = conn.length - 1; i >= 0; i--) {
        wrap = _prosemirrorModel.Fragment.from(conn[i].create(null, wrap));
      }

      wrap = _prosemirrorModel.Fragment.from(before.copy(wrap));
      var tr = state.tr.step(new _prosemirrorTransform.ReplaceAroundStep($cut.pos - 1, end, $cut.pos, end, new _prosemirrorModel.Slice(wrap, 1, 0), conn.length, true));
      var joinAt = end + 2 * conn.length;

      if ((0, _prosemirrorTransform.canJoin)(tr.doc, joinAt)) {
        tr.join(joinAt);
      }

      dispatch(tr.scrollIntoView());
    }

    return true;
  }

  var selAfter = _prosemirrorState.Selection.findFrom($cut, 1);

  var range = selAfter && selAfter.$from.blockRange(selAfter.$to),
      target = range && (0, _prosemirrorTransform.liftTarget)(range);

  if (target != null && target >= $cut.depth) {
    if (dispatch) {
      dispatch(state.tr.lift(range, target).scrollIntoView());
    }

    return true;
  }

  return false;
} // Parameterized commands
// :: (NodeType, ?Object) → (state: EditorState, dispatch: ?(tr: Transaction)) → bool
// Wrap the selection in a node of the given type with the given
// attributes.


function wrapIn(nodeType, attrs) {
  return function (state, dispatch) {
    var ref = state.selection;
    var $from = ref.$from;
    var $to = ref.$to;
    var range = $from.blockRange($to),
        wrapping = range && (0, _prosemirrorTransform.findWrapping)(range, nodeType, attrs);

    if (!wrapping) {
      return false;
    }

    if (dispatch) {
      dispatch(state.tr.wrap(range, wrapping).scrollIntoView());
    }

    return true;
  };
} // :: (NodeType, ?Object) → (state: EditorState, dispatch: ?(tr: Transaction)) → bool
// Returns a command that tries to set the selected textblocks to the
// given node type with the given attributes.


function setBlockType(nodeType, attrs) {
  return function (state, dispatch) {
    var ref = state.selection;
    var from = ref.from;
    var to = ref.to;
    var applicable = false;
    state.doc.nodesBetween(from, to, function (node, pos) {
      if (applicable) {
        return false;
      }

      if (!node.isTextblock || node.hasMarkup(nodeType, attrs)) {
        return;
      }

      if (node.type == nodeType) {
        applicable = true;
      } else {
        var $pos = state.doc.resolve(pos),
            index = $pos.index();
        applicable = $pos.parent.canReplaceWith(index, index + 1, nodeType);
      }
    });

    if (!applicable) {
      return false;
    }

    if (dispatch) {
      dispatch(state.tr.setBlockType(from, to, nodeType, attrs).scrollIntoView());
    }

    return true;
  };
}

function markApplies(doc, ranges, type) {
  var loop = function (i) {
    var ref = ranges[i];
    var $from = ref.$from;
    var $to = ref.$to;
    var can = $from.depth == 0 ? doc.type.allowsMarkType(type) : false;
    doc.nodesBetween($from.pos, $to.pos, function (node) {
      if (can) {
        return false;
      }

      can = node.inlineContent && node.type.allowsMarkType(type);
    });

    if (can) {
      return {
        v: true
      };
    }
  };

  for (var i = 0; i < ranges.length; i++) {
    var returned = loop(i);
    if (returned) return returned.v;
  }

  return false;
} // :: (MarkType, ?Object) → (state: EditorState, dispatch: ?(tr: Transaction)) → bool
// Create a command function that toggles the given mark with the
// given attributes. Will return `false` when the current selection
// doesn't support that mark. This will remove the mark if any marks
// of that type exist in the selection, or add it otherwise. If the
// selection is empty, this applies to the [stored
// marks](#state.EditorState.storedMarks) instead of a range of the
// document.


function toggleMark(markType, attrs) {
  return function (state, dispatch) {
    var ref = state.selection;
    var empty = ref.empty;
    var $cursor = ref.$cursor;
    var ranges = ref.ranges;

    if (empty && !$cursor || !markApplies(state.doc, ranges, markType)) {
      return false;
    }

    if (dispatch) {
      if ($cursor) {
        if (markType.isInSet(state.storedMarks || $cursor.marks())) {
          dispatch(state.tr.removeStoredMark(markType));
        } else {
          dispatch(state.tr.addStoredMark(markType.create(attrs)));
        }
      } else {
        var has = false,
            tr = state.tr;

        for (var i = 0; !has && i < ranges.length; i++) {
          var ref$1 = ranges[i];
          var $from = ref$1.$from;
          var $to = ref$1.$to;
          has = state.doc.rangeHasMark($from.pos, $to.pos, markType);
        }

        for (var i$1 = 0; i$1 < ranges.length; i$1++) {
          var ref$2 = ranges[i$1];
          var $from$1 = ref$2.$from;
          var $to$1 = ref$2.$to;

          if (has) {
            tr.removeMark($from$1.pos, $to$1.pos, markType);
          } else {
            tr.addMark($from$1.pos, $to$1.pos, markType.create(attrs));
          }
        }

        dispatch(tr.scrollIntoView());
      }
    }

    return true;
  };
}

function wrapDispatchForJoin(dispatch, isJoinable) {
  return function (tr) {
    if (!tr.isGeneric) {
      return dispatch(tr);
    }

    var ranges = [];

    for (var i = 0; i < tr.mapping.maps.length; i++) {
      var map = tr.mapping.maps[i];

      for (var j = 0; j < ranges.length; j++) {
        ranges[j] = map.map(ranges[j]);
      }

      map.forEach(function (_s, _e, from, to) {
        return ranges.push(from, to);
      });
    } // Figure out which joinable points exist inside those ranges,
    // by checking all node boundaries in their parent nodes.


    var joinable = [];

    for (var i$1 = 0; i$1 < ranges.length; i$1 += 2) {
      var from = ranges[i$1],
          to = ranges[i$1 + 1];
      var $from = tr.doc.resolve(from),
          depth = $from.sharedDepth(to),
          parent = $from.node(depth);

      for (var index = $from.indexAfter(depth), pos = $from.after(depth + 1); pos <= to; ++index) {
        var after = parent.maybeChild(index);

        if (!after) {
          break;
        }

        if (index && joinable.indexOf(pos) == -1) {
          var before = parent.child(index - 1);

          if (before.type == after.type && isJoinable(before, after)) {
            joinable.push(pos);
          }
        }

        pos += after.nodeSize;
      }
    } // Join the joinable points


    joinable.sort(function (a, b) {
      return a - b;
    });

    for (var i$2 = joinable.length - 1; i$2 >= 0; i$2--) {
      if ((0, _prosemirrorTransform.canJoin)(tr.doc, joinable[i$2])) {
        tr.join(joinable[i$2]);
      }
    }

    dispatch(tr);
  };
} // :: ((state: EditorState, ?(tr: Transaction)) → bool, union<(before: Node, after: Node) → bool, [string]>) → (state: EditorState, ?(tr: Transaction)) → bool
// Wrap a command so that, when it produces a transform that causes
// two joinable nodes to end up next to each other, those are joined.
// Nodes are considered joinable when they are of the same type and
// when the `isJoinable` predicate returns true for them or, if an
// array of strings was passed, if their node type name is in that
// array.


function autoJoin(command, isJoinable) {
  if (Array.isArray(isJoinable)) {
    var types = isJoinable;

    isJoinable = function (node) {
      return types.indexOf(node.type.name) > -1;
    };
  }

  return function (state, dispatch) {
    return command(state, dispatch && wrapDispatchForJoin(dispatch, isJoinable));
  };
} // :: (...[(EditorState, ?(tr: Transaction), ?EditorView) → bool]) → (EditorState, ?(tr: Transaction), ?EditorView) → bool
// Combine a number of command functions into a single function (which
// calls them one by one until one returns true).


function chainCommands() {
  var commands = [],
      len = arguments.length;

  while (len--) commands[len] = arguments[len];

  return function (state, dispatch, view) {
    for (var i = 0; i < commands.length; i++) {
      if (commands[i](state, dispatch, view)) {
        return true;
      }
    }

    return false;
  };
}

var backspace = chainCommands(deleteSelection, joinBackward, selectNodeBackward);
var del = chainCommands(deleteSelection, joinForward, selectNodeForward); // :: Object
// A basic keymap containing bindings not specific to any schema.
// Binds the following keys (when multiple commands are listed, they
// are chained with [`chainCommands`](#commands.chainCommands)):
//
// * **Enter** to `newlineInCode`, `createParagraphNear`, `liftEmptyBlock`, `splitBlock`
// * **Mod-Enter** to `exitCode`
// * **Backspace** and **Mod-Backspace** to `deleteSelection`, `joinBackward`, `selectNodeBackward`
// * **Delete** and **Mod-Delete** to `deleteSelection`, `joinForward`, `selectNodeForward`
// * **Mod-Delete** to `deleteSelection`, `joinForward`, `selectNodeForward`
// * **Mod-a** to `selectAll`

var pcBaseKeymap = {
  "Enter": chainCommands(newlineInCode, createParagraphNear, liftEmptyBlock, splitBlock),
  "Mod-Enter": exitCode,
  "Backspace": backspace,
  "Mod-Backspace": backspace,
  "Delete": del,
  "Mod-Delete": del,
  "Mod-a": selectAll
}; // :: Object
// A copy of `pcBaseKeymap` that also binds **Ctrl-h** like Backspace,
// **Ctrl-d** like Delete, **Alt-Backspace** like Ctrl-Backspace, and
// **Ctrl-Alt-Backspace**, **Alt-Delete**, and **Alt-d** like
// Ctrl-Delete.

exports.pcBaseKeymap = pcBaseKeymap;
var macBaseKeymap = {
  "Ctrl-h": pcBaseKeymap["Backspace"],
  "Alt-Backspace": pcBaseKeymap["Mod-Backspace"],
  "Ctrl-d": pcBaseKeymap["Delete"],
  "Ctrl-Alt-Backspace": pcBaseKeymap["Mod-Delete"],
  "Alt-Delete": pcBaseKeymap["Mod-Delete"],
  "Alt-d": pcBaseKeymap["Mod-Delete"]
};
exports.macBaseKeymap = macBaseKeymap;

for (var key in pcBaseKeymap) {
  macBaseKeymap[key] = pcBaseKeymap[key];
} // declare global: os, navigator


var mac = typeof navigator != "undefined" ? /Mac/.test(navigator.platform) : typeof os != "undefined" ? os.platform() == "darwin" : false; // :: Object
// Depending on the detected platform, this will hold
// [`pcBasekeymap`](#commands.pcBaseKeymap) or
// [`macBaseKeymap`](#commands.macBaseKeymap).

var baseKeymap = mac ? macBaseKeymap : pcBaseKeymap;
exports.baseKeymap = baseKeymap;
},{"prosemirror-transform":"../node_modules/prosemirror-transform/dist/index.es.js","prosemirror-model":"../node_modules/prosemirror-model/dist/index.es.js","prosemirror-state":"../node_modules/prosemirror-state/dist/index.es.js"}],"../node_modules/prosemirror-dropcursor/dist/index.es.js":[function(require,module,exports) {
"use strict";

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

var _prosemirrorState = require("prosemirror-state");

var _prosemirrorTransform = require("prosemirror-transform");

// :: (options: ?Object) → Plugin
// Create a plugin that, when added to a ProseMirror instance,
// causes a decoration to show up at the drop position when something
// is dragged over the editor.
//
//   options::- These options are supported:
//
//     color:: ?string
//     The color of the cursor. Defaults to `black`.
//
//     width:: ?number
//     The precise width of the cursor in pixels. Defaults to 1.
//
//     class:: ?string
//     A CSS class name to add to the cursor element.
function dropCursor(options) {
  if (options === void 0) options = {};
  return new _prosemirrorState.Plugin({
    view: function view(editorView) {
      return new DropCursorView(editorView, options);
    }
  });
}

var DropCursorView = function DropCursorView(editorView, options) {
  var this$1 = this;
  this.editorView = editorView;
  this.width = options.width || 1;
  this.color = options.color || "black";
  this.class = options.class;
  this.cursorPos = null;
  this.element = null;
  this.timeout = null;
  this.handlers = ["dragover", "dragend", "drop", "dragleave"].map(function (name) {
    var handler = function (e) {
      return this$1[name](e);
    };

    editorView.dom.addEventListener(name, handler);
    return {
      name: name,
      handler: handler
    };
  });
};

DropCursorView.prototype.destroy = function destroy() {
  var this$1 = this;
  this.handlers.forEach(function (ref) {
    var name = ref.name;
    var handler = ref.handler;
    return this$1.editorView.dom.removeEventListener(name, handler);
  });
};

DropCursorView.prototype.update = function update(editorView, prevState) {
  if (this.cursorPos != null && prevState.doc != editorView.state.doc) {
    this.updateOverlay();
  }
};

DropCursorView.prototype.setCursor = function setCursor(pos) {
  if (pos == this.cursorPos) {
    return;
  }

  this.cursorPos = pos;

  if (pos == null) {
    this.element.parentNode.removeChild(this.element);
    this.element = null;
  } else {
    this.updateOverlay();
  }
};

DropCursorView.prototype.updateOverlay = function updateOverlay() {
  var $pos = this.editorView.state.doc.resolve(this.cursorPos),
      rect;

  if (!$pos.parent.inlineContent) {
    var before = $pos.nodeBefore,
        after = $pos.nodeAfter;

    if (before || after) {
      var nodeRect = this.editorView.nodeDOM(this.cursorPos - (before ? before.nodeSize : 0)).getBoundingClientRect();
      var top = before ? nodeRect.bottom : nodeRect.top;

      if (before && after) {
        top = (top + this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top) / 2;
      }

      rect = {
        left: nodeRect.left,
        right: nodeRect.right,
        top: top - this.width / 2,
        bottom: top + this.width / 2
      };
    }
  }

  if (!rect) {
    var coords = this.editorView.coordsAtPos(this.cursorPos);
    rect = {
      left: coords.left - this.width / 2,
      right: coords.left + this.width / 2,
      top: coords.top,
      bottom: coords.bottom
    };
  }

  var parent = this.editorView.dom.offsetParent;

  if (!this.element) {
    this.element = parent.appendChild(document.createElement("div"));

    if (this.class) {
      this.element.className = this.class;
    }

    this.element.style.cssText = "position: absolute; z-index: 50; pointer-events: none; background-color: " + this.color;
  }

  var parentRect = !parent || parent == document.body && getComputedStyle(parent).position == "static" ? {
    left: -pageXOffset,
    top: -pageYOffset
  } : parent.getBoundingClientRect();
  this.element.style.left = rect.left - parentRect.left + "px";
  this.element.style.top = rect.top - parentRect.top + "px";
  this.element.style.width = rect.right - rect.left + "px";
  this.element.style.height = rect.bottom - rect.top + "px";
};

DropCursorView.prototype.scheduleRemoval = function scheduleRemoval(timeout) {
  var this$1 = this;
  clearTimeout(this.timeout);
  this.timeout = setTimeout(function () {
    return this$1.setCursor(null);
  }, timeout);
};

DropCursorView.prototype.dragover = function dragover(event) {
  if (!this.editorView.editable) {
    return;
  }

  var pos = this.editorView.posAtCoords({
    left: event.clientX,
    top: event.clientY
  });

  if (pos) {
    var target = pos.pos;

    if (this.editorView.dragging && this.editorView.dragging.slice) {
      target = (0, _prosemirrorTransform.dropPoint)(this.editorView.state.doc, target, this.editorView.dragging.slice);

      if (target == null) {
        target = pos.pos;
      }
    }

    this.setCursor(target);
    this.scheduleRemoval(5000);
  }
};

DropCursorView.prototype.dragend = function dragend() {
  this.scheduleRemoval(20);
};

DropCursorView.prototype.drop = function drop() {
  this.scheduleRemoval(20);
};

DropCursorView.prototype.dragleave = function dragleave(event) {
  if (event.target == this.editorView.dom || !this.editorView.dom.contains(event.relatedTarget)) {
    this.setCursor(null);
  }
};
},{"prosemirror-state":"../node_modules/prosemirror-state/dist/index.es.js","prosemirror-transform":"../node_modules/prosemirror-transform/dist/index.es.js"}],"../node_modules/prosemirror-gapcursor/dist/index.es.js":[function(require,module,exports) {
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.gapCursor = exports.GapCursor = void 0;

var _prosemirrorKeymap = require("prosemirror-keymap");

var _prosemirrorState = require("prosemirror-state");

var _prosemirrorView = require("prosemirror-view");

var _prosemirrorModel = require("prosemirror-model");

// ::- Gap cursor selections are represented using this class. Its
// `$anchor` and `$head` properties both point at the cursor position.
var GapCursor = /*@__PURE__*/function (Selection) {
  function GapCursor($pos) {
    Selection.call(this, $pos, $pos);
  }

  if (Selection) GapCursor.__proto__ = Selection;
  GapCursor.prototype = Object.create(Selection && Selection.prototype);
  GapCursor.prototype.constructor = GapCursor;

  GapCursor.prototype.map = function map(doc, mapping) {
    var $pos = doc.resolve(mapping.map(this.head));
    return GapCursor.valid($pos) ? new GapCursor($pos) : Selection.near($pos);
  };

  GapCursor.prototype.content = function content() {
    return _prosemirrorModel.Slice.empty;
  };

  GapCursor.prototype.eq = function eq(other) {
    return other instanceof GapCursor && other.head == this.head;
  };

  GapCursor.prototype.toJSON = function toJSON() {
    return {
      type: "gapcursor",
      pos: this.head
    };
  };

  GapCursor.fromJSON = function fromJSON(doc, json) {
    if (typeof json.pos != "number") {
      throw new RangeError("Invalid input for GapCursor.fromJSON");
    }

    return new GapCursor(doc.resolve(json.pos));
  };

  GapCursor.prototype.getBookmark = function getBookmark() {
    return new GapBookmark(this.anchor);
  };

  GapCursor.valid = function valid($pos) {
    var parent = $pos.parent;

    if (parent.isTextblock || !closedBefore($pos) || !closedAfter($pos)) {
      return false;
    }

    var override = parent.type.spec.allowGapCursor;

    if (override != null) {
      return override;
    }

    var deflt = parent.contentMatchAt($pos.index()).defaultType;
    return deflt && deflt.isTextblock;
  };

  GapCursor.findFrom = function findFrom($pos, dir, mustMove) {
    search: for (;;) {
      if (!mustMove && GapCursor.valid($pos)) {
        return $pos;
      }

      var pos = $pos.pos,
          next = null; // Scan up from this position

      for (var d = $pos.depth;; d--) {
        var parent = $pos.node(d);

        if (dir > 0 ? $pos.indexAfter(d) < parent.childCount : $pos.index(d) > 0) {
          next = parent.child(dir > 0 ? $pos.indexAfter(d) : $pos.index(d) - 1);
          break;
        } else if (d == 0) {
          return null;
        }

        pos += dir;
        var $cur = $pos.doc.resolve(pos);

        if (GapCursor.valid($cur)) {
          return $cur;
        }
      } // And then down into the next node


      for (;;) {
        var inside = dir > 0 ? next.firstChild : next.lastChild;

        if (!inside) {
          if (next.isAtom && !next.isText && !_prosemirrorState.NodeSelection.isSelectable(next)) {
            $pos = $pos.doc.resolve(pos + next.nodeSize * dir);
            mustMove = false;
            continue search;
          }

          break;
        }

        next = inside;
        pos += dir;
        var $cur$1 = $pos.doc.resolve(pos);

        if (GapCursor.valid($cur$1)) {
          return $cur$1;
        }
      }

      return null;
    }
  };

  return GapCursor;
}(_prosemirrorState.Selection);

exports.GapCursor = GapCursor;
GapCursor.prototype.visible = false;

_prosemirrorState.Selection.jsonID("gapcursor", GapCursor);

var GapBookmark = function GapBookmark(pos) {
  this.pos = pos;
};

GapBookmark.prototype.map = function map(mapping) {
  return new GapBookmark(mapping.map(this.pos));
};

GapBookmark.prototype.resolve = function resolve(doc) {
  var $pos = doc.resolve(this.pos);
  return GapCursor.valid($pos) ? new GapCursor($pos) : _prosemirrorState.Selection.near($pos);
};

function closedBefore($pos) {
  for (var d = $pos.depth; d >= 0; d--) {
    var index = $pos.index(d); // At the start of this parent, look at next one

    if (index == 0) {
      continue;
    } // See if the node before (or its first ancestor) is closed


    for (var before = $pos.node(d).child(index - 1);; before = before.lastChild) {
      if (before.childCount == 0 && !before.inlineContent || before.isAtom || before.type.spec.isolating) {
        return true;
      }

      if (before.inlineContent) {
        return false;
      }
    }
  } // Hit start of document


  return true;
}

function closedAfter($pos) {
  for (var d = $pos.depth; d >= 0; d--) {
    var index = $pos.indexAfter(d),
        parent = $pos.node(d);

    if (index == parent.childCount) {
      continue;
    }

    for (var after = parent.child(index);; after = after.firstChild) {
      if (after.childCount == 0 && !after.inlineContent || after.isAtom || after.type.spec.isolating) {
        return true;
      }

      if (after.inlineContent) {
        return false;
      }
    }
  }

  return true;
} // :: () → Plugin
// Create a gap cursor plugin. When enabled, this will capture clicks
// near and arrow-key-motion past places that don't have a normally
// selectable position nearby, and create a gap cursor selection for
// them. The cursor is drawn as an element with class
// `ProseMirror-gapcursor`. You can either include
// `style/gapcursor.css` from the package's directory or add your own
// styles to make it visible.


var gapCursor = function () {
  return new _prosemirrorState.Plugin({
    props: {
      decorations: drawGapCursor,
      createSelectionBetween: function createSelectionBetween(_view, $anchor, $head) {
        if ($anchor.pos == $head.pos && GapCursor.valid($head)) {
          return new GapCursor($head);
        }
      },
      handleClick: handleClick,
      handleKeyDown: handleKeyDown
    }
  });
};

exports.gapCursor = gapCursor;
var handleKeyDown = (0, _prosemirrorKeymap.keydownHandler)({
  "ArrowLeft": arrow("horiz", -1),
  "ArrowRight": arrow("horiz", 1),
  "ArrowUp": arrow("vert", -1),
  "ArrowDown": arrow("vert", 1)
});

function arrow(axis, dir) {
  var dirStr = axis == "vert" ? dir > 0 ? "down" : "up" : dir > 0 ? "right" : "left";
  return function (state, dispatch, view) {
    var sel = state.selection;
    var $start = dir > 0 ? sel.$to : sel.$from,
        mustMove = sel.empty;

    if (sel instanceof _prosemirrorState.TextSelection) {
      if (!view.endOfTextblock(dirStr) || $start.depth == 0) {
        return false;
      }

      mustMove = false;
      $start = state.doc.resolve(dir > 0 ? $start.after() : $start.before());
    }

    var $found = GapCursor.findFrom($start, dir, mustMove);

    if (!$found) {
      return false;
    }

    if (dispatch) {
      dispatch(state.tr.setSelection(new GapCursor($found)));
    }

    return true;
  };
}

function handleClick(view, pos, event) {
  if (!view.editable) {
    return false;
  }

  var $pos = view.state.doc.resolve(pos);

  if (!GapCursor.valid($pos)) {
    return false;
  }

  var ref = view.posAtCoords({
    left: event.clientX,
    top: event.clientY
  });
  var inside = ref.inside;

  if (inside > -1 && _prosemirrorState.NodeSelection.isSelectable(view.state.doc.nodeAt(inside))) {
    return false;
  }

  view.dispatch(view.state.tr.setSelection(new GapCursor($pos)));
  return true;
}

function drawGapCursor(state) {
  if (!(state.selection instanceof GapCursor)) {
    return null;
  }

  var node = document.createElement("div");
  node.className = "ProseMirror-gapcursor";
  return _prosemirrorView.DecorationSet.create(state.doc, [_prosemirrorView.Decoration.widget(state.selection.head, node, {
    key: "gapcursor"
  })]);
}
},{"prosemirror-keymap":"../node_modules/prosemirror-keymap/dist/index.es.js","prosemirror-state":"../node_modules/prosemirror-state/dist/index.es.js","prosemirror-view":"../node_modules/prosemirror-view/dist/index.es.js","prosemirror-model":"../node_modules/prosemirror-model/dist/index.es.js"}],"../node_modules/crelt/index.es.js":[function(require,module,exports) {
"use strict";

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

function crelt() {
  var elt = arguments[0];
  if (typeof elt == "string") elt = document.createElement(elt);
  var i = 1,
      next = arguments[1];

  if (next && typeof next == "object" && next.nodeType == null && !Array.isArray(next)) {
    for (var name in next) if (Object.prototype.hasOwnProperty.call(next, name)) {
      var value = next[name];
      if (typeof value == "string") elt.setAttribute(name, value);else if (value != null) elt[name] = value;
    }

    i++;
  }

  for (; i < arguments.length; i++) add(elt, arguments[i]);

  return elt;
}

function add(elt, child) {
  if (typeof child == "string") {
    elt.appendChild(document.createTextNode(child));
  } else if (child == null) {} else if (child.nodeType != null) {
    elt.appendChild(child);
  } else if (Array.isArray(child)) {
    for (var i = 0; i < child.length; i++) add(elt, child[i]);
  } else {
    throw new RangeError("Unsupported child node: " + child);
  }
}
},{}],"../node_modules/prosemirror-menu/dist/index.es.js":[function(require,module,exports) {
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.blockTypeItem = blockTypeItem;
exports.menuBar = menuBar;
exports.renderGrouped = renderGrouped;
exports.wrapItem = wrapItem;
exports.undoItem = exports.selectParentNodeItem = exports.redoItem = exports.liftItem = exports.joinUpItem = exports.icons = exports.MenuItem = exports.DropdownSubmenu = exports.Dropdown = void 0;

var _crelt = _interopRequireDefault(require("crelt"));

var _prosemirrorCommands = require("prosemirror-commands");

var _prosemirrorHistory = require("prosemirror-history");

var _prosemirrorState = require("prosemirror-state");

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

var SVG = "http://www.w3.org/2000/svg";
var XLINK = "http://www.w3.org/1999/xlink";
var prefix = "ProseMirror-icon";

function hashPath(path) {
  var hash = 0;

  for (var i = 0; i < path.length; i++) {
    hash = (hash << 5) - hash + path.charCodeAt(i) | 0;
  }

  return hash;
}

function getIcon(icon) {
  var node = document.createElement("div");
  node.className = prefix;

  if (icon.path) {
    var name = "pm-icon-" + hashPath(icon.path).toString(16);

    if (!document.getElementById(name)) {
      buildSVG(name, icon);
    }

    var svg = node.appendChild(document.createElementNS(SVG, "svg"));
    svg.style.width = icon.width / icon.height + "em";
    var use = svg.appendChild(document.createElementNS(SVG, "use"));
    use.setAttributeNS(XLINK, "href", /([^#]*)/.exec(document.location)[1] + "#" + name);
  } else if (icon.dom) {
    node.appendChild(icon.dom.cloneNode(true));
  } else {
    node.appendChild(document.createElement("span")).textContent = icon.text || '';

    if (icon.css) {
      node.firstChild.style.cssText = icon.css;
    }
  }

  return node;
}

function buildSVG(name, data) {
  var collection = document.getElementById(prefix + "-collection");

  if (!collection) {
    collection = document.createElementNS(SVG, "svg");
    collection.id = prefix + "-collection";
    collection.style.display = "none";
    document.body.insertBefore(collection, document.body.firstChild);
  }

  var sym = document.createElementNS(SVG, "symbol");
  sym.id = name;
  sym.setAttribute("viewBox", "0 0 " + data.width + " " + data.height);
  var path = sym.appendChild(document.createElementNS(SVG, "path"));
  path.setAttribute("d", data.path);
  collection.appendChild(sym);
}

var prefix$1 = "ProseMirror-menu"; // ::- An icon or label that, when clicked, executes a command.

var MenuItem = function MenuItem(spec) {
  // :: MenuItemSpec
  // The spec used to create the menu item.
  this.spec = spec;
}; // :: (EditorView) → {dom: dom.Node, update: (EditorState) → bool}
// Renders the icon according to its [display
// spec](#menu.MenuItemSpec.display), and adds an event handler which
// executes the command when the representation is clicked.


exports.MenuItem = MenuItem;

MenuItem.prototype.render = function render(view) {
  var spec = this.spec;
  var dom = spec.render ? spec.render(view) : spec.icon ? getIcon(spec.icon) : spec.label ? (0, _crelt.default)("div", null, translate(view, spec.label)) : null;

  if (!dom) {
    throw new RangeError("MenuItem without icon or label property");
  }

  if (spec.title) {
    var title = typeof spec.title === "function" ? spec.title(view.state) : spec.title;
    dom.setAttribute("title", translate(view, title));
  }

  if (spec.class) {
    dom.classList.add(spec.class);
  }

  if (spec.css) {
    dom.style.cssText += spec.css;
  }

  dom.addEventListener("mousedown", function (e) {
    e.preventDefault();

    if (!dom.classList.contains(prefix$1 + "-disabled")) {
      spec.run(view.state, view.dispatch, view, e);
    }
  });

  function update(state) {
    if (spec.select) {
      var selected = spec.select(state);
      dom.style.display = selected ? "" : "none";

      if (!selected) {
        return false;
      }
    }

    var enabled = true;

    if (spec.enable) {
      enabled = spec.enable(state) || false;
      setClass(dom, prefix$1 + "-disabled", !enabled);
    }

    if (spec.active) {
      var active = enabled && spec.active(state) || false;
      setClass(dom, prefix$1 + "-active", active);
    }

    return true;
  }

  return {
    dom: dom,
    update: update
  };
};

function translate(view, text) {
  return view._props.translate ? view._props.translate(text) : text;
} // MenuItemSpec:: interface
// The configuration object passed to the `MenuItem` constructor.
//
//   run:: (EditorState, (Transaction), EditorView, dom.Event)
//   The function to execute when the menu item is activated.
//
//   select:: ?(EditorState) → bool
//   Optional function that is used to determine whether the item is
//   appropriate at the moment. Deselected items will be hidden.
//
//   enable:: ?(EditorState) → bool
//   Function that is used to determine if the item is enabled. If
//   given and returning false, the item will be given a disabled
//   styling.
//
//   active:: ?(EditorState) → bool
//   A predicate function to determine whether the item is 'active' (for
//   example, the item for toggling the strong mark might be active then
//   the cursor is in strong text).
//
//   render:: ?(EditorView) → dom.Node
//   A function that renders the item. You must provide either this,
//   [`icon`](#menu.MenuItemSpec.icon), or [`label`](#MenuItemSpec.label).
//
//   icon:: ?Object
//   Describes an icon to show for this item. The object may specify
//   an SVG icon, in which case its `path` property should be an [SVG
//   path
//   spec](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/d),
//   and `width` and `height` should provide the viewbox in which that
//   path exists. Alternatively, it may have a `text` property
//   specifying a string of text that makes up the icon, with an
//   optional `css` property giving additional CSS styling for the
//   text. _Or_ it may contain `dom` property containing a DOM node.
//
//   label:: ?string
//   Makes the item show up as a text label. Mostly useful for items
//   wrapped in a [drop-down](#menu.Dropdown) or similar menu. The object
//   should have a `label` property providing the text to display.
//
//   title:: ?union<string, (EditorState) → string>
//   Defines DOM title (mouseover) text for the item.
//
//   class:: ?string
//   Optionally adds a CSS class to the item's DOM representation.
//
//   css:: ?string
//   Optionally adds a string of inline CSS to the item's DOM
//   representation.


var lastMenuEvent = {
  time: 0,
  node: null
};

function markMenuEvent(e) {
  lastMenuEvent.time = Date.now();
  lastMenuEvent.node = e.target;
}

function isMenuEvent(wrapper) {
  return Date.now() - 100 < lastMenuEvent.time && lastMenuEvent.node && wrapper.contains(lastMenuEvent.node);
} // ::- A drop-down menu, displayed as a label with a downwards-pointing
// triangle to the right of it.


var Dropdown = function Dropdown(content, options) {
  this.options = options || {};
  this.content = Array.isArray(content) ? content : [content];
}; // :: (EditorView) → {dom: dom.Node, update: (EditorState)}
// Render the dropdown menu and sub-items.


exports.Dropdown = Dropdown;

Dropdown.prototype.render = function render(view) {
  var this$1 = this;
  var content = renderDropdownItems(this.content, view);
  var label = (0, _crelt.default)("div", {
    class: prefix$1 + "-dropdown " + (this.options.class || ""),
    style: this.options.css
  }, translate(view, this.options.label));

  if (this.options.title) {
    label.setAttribute("title", translate(view, this.options.title));
  }

  var wrap = (0, _crelt.default)("div", {
    class: prefix$1 + "-dropdown-wrap"
  }, label);
  var open = null,
      listeningOnClose = null;

  var close = function () {
    if (open && open.close()) {
      open = null;
      window.removeEventListener("mousedown", listeningOnClose);
    }
  };

  label.addEventListener("mousedown", function (e) {
    e.preventDefault();
    markMenuEvent(e);

    if (open) {
      close();
    } else {
      open = this$1.expand(wrap, content.dom);
      window.addEventListener("mousedown", listeningOnClose = function () {
        if (!isMenuEvent(wrap)) {
          close();
        }
      });
    }
  });

  function update(state) {
    var inner = content.update(state);
    wrap.style.display = inner ? "" : "none";
    return inner;
  }

  return {
    dom: wrap,
    update: update
  };
};

Dropdown.prototype.expand = function expand(dom, items) {
  var menuDOM = (0, _crelt.default)("div", {
    class: prefix$1 + "-dropdown-menu " + (this.options.class || "")
  }, items);
  var done = false;

  function close() {
    if (done) {
      return;
    }

    done = true;
    dom.removeChild(menuDOM);
    return true;
  }

  dom.appendChild(menuDOM);
  return {
    close: close,
    node: menuDOM
  };
};

function renderDropdownItems(items, view) {
  var rendered = [],
      updates = [];

  for (var i = 0; i < items.length; i++) {
    var ref = items[i].render(view);
    var dom = ref.dom;
    var update = ref.update;
    rendered.push((0, _crelt.default)("div", {
      class: prefix$1 + "-dropdown-item"
    }, dom));
    updates.push(update);
  }

  return {
    dom: rendered,
    update: combineUpdates(updates, rendered)
  };
}

function combineUpdates(updates, nodes) {
  return function (state) {
    var something = false;

    for (var i = 0; i < updates.length; i++) {
      var up = updates[i](state);
      nodes[i].style.display = up ? "" : "none";

      if (up) {
        something = true;
      }
    }

    return something;
  };
} // ::- Represents a submenu wrapping a group of elements that start
// hidden and expand to the right when hovered over or tapped.


var DropdownSubmenu = function DropdownSubmenu(content, options) {
  this.options = options || {};
  this.content = Array.isArray(content) ? content : [content];
}; // :: (EditorView) → {dom: dom.Node, update: (EditorState) → bool}
// Renders the submenu.


exports.DropdownSubmenu = DropdownSubmenu;

DropdownSubmenu.prototype.render = function render(view) {
  var items = renderDropdownItems(this.content, view);
  var label = (0, _crelt.default)("div", {
    class: prefix$1 + "-submenu-label"
  }, translate(view, this.options.label));
  var wrap = (0, _crelt.default)("div", {
    class: prefix$1 + "-submenu-wrap"
  }, label, (0, _crelt.default)("div", {
    class: prefix$1 + "-submenu"
  }, items.dom));
  var listeningOnClose = null;
  label.addEventListener("mousedown", function (e) {
    e.preventDefault();
    markMenuEvent(e);
    setClass(wrap, prefix$1 + "-submenu-wrap-active");

    if (!listeningOnClose) {
      window.addEventListener("mousedown", listeningOnClose = function () {
        if (!isMenuEvent(wrap)) {
          wrap.classList.remove(prefix$1 + "-submenu-wrap-active");
          window.removeEventListener("mousedown", listeningOnClose);
          listeningOnClose = null;
        }
      });
    }
  });

  function update(state) {
    var inner = items.update(state);
    wrap.style.display = inner ? "" : "none";
    return inner;
  }

  return {
    dom: wrap,
    update: update
  };
}; // :: (EditorView, [union<MenuElement, [MenuElement]>]) → {dom: ?dom.DocumentFragment, update: (EditorState) → bool}
// Render the given, possibly nested, array of menu elements into a
// document fragment, placing separators between them (and ensuring no
// superfluous separators appear when some of the groups turn out to
// be empty).


function renderGrouped(view, content) {
  var result = document.createDocumentFragment();
  var updates = [],
      separators = [];

  for (var i = 0; i < content.length; i++) {
    var items = content[i],
        localUpdates = [],
        localNodes = [];

    for (var j = 0; j < items.length; j++) {
      var ref = items[j].render(view);
      var dom = ref.dom;
      var update$1 = ref.update;
      var span = (0, _crelt.default)("span", {
        class: prefix$1 + "item"
      }, dom);
      result.appendChild(span);
      localNodes.push(span);
      localUpdates.push(update$1);
    }

    if (localUpdates.length) {
      updates.push(combineUpdates(localUpdates, localNodes));

      if (i < content.length - 1) {
        separators.push(result.appendChild(separator()));
      }
    }
  }

  function update(state) {
    var something = false,
        needSep = false;

    for (var i = 0; i < updates.length; i++) {
      var hasContent = updates[i](state);

      if (i) {
        separators[i - 1].style.display = needSep && hasContent ? "" : "none";
      }

      needSep = hasContent;

      if (hasContent) {
        something = true;
      }
    }

    return something;
  }

  return {
    dom: result,
    update: update
  };
}

function separator() {
  return (0, _crelt.default)("span", {
    class: prefix$1 + "separator"
  });
} // :: Object
// A set of basic editor-related icons. Contains the properties
// `join`, `lift`, `selectParentNode`, `undo`, `redo`, `strong`, `em`,
// `code`, `link`, `bulletList`, `orderedList`, and `blockquote`, each
// holding an object that can be used as the `icon` option to
// `MenuItem`.


var icons = {
  join: {
    width: 800,
    height: 900,
    path: "M0 75h800v125h-800z M0 825h800v-125h-800z M250 400h100v-100h100v100h100v100h-100v100h-100v-100h-100z"
  },
  lift: {
    width: 1024,
    height: 1024,
    path: "M219 310v329q0 7-5 12t-12 5q-8 0-13-5l-164-164q-5-5-5-13t5-13l164-164q5-5 13-5 7 0 12 5t5 12zM1024 749v109q0 7-5 12t-12 5h-987q-7 0-12-5t-5-12v-109q0-7 5-12t12-5h987q7 0 12 5t5 12zM1024 530v109q0 7-5 12t-12 5h-621q-7 0-12-5t-5-12v-109q0-7 5-12t12-5h621q7 0 12 5t5 12zM1024 310v109q0 7-5 12t-12 5h-621q-7 0-12-5t-5-12v-109q0-7 5-12t12-5h621q7 0 12 5t5 12zM1024 91v109q0 7-5 12t-12 5h-987q-7 0-12-5t-5-12v-109q0-7 5-12t12-5h987q7 0 12 5t5 12z"
  },
  selectParentNode: {
    text: "\u2b1a",
    css: "font-weight: bold"
  },
  undo: {
    width: 1024,
    height: 1024,
    path: "M761 1024c113-206 132-520-313-509v253l-384-384 384-384v248c534-13 594 472 313 775z"
  },
  redo: {
    width: 1024,
    height: 1024,
    path: "M576 248v-248l384 384-384 384v-253c-446-10-427 303-313 509-280-303-221-789 313-775z"
  },
  strong: {
    width: 805,
    height: 1024,
    path: "M317 869q42 18 80 18 214 0 214-191 0-65-23-102-15-25-35-42t-38-26-46-14-48-6-54-1q-41 0-57 5 0 30-0 90t-0 90q0 4-0 38t-0 55 2 47 6 38zM309 442q24 4 62 4 46 0 81-7t62-25 42-51 14-81q0-40-16-70t-45-46-61-24-70-8q-28 0-74 7 0 28 2 86t2 86q0 15-0 45t-0 45q0 26 0 39zM0 950l1-53q8-2 48-9t60-15q4-6 7-15t4-19 3-18 1-21 0-19v-37q0-561-12-585-2-4-12-8t-25-6-28-4-27-2-17-1l-2-47q56-1 194-6t213-5q13 0 39 0t38 0q40 0 78 7t73 24 61 40 42 59 16 78q0 29-9 54t-22 41-36 32-41 25-48 22q88 20 146 76t58 141q0 57-20 102t-53 74-78 48-93 27-100 8q-25 0-75-1t-75-1q-60 0-175 6t-132 6z"
  },
  em: {
    width: 585,
    height: 1024,
    path: "M0 949l9-48q3-1 46-12t63-21q16-20 23-57 0-4 35-165t65-310 29-169v-14q-13-7-31-10t-39-4-33-3l10-58q18 1 68 3t85 4 68 1q27 0 56-1t69-4 56-3q-2 22-10 50-17 5-58 16t-62 19q-4 10-8 24t-5 22-4 26-3 24q-15 84-50 239t-44 203q-1 5-7 33t-11 51-9 47-3 32l0 10q9 2 105 17-1 25-9 56-6 0-18 0t-18 0q-16 0-49-5t-49-5q-78-1-117-1-29 0-81 5t-69 6z"
  },
  code: {
    width: 896,
    height: 1024,
    path: "M608 192l-96 96 224 224-224 224 96 96 288-320-288-320zM288 192l-288 320 288 320 96-96-224-224 224-224-96-96z"
  },
  link: {
    width: 951,
    height: 1024,
    path: "M832 694q0-22-16-38l-118-118q-16-16-38-16-24 0-41 18 1 1 10 10t12 12 8 10 7 14 2 15q0 22-16 38t-38 16q-8 0-15-2t-14-7-10-8-12-12-10-10q-18 17-18 41 0 22 16 38l117 118q15 15 38 15 22 0 38-14l84-83q16-16 16-38zM430 292q0-22-16-38l-117-118q-16-16-38-16-22 0-38 15l-84 83q-16 16-16 38 0 22 16 38l118 118q15 15 38 15 24 0 41-17-1-1-10-10t-12-12-8-10-7-14-2-15q0-22 16-38t38-16q8 0 15 2t14 7 10 8 12 12 10 10q18-17 18-41zM941 694q0 68-48 116l-84 83q-47 47-116 47-69 0-116-48l-117-118q-47-47-47-116 0-70 50-119l-50-50q-49 50-118 50-68 0-116-48l-118-118q-48-48-48-116t48-116l84-83q47-47 116-47 69 0 116 48l117 118q47 47 47 116 0 70-50 119l50 50q49-50 118-50 68 0 116 48l118 118q48 48 48 116z"
  },
  bulletList: {
    width: 768,
    height: 896,
    path: "M0 512h128v-128h-128v128zM0 256h128v-128h-128v128zM0 768h128v-128h-128v128zM256 512h512v-128h-512v128zM256 256h512v-128h-512v128zM256 768h512v-128h-512v128z"
  },
  orderedList: {
    width: 768,
    height: 896,
    path: "M320 512h448v-128h-448v128zM320 768h448v-128h-448v128zM320 128v128h448v-128h-448zM79 384h78v-256h-36l-85 23v50l43-2v185zM189 590c0-36-12-78-96-78-33 0-64 6-83 16l1 66c21-10 42-15 67-15s32 11 32 28c0 26-30 58-110 112v50h192v-67l-91 2c49-30 87-66 87-113l1-1z"
  },
  blockquote: {
    width: 640,
    height: 896,
    path: "M0 448v256h256v-256h-128c0 0 0-128 128-128v-128c0 0-256 0-256 256zM640 320v-128c0 0-256 0-256 256v256h256v-256h-128c0 0 0-128 128-128z"
  }
}; // :: MenuItem
// Menu item for the `joinUp` command.

exports.icons = icons;
var joinUpItem = new MenuItem({
  title: "Join with above block",
  run: _prosemirrorCommands.joinUp,
  select: function (state) {
    return (0, _prosemirrorCommands.joinUp)(state);
  },
  icon: icons.join
}); // :: MenuItem
// Menu item for the `lift` command.

exports.joinUpItem = joinUpItem;
var liftItem = new MenuItem({
  title: "Lift out of enclosing block",
  run: _prosemirrorCommands.lift,
  select: function (state) {
    return (0, _prosemirrorCommands.lift)(state);
  },
  icon: icons.lift
}); // :: MenuItem
// Menu item for the `selectParentNode` command.

exports.liftItem = liftItem;
var selectParentNodeItem = new MenuItem({
  title: "Select parent node",
  run: _prosemirrorCommands.selectParentNode,
  select: function (state) {
    return (0, _prosemirrorCommands.selectParentNode)(state);
  },
  icon: icons.selectParentNode
}); // :: MenuItem
// Menu item for the `undo` command.

exports.selectParentNodeItem = selectParentNodeItem;
var undoItem = new MenuItem({
  title: "Undo last change",
  run: _prosemirrorHistory.undo,
  enable: function (state) {
    return (0, _prosemirrorHistory.undo)(state);
  },
  icon: icons.undo
}); // :: MenuItem
// Menu item for the `redo` command.

exports.undoItem = undoItem;
var redoItem = new MenuItem({
  title: "Redo last undone change",
  run: _prosemirrorHistory.redo,
  enable: function (state) {
    return (0, _prosemirrorHistory.redo)(state);
  },
  icon: icons.redo
}); // :: (NodeType, Object) → MenuItem
// Build a menu item for wrapping the selection in a given node type.
// Adds `run` and `select` properties to the ones present in
// `options`. `options.attrs` may be an object or a function.

exports.redoItem = redoItem;

function wrapItem(nodeType, options) {
  var passedOptions = {
    run: function run(state, dispatch) {
      // FIXME if (options.attrs instanceof Function) options.attrs(state, attrs => wrapIn(nodeType, attrs)(state))
      return (0, _prosemirrorCommands.wrapIn)(nodeType, options.attrs)(state, dispatch);
    },
    select: function select(state) {
      return (0, _prosemirrorCommands.wrapIn)(nodeType, options.attrs instanceof Function ? null : options.attrs)(state);
    }
  };

  for (var prop in options) {
    passedOptions[prop] = options[prop];
  }

  return new MenuItem(passedOptions);
} // :: (NodeType, Object) → MenuItem
// Build a menu item for changing the type of the textblock around the
// selection to the given type. Provides `run`, `active`, and `select`
// properties. Others must be given in `options`. `options.attrs` may
// be an object to provide the attributes for the textblock node.


function blockTypeItem(nodeType, options) {
  var command = (0, _prosemirrorCommands.setBlockType)(nodeType, options.attrs);
  var passedOptions = {
    run: command,
    enable: function enable(state) {
      return command(state);
    },
    active: function active(state) {
      var ref = state.selection;
      var $from = ref.$from;
      var to = ref.to;
      var node = ref.node;

      if (node) {
        return node.hasMarkup(nodeType, options.attrs);
      }

      return to <= $from.end() && $from.parent.hasMarkup(nodeType, options.attrs);
    }
  };

  for (var prop in options) {
    passedOptions[prop] = options[prop];
  }

  return new MenuItem(passedOptions);
} // Work around classList.toggle being broken in IE11


function setClass(dom, cls, on) {
  if (on) {
    dom.classList.add(cls);
  } else {
    dom.classList.remove(cls);
  }
}

var prefix$2 = "ProseMirror-menubar";

function isIOS() {
  if (typeof navigator == "undefined") {
    return false;
  }

  var agent = navigator.userAgent;
  return !/Edge\/\d/.test(agent) && /AppleWebKit/.test(agent) && /Mobile\/\w+/.test(agent);
} // :: (Object) → Plugin
// A plugin that will place a menu bar above the editor. Note that
// this involves wrapping the editor in an additional `<div>`.
//
//   options::-
//   Supports the following options:
//
//     content:: [[MenuElement]]
//     Provides the content of the menu, as a nested array to be
//     passed to `renderGrouped`.
//
//     floating:: ?bool
//     Determines whether the menu floats, i.e. whether it sticks to
//     the top of the viewport when the editor is partially scrolled
//     out of view.


function menuBar(options) {
  return new _prosemirrorState.Plugin({
    view: function view(editorView) {
      return new MenuBarView(editorView, options);
    }
  });
}

var MenuBarView = function MenuBarView(editorView, options) {
  var this$1 = this;
  this.editorView = editorView;
  this.options = options;
  this.wrapper = (0, _crelt.default)("div", {
    class: prefix$2 + "-wrapper"
  });
  this.menu = this.wrapper.appendChild((0, _crelt.default)("div", {
    class: prefix$2
  }));
  this.menu.className = prefix$2;
  this.spacer = null;
  editorView.dom.parentNode.replaceChild(this.wrapper, editorView.dom);
  this.wrapper.appendChild(editorView.dom);
  this.maxHeight = 0;
  this.widthForMaxHeight = 0;
  this.floating = false;
  var ref = renderGrouped(this.editorView, this.options.content);
  var dom = ref.dom;
  var update = ref.update;
  this.contentUpdate = update;
  this.menu.appendChild(dom);
  this.update();

  if (options.floating && !isIOS()) {
    this.updateFloat();
    var potentialScrollers = getAllWrapping(this.wrapper);

    this.scrollFunc = function (e) {
      var root = this$1.editorView.root;

      if (!(root.body || root).contains(this$1.wrapper)) {
        potentialScrollers.forEach(function (el) {
          return el.removeEventListener("scroll", this$1.scrollFunc);
        });
      } else {
        this$1.updateFloat(e.target.getBoundingClientRect && e.target);
      }
    };

    potentialScrollers.forEach(function (el) {
      return el.addEventListener('scroll', this$1.scrollFunc);
    });
  }
};

MenuBarView.prototype.update = function update() {
  this.contentUpdate(this.editorView.state);

  if (this.floating) {
    this.updateScrollCursor();
  } else {
    if (this.menu.offsetWidth != this.widthForMaxHeight) {
      this.widthForMaxHeight = this.menu.offsetWidth;
      this.maxHeight = 0;
    }

    if (this.menu.offsetHeight > this.maxHeight) {
      this.maxHeight = this.menu.offsetHeight;
      this.menu.style.minHeight = this.maxHeight + "px";
    }
  }
};

MenuBarView.prototype.updateScrollCursor = function updateScrollCursor() {
  var selection = this.editorView.root.getSelection();

  if (!selection.focusNode) {
    return;
  }

  var rects = selection.getRangeAt(0).getClientRects();
  var selRect = rects[selectionIsInverted(selection) ? 0 : rects.length - 1];

  if (!selRect) {
    return;
  }

  var menuRect = this.menu.getBoundingClientRect();

  if (selRect.top < menuRect.bottom && selRect.bottom > menuRect.top) {
    var scrollable = findWrappingScrollable(this.wrapper);

    if (scrollable) {
      scrollable.scrollTop -= menuRect.bottom - selRect.top;
    }
  }
};

MenuBarView.prototype.updateFloat = function updateFloat(scrollAncestor) {
  var parent = this.wrapper,
      editorRect = parent.getBoundingClientRect(),
      top = scrollAncestor ? Math.max(0, scrollAncestor.getBoundingClientRect().top) : 0;

  if (this.floating) {
    if (editorRect.top >= top || editorRect.bottom < this.menu.offsetHeight + 10) {
      this.floating = false;
      this.menu.style.position = this.menu.style.left = this.menu.style.top = this.menu.style.width = "";
      this.menu.style.display = "";
      this.spacer.parentNode.removeChild(this.spacer);
      this.spacer = null;
    } else {
      var border = (parent.offsetWidth - parent.clientWidth) / 2;
      this.menu.style.left = editorRect.left + border + "px";
      this.menu.style.display = editorRect.top > window.innerHeight ? "none" : "";

      if (scrollAncestor) {
        this.menu.style.top = top + "px";
      }
    }
  } else {
    if (editorRect.top < top && editorRect.bottom >= this.menu.offsetHeight + 10) {
      this.floating = true;
      var menuRect = this.menu.getBoundingClientRect();
      this.menu.style.left = menuRect.left + "px";
      this.menu.style.width = menuRect.width + "px";

      if (scrollAncestor) {
        this.menu.style.top = top + "px";
      }

      this.menu.style.position = "fixed";
      this.spacer = (0, _crelt.default)("div", {
        class: prefix$2 + "-spacer",
        style: "height: " + menuRect.height + "px"
      });
      parent.insertBefore(this.spacer, this.menu);
    }
  }
};

MenuBarView.prototype.destroy = function destroy() {
  if (this.wrapper.parentNode) {
    this.wrapper.parentNode.replaceChild(this.editorView.dom, this.wrapper);
  }
}; // Not precise, but close enough


function selectionIsInverted(selection) {
  if (selection.anchorNode == selection.focusNode) {
    return selection.anchorOffset > selection.focusOffset;
  }

  return selection.anchorNode.compareDocumentPosition(selection.focusNode) == Node.DOCUMENT_POSITION_FOLLOWING;
}

function findWrappingScrollable(node) {
  for (var cur = node.parentNode; cur; cur = cur.parentNode) {
    if (cur.scrollHeight > cur.clientHeight) {
      return cur;
    }
  }
}

function getAllWrapping(node) {
  var res = [window];

  for (var cur = node.parentNode; cur; cur = cur.parentNode) {
    res.push(cur);
  }

  return res;
}
},{"crelt":"../node_modules/crelt/index.es.js","prosemirror-commands":"../node_modules/prosemirror-commands/dist/index.es.js","prosemirror-history":"../node_modules/prosemirror-history/dist/index.es.js","prosemirror-state":"../node_modules/prosemirror-state/dist/index.es.js"}],"../node_modules/prosemirror-schema-list/dist/index.es.js":[function(require,module,exports) {
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.addListNodes = addListNodes;
exports.liftListItem = liftListItem;
exports.sinkListItem = sinkListItem;
exports.splitListItem = splitListItem;
exports.wrapInList = wrapInList;
exports.orderedList = exports.listItem = exports.bulletList = void 0;

var _prosemirrorTransform = require("prosemirror-transform");

var _prosemirrorModel = require("prosemirror-model");

var olDOM = ["ol", 0],
    ulDOM = ["ul", 0],
    liDOM = ["li", 0]; // :: NodeSpec
// An ordered list [node spec](#model.NodeSpec). Has a single
// attribute, `order`, which determines the number at which the list
// starts counting, and defaults to 1. Represented as an `<ol>`
// element.

var orderedList = {
  attrs: {
    order: {
      default: 1
    }
  },
  parseDOM: [{
    tag: "ol",
    getAttrs: function getAttrs(dom) {
      return {
        order: dom.hasAttribute("start") ? +dom.getAttribute("start") : 1
      };
    }
  }],
  toDOM: function toDOM(node) {
    return node.attrs.order == 1 ? olDOM : ["ol", {
      start: node.attrs.order
    }, 0];
  }
}; // :: NodeSpec
// A bullet list node spec, represented in the DOM as `<ul>`.

exports.orderedList = orderedList;
var bulletList = {
  parseDOM: [{
    tag: "ul"
  }],
  toDOM: function toDOM() {
    return ulDOM;
  }
}; // :: NodeSpec
// A list item (`<li>`) spec.

exports.bulletList = bulletList;
var listItem = {
  parseDOM: [{
    tag: "li"
  }],
  toDOM: function toDOM() {
    return liDOM;
  },
  defining: true
};
exports.listItem = listItem;

function add(obj, props) {
  var copy = {};

  for (var prop in obj) {
    copy[prop] = obj[prop];
  }

  for (var prop$1 in props) {
    copy[prop$1] = props[prop$1];
  }

  return copy;
} // :: (OrderedMap<NodeSpec>, string, ?string) → OrderedMap<NodeSpec>
// Convenience function for adding list-related node types to a map
// specifying the nodes for a schema. Adds
// [`orderedList`](#schema-list.orderedList) as `"ordered_list"`,
// [`bulletList`](#schema-list.bulletList) as `"bullet_list"`, and
// [`listItem`](#schema-list.listItem) as `"list_item"`.
//
// `itemContent` determines the content expression for the list items.
// If you want the commands defined in this module to apply to your
// list structure, it should have a shape like `"paragraph block*"` or
// `"paragraph (ordered_list | bullet_list)*"`. `listGroup` can be
// given to assign a group name to the list node types, for example
// `"block"`.


function addListNodes(nodes, itemContent, listGroup) {
  return nodes.append({
    ordered_list: add(orderedList, {
      content: "list_item+",
      group: listGroup
    }),
    bullet_list: add(bulletList, {
      content: "list_item+",
      group: listGroup
    }),
    list_item: add(listItem, {
      content: itemContent
    })
  });
} // :: (NodeType, ?Object) → (state: EditorState, dispatch: ?(tr: Transaction)) → bool
// Returns a command function that wraps the selection in a list with
// the given type an attributes. If `dispatch` is null, only return a
// value to indicate whether this is possible, but don't actually
// perform the change.


function wrapInList(listType, attrs) {
  return function (state, dispatch) {
    var ref = state.selection;
    var $from = ref.$from;
    var $to = ref.$to;
    var range = $from.blockRange($to),
        doJoin = false,
        outerRange = range;

    if (!range) {
      return false;
    } // This is at the top of an existing list item


    if (range.depth >= 2 && $from.node(range.depth - 1).type.compatibleContent(listType) && range.startIndex == 0) {
      // Don't do anything if this is the top of the list
      if ($from.index(range.depth - 1) == 0) {
        return false;
      }

      var $insert = state.doc.resolve(range.start - 2);
      outerRange = new _prosemirrorModel.NodeRange($insert, $insert, range.depth);

      if (range.endIndex < range.parent.childCount) {
        range = new _prosemirrorModel.NodeRange($from, state.doc.resolve($to.end(range.depth)), range.depth);
      }

      doJoin = true;
    }

    var wrap = (0, _prosemirrorTransform.findWrapping)(outerRange, listType, attrs, range);

    if (!wrap) {
      return false;
    }

    if (dispatch) {
      dispatch(doWrapInList(state.tr, range, wrap, doJoin, listType).scrollIntoView());
    }

    return true;
  };
}

function doWrapInList(tr, range, wrappers, joinBefore, listType) {
  var content = _prosemirrorModel.Fragment.empty;

  for (var i = wrappers.length - 1; i >= 0; i--) {
    content = _prosemirrorModel.Fragment.from(wrappers[i].type.create(wrappers[i].attrs, content));
  }

  tr.step(new _prosemirrorTransform.ReplaceAroundStep(range.start - (joinBefore ? 2 : 0), range.end, range.start, range.end, new _prosemirrorModel.Slice(content, 0, 0), wrappers.length, true));
  var found = 0;

  for (var i$1 = 0; i$1 < wrappers.length; i$1++) {
    if (wrappers[i$1].type == listType) {
      found = i$1 + 1;
    }
  }

  var splitDepth = wrappers.length - found;
  var splitPos = range.start + wrappers.length - (joinBefore ? 2 : 0),
      parent = range.parent;

  for (var i$2 = range.startIndex, e = range.endIndex, first = true; i$2 < e; i$2++, first = false) {
    if (!first && (0, _prosemirrorTransform.canSplit)(tr.doc, splitPos, splitDepth)) {
      tr.split(splitPos, splitDepth);
      splitPos += 2 * splitDepth;
    }

    splitPos += parent.child(i$2).nodeSize;
  }

  return tr;
} // :: (NodeType) → (state: EditorState, dispatch: ?(tr: Transaction)) → bool
// Build a command that splits a non-empty textblock at the top level
// of a list item by also splitting that list item.


function splitListItem(itemType) {
  return function (state, dispatch) {
    var ref = state.selection;
    var $from = ref.$from;
    var $to = ref.$to;
    var node = ref.node;

    if (node && node.isBlock || $from.depth < 2 || !$from.sameParent($to)) {
      return false;
    }

    var grandParent = $from.node(-1);

    if (grandParent.type != itemType) {
      return false;
    }

    if ($from.parent.content.size == 0) {
      // In an empty block. If this is a nested list, the wrapping
      // list item should be split. Otherwise, bail out and let next
      // command handle lifting.
      if ($from.depth == 2 || $from.node(-3).type != itemType || $from.index(-2) != $from.node(-2).childCount - 1) {
        return false;
      }

      if (dispatch) {
        var wrap = _prosemirrorModel.Fragment.empty,
            keepItem = $from.index(-1) > 0; // Build a fragment containing empty versions of the structure
        // from the outer list item to the parent node of the cursor

        for (var d = $from.depth - (keepItem ? 1 : 2); d >= $from.depth - 3; d--) {
          wrap = _prosemirrorModel.Fragment.from($from.node(d).copy(wrap));
        } // Add a second list item with an empty default start node


        wrap = wrap.append(_prosemirrorModel.Fragment.from(itemType.createAndFill()));
        var tr$1 = state.tr.replace($from.before(keepItem ? null : -1), $from.after(-3), new _prosemirrorModel.Slice(wrap, keepItem ? 3 : 2, 2));
        tr$1.setSelection(state.selection.constructor.near(tr$1.doc.resolve($from.pos + (keepItem ? 3 : 2))));
        dispatch(tr$1.scrollIntoView());
      }

      return true;
    }

    var nextType = $to.pos == $from.end() ? grandParent.contentMatchAt(0).defaultType : null;
    var tr = state.tr.delete($from.pos, $to.pos);
    var types = nextType && [null, {
      type: nextType
    }];

    if (!(0, _prosemirrorTransform.canSplit)(tr.doc, $from.pos, 2, types)) {
      return false;
    }

    if (dispatch) {
      dispatch(tr.split($from.pos, 2, types).scrollIntoView());
    }

    return true;
  };
} // :: (NodeType) → (state: EditorState, dispatch: ?(tr: Transaction)) → bool
// Create a command to lift the list item around the selection up into
// a wrapping list.


function liftListItem(itemType) {
  return function (state, dispatch) {
    var ref = state.selection;
    var $from = ref.$from;
    var $to = ref.$to;
    var range = $from.blockRange($to, function (node) {
      return node.childCount && node.firstChild.type == itemType;
    });

    if (!range) {
      return false;
    }

    if (!dispatch) {
      return true;
    }

    if ($from.node(range.depth - 1).type == itemType) // Inside a parent list
      {
        return liftToOuterList(state, dispatch, itemType, range);
      } else // Outer list node
      {
        return liftOutOfList(state, dispatch, range);
      }
  };
}

function liftToOuterList(state, dispatch, itemType, range) {
  var tr = state.tr,
      end = range.end,
      endOfList = range.$to.end(range.depth);

  if (end < endOfList) {
    // There are siblings after the lifted items, which must become
    // children of the last item
    tr.step(new _prosemirrorTransform.ReplaceAroundStep(end - 1, endOfList, end, endOfList, new _prosemirrorModel.Slice(_prosemirrorModel.Fragment.from(itemType.create(null, range.parent.copy())), 1, 0), 1, true));
    range = new _prosemirrorModel.NodeRange(tr.doc.resolve(range.$from.pos), tr.doc.resolve(endOfList), range.depth);
  }

  dispatch(tr.lift(range, (0, _prosemirrorTransform.liftTarget)(range)).scrollIntoView());
  return true;
}

function liftOutOfList(state, dispatch, range) {
  var tr = state.tr,
      list = range.parent; // Merge the list items into a single big item

  for (var pos = range.end, i = range.endIndex - 1, e = range.startIndex; i > e; i--) {
    pos -= list.child(i).nodeSize;
    tr.delete(pos - 1, pos + 1);
  }

  var $start = tr.doc.resolve(range.start),
      item = $start.nodeAfter;
  var atStart = range.startIndex == 0,
      atEnd = range.endIndex == list.childCount;
  var parent = $start.node(-1),
      indexBefore = $start.index(-1);

  if (!parent.canReplace(indexBefore + (atStart ? 0 : 1), indexBefore + 1, item.content.append(atEnd ? _prosemirrorModel.Fragment.empty : _prosemirrorModel.Fragment.from(list)))) {
    return false;
  }

  var start = $start.pos,
      end = start + item.nodeSize; // Strip off the surrounding list. At the sides where we're not at
  // the end of the list, the existing list is closed. At sides where
  // this is the end, it is overwritten to its end.

  tr.step(new _prosemirrorTransform.ReplaceAroundStep(start - (atStart ? 1 : 0), end + (atEnd ? 1 : 0), start + 1, end - 1, new _prosemirrorModel.Slice((atStart ? _prosemirrorModel.Fragment.empty : _prosemirrorModel.Fragment.from(list.copy(_prosemirrorModel.Fragment.empty))).append(atEnd ? _prosemirrorModel.Fragment.empty : _prosemirrorModel.Fragment.from(list.copy(_prosemirrorModel.Fragment.empty))), atStart ? 0 : 1, atEnd ? 0 : 1), atStart ? 0 : 1));
  dispatch(tr.scrollIntoView());
  return true;
} // :: (NodeType) → (state: EditorState, dispatch: ?(tr: Transaction)) → bool
// Create a command to sink the list item around the selection down
// into an inner list.


function sinkListItem(itemType) {
  return function (state, dispatch) {
    var ref = state.selection;
    var $from = ref.$from;
    var $to = ref.$to;
    var range = $from.blockRange($to, function (node) {
      return node.childCount && node.firstChild.type == itemType;
    });

    if (!range) {
      return false;
    }

    var startIndex = range.startIndex;

    if (startIndex == 0) {
      return false;
    }

    var parent = range.parent,
        nodeBefore = parent.child(startIndex - 1);

    if (nodeBefore.type != itemType) {
      return false;
    }

    if (dispatch) {
      var nestedBefore = nodeBefore.lastChild && nodeBefore.lastChild.type == parent.type;

      var inner = _prosemirrorModel.Fragment.from(nestedBefore ? itemType.create() : null);

      var slice = new _prosemirrorModel.Slice(_prosemirrorModel.Fragment.from(itemType.create(null, _prosemirrorModel.Fragment.from(parent.type.create(null, inner)))), nestedBefore ? 3 : 1, 0);
      var before = range.start,
          after = range.end;
      dispatch(state.tr.step(new _prosemirrorTransform.ReplaceAroundStep(before - (nestedBefore ? 3 : 1), after, before, after, slice, 1, true)).scrollIntoView());
    }

    return true;
  };
}
},{"prosemirror-transform":"../node_modules/prosemirror-transform/dist/index.es.js","prosemirror-model":"../node_modules/prosemirror-model/dist/index.es.js"}],"../node_modules/prosemirror-inputrules/dist/index.es.js":[function(require,module,exports) {
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.inputRules = inputRules;
exports.textblockTypeInputRule = textblockTypeInputRule;
exports.undoInputRule = undoInputRule;
exports.wrappingInputRule = wrappingInputRule;
exports.smartQuotes = exports.openSingleQuote = exports.openDoubleQuote = exports.emDash = exports.ellipsis = exports.closeSingleQuote = exports.closeDoubleQuote = exports.InputRule = void 0;

var _prosemirrorState = require("prosemirror-state");

var _prosemirrorTransform = require("prosemirror-transform");

// ::- Input rules are regular expressions describing a piece of text
// that, when typed, causes something to happen. This might be
// changing two dashes into an emdash, wrapping a paragraph starting
// with `"> "` into a blockquote, or something entirely different.
var InputRule = function InputRule(match, handler) {
  this.match = match;
  this.handler = typeof handler == "string" ? stringHandler(handler) : handler;
};

exports.InputRule = InputRule;

function stringHandler(string) {
  return function (state, match, start, end) {
    var insert = string;

    if (match[1]) {
      var offset = match[0].lastIndexOf(match[1]);
      insert += match[0].slice(offset + match[1].length);
      start += offset;
      var cutOff = start - end;

      if (cutOff > 0) {
        insert = match[0].slice(offset - cutOff, offset) + insert;
        start = end;
      }
    }

    return state.tr.insertText(insert, start, end);
  };
}

var MAX_MATCH = 500; // :: (config: {rules: [InputRule]}) → Plugin
// Create an input rules plugin. When enabled, it will cause text
// input that matches any of the given rules to trigger the rule's
// action.

function inputRules(ref) {
  var rules = ref.rules;
  var plugin = new _prosemirrorState.Plugin({
    state: {
      init: function init() {
        return null;
      },
      apply: function apply(tr, prev) {
        var stored = tr.getMeta(this);

        if (stored) {
          return stored;
        }

        return tr.selectionSet || tr.docChanged ? null : prev;
      }
    },
    props: {
      handleTextInput: function handleTextInput(view, from, to, text) {
        return run(view, from, to, text, rules, plugin);
      },
      handleDOMEvents: {
        compositionend: function (view) {
          setTimeout(function () {
            var ref = view.state.selection;
            var $cursor = ref.$cursor;

            if ($cursor) {
              run(view, $cursor.pos, $cursor.pos, "", rules, plugin);
            }
          });
        }
      }
    },
    isInputRules: true
  });
  return plugin;
}

function run(view, from, to, text, rules, plugin) {
  if (view.composing) {
    return false;
  }

  var state = view.state,
      $from = state.doc.resolve(from);

  if ($from.parent.type.spec.code) {
    return false;
  }

  var textBefore = $from.parent.textBetween(Math.max(0, $from.parentOffset - MAX_MATCH), $from.parentOffset, null, "\ufffc") + text;

  for (var i = 0; i < rules.length; i++) {
    var match = rules[i].match.exec(textBefore);
    var tr = match && rules[i].handler(state, match, from - (match[0].length - text.length), to);

    if (!tr) {
      continue;
    }

    view.dispatch(tr.setMeta(plugin, {
      transform: tr,
      from: from,
      to: to,
      text: text
    }));
    return true;
  }

  return false;
} // :: (EditorState, ?(Transaction)) → bool
// This is a command that will undo an input rule, if applying such a
// rule was the last thing that the user did.


function undoInputRule(state, dispatch) {
  var plugins = state.plugins;

  for (var i = 0; i < plugins.length; i++) {
    var plugin = plugins[i],
        undoable = void 0;

    if (plugin.spec.isInputRules && (undoable = plugin.getState(state))) {
      if (dispatch) {
        var tr = state.tr,
            toUndo = undoable.transform;

        for (var j = toUndo.steps.length - 1; j >= 0; j--) {
          tr.step(toUndo.steps[j].invert(toUndo.docs[j]));
        }

        var marks = tr.doc.resolve(undoable.from).marks();
        dispatch(tr.replaceWith(undoable.from, undoable.to, state.schema.text(undoable.text, marks)));
      }

      return true;
    }
  }

  return false;
} // :: InputRule Converts double dashes to an emdash.


var emDash = new InputRule(/--$/, "—"); // :: InputRule Converts three dots to an ellipsis character.

exports.emDash = emDash;
var ellipsis = new InputRule(/\.\.\.$/, "…"); // :: InputRule “Smart” opening double quotes.

exports.ellipsis = ellipsis;
var openDoubleQuote = new InputRule(/(?:^|[\s\{\[\(\<'"\u2018\u201C])(")$/, "“"); // :: InputRule “Smart” closing double quotes.

exports.openDoubleQuote = openDoubleQuote;
var closeDoubleQuote = new InputRule(/"$/, "”"); // :: InputRule “Smart” opening single quotes.

exports.closeDoubleQuote = closeDoubleQuote;
var openSingleQuote = new InputRule(/(?:^|[\s\{\[\(\<'"\u2018\u201C])(')$/, "‘"); // :: InputRule “Smart” closing single quotes.

exports.openSingleQuote = openSingleQuote;
var closeSingleQuote = new InputRule(/'$/, "’"); // :: [InputRule] Smart-quote related input rules.

exports.closeSingleQuote = closeSingleQuote;
var smartQuotes = [openDoubleQuote, closeDoubleQuote, openSingleQuote, closeSingleQuote]; // :: (RegExp, NodeType, ?union<Object, ([string]) → ?Object>, ?([string], Node) → bool) → InputRule
// Build an input rule for automatically wrapping a textblock when a
// given string is typed. The `regexp` argument is
// directly passed through to the `InputRule` constructor. You'll
// probably want the regexp to start with `^`, so that the pattern can
// only occur at the start of a textblock.
//
// `nodeType` is the type of node to wrap in. If it needs attributes,
// you can either pass them directly, or pass a function that will
// compute them from the regular expression match.
//
// By default, if there's a node with the same type above the newly
// wrapped node, the rule will try to [join](#transform.Transform.join) those
// two nodes. You can pass a join predicate, which takes a regular
// expression match and the node before the wrapped node, and can
// return a boolean to indicate whether a join should happen.

exports.smartQuotes = smartQuotes;

function wrappingInputRule(regexp, nodeType, getAttrs, joinPredicate) {
  return new InputRule(regexp, function (state, match, start, end) {
    var attrs = getAttrs instanceof Function ? getAttrs(match) : getAttrs;
    var tr = state.tr.delete(start, end);
    var $start = tr.doc.resolve(start),
        range = $start.blockRange(),
        wrapping = range && (0, _prosemirrorTransform.findWrapping)(range, nodeType, attrs);

    if (!wrapping) {
      return null;
    }

    tr.wrap(range, wrapping);
    var before = tr.doc.resolve(start - 1).nodeBefore;

    if (before && before.type == nodeType && (0, _prosemirrorTransform.canJoin)(tr.doc, start - 1) && (!joinPredicate || joinPredicate(match, before))) {
      tr.join(start - 1);
    }

    return tr;
  });
} // :: (RegExp, NodeType, ?union<Object, ([string]) → ?Object>) → InputRule
// Build an input rule that changes the type of a textblock when the
// matched text is typed into it. You'll usually want to start your
// regexp with `^` to that it is only matched at the start of a
// textblock. The optional `getAttrs` parameter can be used to compute
// the new node's attributes, and works the same as in the
// `wrappingInputRule` function.


function textblockTypeInputRule(regexp, nodeType, getAttrs) {
  return new InputRule(regexp, function (state, match, start, end) {
    var $start = state.doc.resolve(start);
    var attrs = getAttrs instanceof Function ? getAttrs(match) : getAttrs;

    if (!$start.node(-1).canReplaceWith($start.index(-1), $start.indexAfter(-1), nodeType)) {
      return null;
    }

    return state.tr.delete(start, end).setBlockType(start, start, nodeType, attrs);
  });
}
},{"prosemirror-state":"../node_modules/prosemirror-state/dist/index.es.js","prosemirror-transform":"../node_modules/prosemirror-transform/dist/index.es.js"}],"../node_modules/prosemirror-example-setup/dist/index.es.js":[function(require,module,exports) {
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.buildInputRules = buildInputRules;
exports.buildKeymap = buildKeymap;
exports.buildMenuItems = buildMenuItems;
exports.exampleSetup = exampleSetup;

var _prosemirrorKeymap = require("prosemirror-keymap");

var _prosemirrorHistory = require("prosemirror-history");

var _prosemirrorCommands = require("prosemirror-commands");

var _prosemirrorState = require("prosemirror-state");

var _prosemirrorDropcursor = require("prosemirror-dropcursor");

var _prosemirrorGapcursor = require("prosemirror-gapcursor");

var _prosemirrorMenu = require("prosemirror-menu");

var _prosemirrorSchemaList = require("prosemirror-schema-list");

var _prosemirrorInputrules = require("prosemirror-inputrules");

var prefix = "ProseMirror-prompt";

function openPrompt(options) {
  var wrapper = document.body.appendChild(document.createElement("div"));
  wrapper.className = prefix;

  var mouseOutside = function (e) {
    if (!wrapper.contains(e.target)) {
      close();
    }
  };

  setTimeout(function () {
    return window.addEventListener("mousedown", mouseOutside);
  }, 50);

  var close = function () {
    window.removeEventListener("mousedown", mouseOutside);

    if (wrapper.parentNode) {
      wrapper.parentNode.removeChild(wrapper);
    }
  };

  var domFields = [];

  for (var name in options.fields) {
    domFields.push(options.fields[name].render());
  }

  var submitButton = document.createElement("button");
  submitButton.type = "submit";
  submitButton.className = prefix + "-submit";
  submitButton.textContent = "OK";
  var cancelButton = document.createElement("button");
  cancelButton.type = "button";
  cancelButton.className = prefix + "-cancel";
  cancelButton.textContent = "Cancel";
  cancelButton.addEventListener("click", close);
  var form = wrapper.appendChild(document.createElement("form"));

  if (options.title) {
    form.appendChild(document.createElement("h5")).textContent = options.title;
  }

  domFields.forEach(function (field) {
    form.appendChild(document.createElement("div")).appendChild(field);
  });
  var buttons = form.appendChild(document.createElement("div"));
  buttons.className = prefix + "-buttons";
  buttons.appendChild(submitButton);
  buttons.appendChild(document.createTextNode(" "));
  buttons.appendChild(cancelButton);
  var box = wrapper.getBoundingClientRect();
  wrapper.style.top = (window.innerHeight - box.height) / 2 + "px";
  wrapper.style.left = (window.innerWidth - box.width) / 2 + "px";

  var submit = function () {
    var params = getValues(options.fields, domFields);

    if (params) {
      close();
      options.callback(params);
    }
  };

  form.addEventListener("submit", function (e) {
    e.preventDefault();
    submit();
  });
  form.addEventListener("keydown", function (e) {
    if (e.keyCode == 27) {
      e.preventDefault();
      close();
    } else if (e.keyCode == 13 && !(e.ctrlKey || e.metaKey || e.shiftKey)) {
      e.preventDefault();
      submit();
    } else if (e.keyCode == 9) {
      window.setTimeout(function () {
        if (!wrapper.contains(document.activeElement)) {
          close();
        }
      }, 500);
    }
  });
  var input = form.elements[0];

  if (input) {
    input.focus();
  }
}

function getValues(fields, domFields) {
  var result = Object.create(null),
      i = 0;

  for (var name in fields) {
    var field = fields[name],
        dom = domFields[i++];
    var value = field.read(dom),
        bad = field.validate(value);

    if (bad) {
      reportInvalid(dom, bad);
      return null;
    }

    result[name] = field.clean(value);
  }

  return result;
}

function reportInvalid(dom, message) {
  // FIXME this is awful and needs a lot more work
  var parent = dom.parentNode;
  var msg = parent.appendChild(document.createElement("div"));
  msg.style.left = dom.offsetLeft + dom.offsetWidth + 2 + "px";
  msg.style.top = dom.offsetTop - 5 + "px";
  msg.className = "ProseMirror-invalid";
  msg.textContent = message;
  setTimeout(function () {
    return parent.removeChild(msg);
  }, 1500);
} // ::- The type of field that `FieldPrompt` expects to be passed to it.


var Field = function Field(options) {
  this.options = options;
}; // render:: (state: EditorState, props: Object) → dom.Node
// Render the field to the DOM. Should be implemented by all subclasses.
// :: (dom.Node) → any
// Read the field's value from its DOM node.


Field.prototype.read = function read(dom) {
  return dom.value;
}; // :: (any) → ?string
// A field-type-specific validation function.


Field.prototype.validateType = function validateType(_value) {};

Field.prototype.validate = function validate(value) {
  if (!value && this.options.required) {
    return "Required field";
  }

  return this.validateType(value) || this.options.validate && this.options.validate(value);
};

Field.prototype.clean = function clean(value) {
  return this.options.clean ? this.options.clean(value) : value;
}; // ::- A field class for single-line text fields.


var TextField = /*@__PURE__*/function (Field) {
  function TextField() {
    Field.apply(this, arguments);
  }

  if (Field) TextField.__proto__ = Field;
  TextField.prototype = Object.create(Field && Field.prototype);
  TextField.prototype.constructor = TextField;

  TextField.prototype.render = function render() {
    var input = document.createElement("input");
    input.type = "text";
    input.placeholder = this.options.label;
    input.value = this.options.value || "";
    input.autocomplete = "off";
    return input;
  };

  return TextField;
}(Field); // Helpers to create specific types of items


function canInsert(state, nodeType) {
  var $from = state.selection.$from;

  for (var d = $from.depth; d >= 0; d--) {
    var index = $from.index(d);

    if ($from.node(d).canReplaceWith(index, index, nodeType)) {
      return true;
    }
  }

  return false;
}

function insertImageItem(nodeType) {
  return new _prosemirrorMenu.MenuItem({
    title: "Insert image",
    label: "Image",
    enable: function enable(state) {
      return canInsert(state, nodeType);
    },
    run: function run(state, _, view) {
      var ref = state.selection;
      var from = ref.from;
      var to = ref.to;
      var attrs = null;

      if (state.selection instanceof _prosemirrorState.NodeSelection && state.selection.node.type == nodeType) {
        attrs = state.selection.node.attrs;
      }

      openPrompt({
        title: "Insert image",
        fields: {
          src: new TextField({
            label: "Location",
            required: true,
            value: attrs && attrs.src
          }),
          title: new TextField({
            label: "Title",
            value: attrs && attrs.title
          }),
          alt: new TextField({
            label: "Description",
            value: attrs ? attrs.alt : state.doc.textBetween(from, to, " ")
          })
        },
        callback: function callback(attrs) {
          view.dispatch(view.state.tr.replaceSelectionWith(nodeType.createAndFill(attrs)));
          view.focus();
        }
      });
    }
  });
}

function cmdItem(cmd, options) {
  var passedOptions = {
    label: options.title,
    run: cmd
  };

  for (var prop in options) {
    passedOptions[prop] = options[prop];
  }

  if ((!options.enable || options.enable === true) && !options.select) {
    passedOptions[options.enable ? "enable" : "select"] = function (state) {
      return cmd(state);
    };
  }

  return new _prosemirrorMenu.MenuItem(passedOptions);
}

function markActive(state, type) {
  var ref = state.selection;
  var from = ref.from;
  var $from = ref.$from;
  var to = ref.to;
  var empty = ref.empty;

  if (empty) {
    return type.isInSet(state.storedMarks || $from.marks());
  } else {
    return state.doc.rangeHasMark(from, to, type);
  }
}

function markItem(markType, options) {
  var passedOptions = {
    active: function active(state) {
      return markActive(state, markType);
    },
    enable: true
  };

  for (var prop in options) {
    passedOptions[prop] = options[prop];
  }

  return cmdItem((0, _prosemirrorCommands.toggleMark)(markType), passedOptions);
}

function linkItem(markType) {
  return new _prosemirrorMenu.MenuItem({
    title: "Add or remove link",
    icon: _prosemirrorMenu.icons.link,
    active: function active(state) {
      return markActive(state, markType);
    },
    enable: function enable(state) {
      return !state.selection.empty;
    },
    run: function run(state, dispatch, view) {
      if (markActive(state, markType)) {
        (0, _prosemirrorCommands.toggleMark)(markType)(state, dispatch);
        return true;
      }

      openPrompt({
        title: "Create a link",
        fields: {
          href: new TextField({
            label: "Link target",
            required: true
          }),
          title: new TextField({
            label: "Title"
          })
        },
        callback: function callback(attrs) {
          (0, _prosemirrorCommands.toggleMark)(markType, attrs)(view.state, view.dispatch);
          view.focus();
        }
      });
    }
  });
}

function wrapListItem(nodeType, options) {
  return cmdItem((0, _prosemirrorSchemaList.wrapInList)(nodeType, options.attrs), options);
} // :: (Schema) → Object
// Given a schema, look for default mark and node types in it and
// return an object with relevant menu items relating to those marks:
//
// **`toggleStrong`**`: MenuItem`
//   : A menu item to toggle the [strong mark](#schema-basic.StrongMark).
//
// **`toggleEm`**`: MenuItem`
//   : A menu item to toggle the [emphasis mark](#schema-basic.EmMark).
//
// **`toggleCode`**`: MenuItem`
//   : A menu item to toggle the [code font mark](#schema-basic.CodeMark).
//
// **`toggleLink`**`: MenuItem`
//   : A menu item to toggle the [link mark](#schema-basic.LinkMark).
//
// **`insertImage`**`: MenuItem`
//   : A menu item to insert an [image](#schema-basic.Image).
//
// **`wrapBulletList`**`: MenuItem`
//   : A menu item to wrap the selection in a [bullet list](#schema-list.BulletList).
//
// **`wrapOrderedList`**`: MenuItem`
//   : A menu item to wrap the selection in an [ordered list](#schema-list.OrderedList).
//
// **`wrapBlockQuote`**`: MenuItem`
//   : A menu item to wrap the selection in a [block quote](#schema-basic.BlockQuote).
//
// **`makeParagraph`**`: MenuItem`
//   : A menu item to set the current textblock to be a normal
//     [paragraph](#schema-basic.Paragraph).
//
// **`makeCodeBlock`**`: MenuItem`
//   : A menu item to set the current textblock to be a
//     [code block](#schema-basic.CodeBlock).
//
// **`makeHead[N]`**`: MenuItem`
//   : Where _N_ is 1 to 6. Menu items to set the current textblock to
//     be a [heading](#schema-basic.Heading) of level _N_.
//
// **`insertHorizontalRule`**`: MenuItem`
//   : A menu item to insert a horizontal rule.
//
// The return value also contains some prefabricated menu elements and
// menus, that you can use instead of composing your own menu from
// scratch:
//
// **`insertMenu`**`: Dropdown`
//   : A dropdown containing the `insertImage` and
//     `insertHorizontalRule` items.
//
// **`typeMenu`**`: Dropdown`
//   : A dropdown containing the items for making the current
//     textblock a paragraph, code block, or heading.
//
// **`fullMenu`**`: [[MenuElement]]`
//   : An array of arrays of menu elements for use as the full menu
//     for, for example the [menu bar](https://github.com/prosemirror/prosemirror-menu#user-content-menubar).


function buildMenuItems(schema) {
  var r = {},
      type;

  if (type = schema.marks.strong) {
    r.toggleStrong = markItem(type, {
      title: "Toggle strong style",
      icon: _prosemirrorMenu.icons.strong
    });
  }

  if (type = schema.marks.em) {
    r.toggleEm = markItem(type, {
      title: "Toggle emphasis",
      icon: _prosemirrorMenu.icons.em
    });
  }

  if (type = schema.marks.code) {
    r.toggleCode = markItem(type, {
      title: "Toggle code font",
      icon: _prosemirrorMenu.icons.code
    });
  }

  if (type = schema.marks.link) {
    r.toggleLink = linkItem(type);
  }

  if (type = schema.nodes.image) {
    r.insertImage = insertImageItem(type);
  }

  if (type = schema.nodes.bullet_list) {
    r.wrapBulletList = wrapListItem(type, {
      title: "Wrap in bullet list",
      icon: _prosemirrorMenu.icons.bulletList
    });
  }

  if (type = schema.nodes.ordered_list) {
    r.wrapOrderedList = wrapListItem(type, {
      title: "Wrap in ordered list",
      icon: _prosemirrorMenu.icons.orderedList
    });
  }

  if (type = schema.nodes.blockquote) {
    r.wrapBlockQuote = (0, _prosemirrorMenu.wrapItem)(type, {
      title: "Wrap in block quote",
      icon: _prosemirrorMenu.icons.blockquote
    });
  }

  if (type = schema.nodes.paragraph) {
    r.makeParagraph = (0, _prosemirrorMenu.blockTypeItem)(type, {
      title: "Change to paragraph",
      label: "Plain"
    });
  }

  if (type = schema.nodes.code_block) {
    r.makeCodeBlock = (0, _prosemirrorMenu.blockTypeItem)(type, {
      title: "Change to code block",
      label: "Code"
    });
  }

  if (type = schema.nodes.heading) {
    for (var i = 1; i <= 10; i++) {
      r["makeHead" + i] = (0, _prosemirrorMenu.blockTypeItem)(type, {
        title: "Change to heading " + i,
        label: "Level " + i,
        attrs: {
          level: i
        }
      });
    }
  }

  if (type = schema.nodes.horizontal_rule) {
    var hr = type;
    r.insertHorizontalRule = new _prosemirrorMenu.MenuItem({
      title: "Insert horizontal rule",
      label: "Horizontal rule",
      enable: function enable(state) {
        return canInsert(state, hr);
      },
      run: function run(state, dispatch) {
        dispatch(state.tr.replaceSelectionWith(hr.create()));
      }
    });
  }

  var cut = function (arr) {
    return arr.filter(function (x) {
      return x;
    });
  };

  r.insertMenu = new _prosemirrorMenu.Dropdown(cut([r.insertImage, r.insertHorizontalRule]), {
    label: "Insert"
  });
  r.typeMenu = new _prosemirrorMenu.Dropdown(cut([r.makeParagraph, r.makeCodeBlock, r.makeHead1 && new _prosemirrorMenu.DropdownSubmenu(cut([r.makeHead1, r.makeHead2, r.makeHead3, r.makeHead4, r.makeHead5, r.makeHead6]), {
    label: "Heading"
  })]), {
    label: "Type..."
  });
  r.inlineMenu = [cut([r.toggleStrong, r.toggleEm, r.toggleCode, r.toggleLink])];
  r.blockMenu = [cut([r.wrapBulletList, r.wrapOrderedList, r.wrapBlockQuote, _prosemirrorMenu.joinUpItem, _prosemirrorMenu.liftItem, _prosemirrorMenu.selectParentNodeItem])];
  r.fullMenu = r.inlineMenu.concat([[r.insertMenu, r.typeMenu]], [[_prosemirrorMenu.undoItem, _prosemirrorMenu.redoItem]], r.blockMenu);
  return r;
}

var mac = typeof navigator != "undefined" ? /Mac/.test(navigator.platform) : false; // :: (Schema, ?Object) → Object
// Inspect the given schema looking for marks and nodes from the
// basic schema, and if found, add key bindings related to them.
// This will add:
//
// * **Mod-b** for toggling [strong](#schema-basic.StrongMark)
// * **Mod-i** for toggling [emphasis](#schema-basic.EmMark)
// * **Mod-`** for toggling [code font](#schema-basic.CodeMark)
// * **Ctrl-Shift-0** for making the current textblock a paragraph
// * **Ctrl-Shift-1** to **Ctrl-Shift-Digit6** for making the current
//   textblock a heading of the corresponding level
// * **Ctrl-Shift-Backslash** to make the current textblock a code block
// * **Ctrl-Shift-8** to wrap the selection in an ordered list
// * **Ctrl-Shift-9** to wrap the selection in a bullet list
// * **Ctrl->** to wrap the selection in a block quote
// * **Enter** to split a non-empty textblock in a list item while at
//   the same time splitting the list item
// * **Mod-Enter** to insert a hard break
// * **Mod-_** to insert a horizontal rule
// * **Backspace** to undo an input rule
// * **Alt-ArrowUp** to `joinUp`
// * **Alt-ArrowDown** to `joinDown`
// * **Mod-BracketLeft** to `lift`
// * **Escape** to `selectParentNode`
//
// You can suppress or map these bindings by passing a `mapKeys`
// argument, which maps key names (say `"Mod-B"` to either `false`, to
// remove the binding, or a new key name string.

function buildKeymap(schema, mapKeys) {
  var keys = {},
      type;

  function bind(key, cmd) {
    if (mapKeys) {
      var mapped = mapKeys[key];

      if (mapped === false) {
        return;
      }

      if (mapped) {
        key = mapped;
      }
    }

    keys[key] = cmd;
  }

  bind("Mod-z", _prosemirrorHistory.undo);
  bind("Shift-Mod-z", _prosemirrorHistory.redo);
  bind("Backspace", _prosemirrorInputrules.undoInputRule);

  if (!mac) {
    bind("Mod-y", _prosemirrorHistory.redo);
  }

  bind("Alt-ArrowUp", _prosemirrorCommands.joinUp);
  bind("Alt-ArrowDown", _prosemirrorCommands.joinDown);
  bind("Mod-BracketLeft", _prosemirrorCommands.lift);
  bind("Escape", _prosemirrorCommands.selectParentNode);

  if (type = schema.marks.strong) {
    bind("Mod-b", (0, _prosemirrorCommands.toggleMark)(type));
    bind("Mod-B", (0, _prosemirrorCommands.toggleMark)(type));
  }

  if (type = schema.marks.em) {
    bind("Mod-i", (0, _prosemirrorCommands.toggleMark)(type));
    bind("Mod-I", (0, _prosemirrorCommands.toggleMark)(type));
  }

  if (type = schema.marks.code) {
    bind("Mod-`", (0, _prosemirrorCommands.toggleMark)(type));
  }

  if (type = schema.nodes.bullet_list) {
    bind("Shift-Ctrl-8", (0, _prosemirrorSchemaList.wrapInList)(type));
  }

  if (type = schema.nodes.ordered_list) {
    bind("Shift-Ctrl-9", (0, _prosemirrorSchemaList.wrapInList)(type));
  }

  if (type = schema.nodes.blockquote) {
    bind("Ctrl->", (0, _prosemirrorCommands.wrapIn)(type));
  }

  if (type = schema.nodes.hard_break) {
    var br = type,
        cmd = (0, _prosemirrorCommands.chainCommands)(_prosemirrorCommands.exitCode, function (state, dispatch) {
      dispatch(state.tr.replaceSelectionWith(br.create()).scrollIntoView());
      return true;
    });
    bind("Mod-Enter", cmd);
    bind("Shift-Enter", cmd);

    if (mac) {
      bind("Ctrl-Enter", cmd);
    }
  }

  if (type = schema.nodes.list_item) {
    bind("Enter", (0, _prosemirrorSchemaList.splitListItem)(type));
    bind("Mod-[", (0, _prosemirrorSchemaList.liftListItem)(type));
    bind("Mod-]", (0, _prosemirrorSchemaList.sinkListItem)(type));
  }

  if (type = schema.nodes.paragraph) {
    bind("Shift-Ctrl-0", (0, _prosemirrorCommands.setBlockType)(type));
  }

  if (type = schema.nodes.code_block) {
    bind("Shift-Ctrl-\\", (0, _prosemirrorCommands.setBlockType)(type));
  }

  if (type = schema.nodes.heading) {
    for (var i = 1; i <= 6; i++) {
      bind("Shift-Ctrl-" + i, (0, _prosemirrorCommands.setBlockType)(type, {
        level: i
      }));
    }
  }

  if (type = schema.nodes.horizontal_rule) {
    var hr = type;
    bind("Mod-_", function (state, dispatch) {
      dispatch(state.tr.replaceSelectionWith(hr.create()).scrollIntoView());
      return true;
    });
  }

  return keys;
} // : (NodeType) → InputRule
// Given a blockquote node type, returns an input rule that turns `"> "`
// at the start of a textblock into a blockquote.


function blockQuoteRule(nodeType) {
  return (0, _prosemirrorInputrules.wrappingInputRule)(/^\s*>\s$/, nodeType);
} // : (NodeType) → InputRule
// Given a list node type, returns an input rule that turns a number
// followed by a dot at the start of a textblock into an ordered list.


function orderedListRule(nodeType) {
  return (0, _prosemirrorInputrules.wrappingInputRule)(/^(\d+)\.\s$/, nodeType, function (match) {
    return {
      order: +match[1]
    };
  }, function (match, node) {
    return node.childCount + node.attrs.order == +match[1];
  });
} // : (NodeType) → InputRule
// Given a list node type, returns an input rule that turns a bullet
// (dash, plush, or asterisk) at the start of a textblock into a
// bullet list.


function bulletListRule(nodeType) {
  return (0, _prosemirrorInputrules.wrappingInputRule)(/^\s*([-+*])\s$/, nodeType);
} // : (NodeType) → InputRule
// Given a code block node type, returns an input rule that turns a
// textblock starting with three backticks into a code block.


function codeBlockRule(nodeType) {
  return (0, _prosemirrorInputrules.textblockTypeInputRule)(/^```$/, nodeType);
} // : (NodeType, number) → InputRule
// Given a node type and a maximum level, creates an input rule that
// turns up to that number of `#` characters followed by a space at
// the start of a textblock into a heading whose level corresponds to
// the number of `#` signs.


function headingRule(nodeType, maxLevel) {
  return (0, _prosemirrorInputrules.textblockTypeInputRule)(new RegExp("^(#{1," + maxLevel + "})\\s$"), nodeType, function (match) {
    return {
      level: match[1].length
    };
  });
} // : (Schema) → Plugin
// A set of input rules for creating the basic block quotes, lists,
// code blocks, and heading.


function buildInputRules(schema) {
  var rules = _prosemirrorInputrules.smartQuotes.concat(_prosemirrorInputrules.ellipsis, _prosemirrorInputrules.emDash),
      type;

  if (type = schema.nodes.blockquote) {
    rules.push(blockQuoteRule(type));
  }

  if (type = schema.nodes.ordered_list) {
    rules.push(orderedListRule(type));
  }

  if (type = schema.nodes.bullet_list) {
    rules.push(bulletListRule(type));
  }

  if (type = schema.nodes.code_block) {
    rules.push(codeBlockRule(type));
  }

  if (type = schema.nodes.heading) {
    rules.push(headingRule(type, 6));
  }

  return (0, _prosemirrorInputrules.inputRules)({
    rules: rules
  });
} // !! This module exports helper functions for deriving a set of basic
// menu items, input rules, or key bindings from a schema. These
// values need to know about the schema for two reasons—they need
// access to specific instances of node and mark types, and they need
// to know which of the node and mark types that they know about are
// actually present in the schema.
//
// The `exampleSetup` plugin ties these together into a plugin that
// will automatically enable this basic functionality in an editor.
// :: (Object) → [Plugin]
// A convenience plugin that bundles together a simple menu with basic
// key bindings, input rules, and styling for the example schema.
// Probably only useful for quickly setting up a passable
// editor—you'll need more control over your settings in most
// real-world situations.
//
//   options::- The following options are recognized:
//
//     schema:: Schema
//     The schema to generate key bindings and menu items for.
//
//     mapKeys:: ?Object
//     Can be used to [adjust](#example-setup.buildKeymap) the key bindings created.
//
//     menuBar:: ?bool
//     Set to false to disable the menu bar.
//
//     history:: ?bool
//     Set to false to disable the history plugin.
//
//     floatingMenu:: ?bool
//     Set to false to make the menu bar non-floating.
//
//     menuContent:: [[MenuItem]]
//     Can be used to override the menu content.


function exampleSetup(options) {
  var plugins = [buildInputRules(options.schema), (0, _prosemirrorKeymap.keymap)(buildKeymap(options.schema, options.mapKeys)), (0, _prosemirrorKeymap.keymap)(_prosemirrorCommands.baseKeymap), (0, _prosemirrorDropcursor.dropCursor)(), (0, _prosemirrorGapcursor.gapCursor)()];

  if (options.menuBar !== false) {
    plugins.push((0, _prosemirrorMenu.menuBar)({
      floating: options.floatingMenu !== false,
      content: options.menuContent || buildMenuItems(options.schema).fullMenu
    }));
  }

  if (options.history !== false) {
    plugins.push((0, _prosemirrorHistory.history)());
  }

  return plugins.concat(new _prosemirrorState.Plugin({
    props: {
      attributes: {
        class: "ProseMirror-example-setup-style"
      }
    }
  }));
}
},{"prosemirror-keymap":"../node_modules/prosemirror-keymap/dist/index.es.js","prosemirror-history":"../node_modules/prosemirror-history/dist/index.es.js","prosemirror-commands":"../node_modules/prosemirror-commands/dist/index.es.js","prosemirror-state":"../node_modules/prosemirror-state/dist/index.es.js","prosemirror-dropcursor":"../node_modules/prosemirror-dropcursor/dist/index.es.js","prosemirror-gapcursor":"../node_modules/prosemirror-gapcursor/dist/index.es.js","prosemirror-menu":"../node_modules/prosemirror-menu/dist/index.es.js","prosemirror-schema-list":"../node_modules/prosemirror-schema-list/dist/index.es.js","prosemirror-inputrules":"../node_modules/prosemirror-inputrules/dist/index.es.js"}],"empty-plugin.js":[function(require,module,exports) {
"use strict";

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

var _prosemirrorState = require("prosemirror-state");

function createPluginState() {
  return {
    doSomething: function doSomething() {}
  };
}

var key = new _prosemirrorState.PluginKey("empty-plugin");
var plugin = new _prosemirrorState.Plugin({
  key: key,
  state: {
    init: function init() {
      return createPluginState();
    },
    apply: function apply(tr, pluginState) {
      return pluginState;
    }
  }
});
var _default = plugin;
exports.default = _default;
},{"prosemirror-state":"../node_modules/prosemirror-state/dist/index.es.js"}],"index.js":[function(require,module,exports) {
"use strict";

var _src = _interopRequireDefault(require("../src"));

require("./editor.css");

var _prosemirrorState = require("prosemirror-state");

var _prosemirrorView = require("prosemirror-view");

var _prosemirrorSchemaBasic = require("prosemirror-schema-basic");

var _prosemirrorExampleSetup = require("prosemirror-example-setup");

var _emptyPlugin = _interopRequireDefault(require("./empty-plugin"));

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

// aik-mode:react
var plugins = (0, _prosemirrorExampleSetup.exampleSetup)({
  schema: _prosemirrorSchemaBasic.schema
});
plugins.push(_emptyPlugin.default);
var view = new _prosemirrorView.EditorView(document.querySelector("#app"), {
  state: _prosemirrorState.EditorState.create({
    schema: _prosemirrorSchemaBasic.schema,
    plugins: plugins
  })
});
(0, _src.default)(view);
},{"../src":"../src/index.js","./editor.css":"editor.css","prosemirror-state":"../node_modules/prosemirror-state/dist/index.es.js","prosemirror-view":"../node_modules/prosemirror-view/dist/index.es.js","prosemirror-schema-basic":"../node_modules/prosemirror-schema-basic/dist/index.es.js","prosemirror-example-setup":"../node_modules/prosemirror-example-setup/dist/index.es.js","./empty-plugin":"empty-plugin.js"}],"../src/state/idle-scheduler.js":[function(require,module,exports) {
"use strict";

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

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

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; }

var IdleScheduler = /*#__PURE__*/function () {
  function IdleScheduler() {
    _classCallCheck(this, IdleScheduler);

    _defineProperty(this, "task", undefined);
  }

  _createClass(IdleScheduler, [{
    key: "request",
    value: function request() {
      this.cancel();
      var request = window.requestIdleCallback || window.requestAnimationFrame;
      return new Promise(function (resolve) {
        return request(resolve);
      });
    }
  }, {
    key: "cancel",
    value: function cancel() {
      var cancel = window.cancelIdleCallack || window.cancelAnimationFrame;

      if (this.task) {
        cancel(this.task);
      }
    }
  }]);

  return IdleScheduler;
}();

exports.IdleScheduler = IdleScheduler;
},{}],"../node_modules/parcel/src/builtins/hmr-runtime.js":[function(require,module,exports) {
var global = arguments[3];
var OVERLAY_ID = '__parcel__error__overlay__';
var OldModule = module.bundle.Module;

function Module(moduleName) {
  OldModule.call(this, moduleName);
  this.hot = {
    data: module.bundle.hotData,
    _acceptCallbacks: [],
    _disposeCallbacks: [],
    accept: function (fn) {
      this._acceptCallbacks.push(fn || function () {});
    },
    dispose: function (fn) {
      this._disposeCallbacks.push(fn);
    }
  };
  module.bundle.hotData = null;
}

module.bundle.Module = Module;
var checkedAssets, assetsToAccept;
var parent = module.bundle.parent;

if ((!parent || !parent.isParcelRequire) && typeof WebSocket !== 'undefined') {
  var hostname = "" || location.hostname;
  var protocol = location.protocol === 'https:' ? 'wss' : 'ws';
  var ws = new WebSocket(protocol + '://' + hostname + ':' + "53419" + '/');

  ws.onmessage = function (event) {
    checkedAssets = {};
    assetsToAccept = [];
    var data = JSON.parse(event.data);

    if (data.type === 'update') {
      var handled = false;
      data.assets.forEach(function (asset) {
        if (!asset.isNew) {
          var didAccept = hmrAcceptCheck(global.parcelRequire, asset.id);

          if (didAccept) {
            handled = true;
          }
        }
      }); // Enable HMR for CSS by default.

      handled = handled || data.assets.every(function (asset) {
        return asset.type === 'css' && asset.generated.js;
      });

      if (handled) {
        console.clear();
        data.assets.forEach(function (asset) {
          hmrApply(global.parcelRequire, asset);
        });
        assetsToAccept.forEach(function (v) {
          hmrAcceptRun(v[0], v[1]);
        });
      } else if (location.reload) {
        // `location` global exists in a web worker context but lacks `.reload()` function.
        location.reload();
      }
    }

    if (data.type === 'reload') {
      ws.close();

      ws.onclose = function () {
        location.reload();
      };
    }

    if (data.type === 'error-resolved') {
      console.log('[parcel] ✨ Error resolved');
      removeErrorOverlay();
    }

    if (data.type === 'error') {
      console.error('[parcel] 🚨  ' + data.error.message + '\n' + data.error.stack);
      removeErrorOverlay();
      var overlay = createErrorOverlay(data);
      document.body.appendChild(overlay);
    }
  };
}

function removeErrorOverlay() {
  var overlay = document.getElementById(OVERLAY_ID);

  if (overlay) {
    overlay.remove();
  }
}

function createErrorOverlay(data) {
  var overlay = document.createElement('div');
  overlay.id = OVERLAY_ID; // html encode message and stack trace

  var message = document.createElement('div');
  var stackTrace = document.createElement('pre');
  message.innerText = data.error.message;
  stackTrace.innerText = data.error.stack;
  overlay.innerHTML = '<div style="background: black; font-size: 16px; color: white; position: fixed; height: 100%; width: 100%; top: 0px; left: 0px; padding: 30px; opacity: 0.85; font-family: Menlo, Consolas, monospace; z-index: 9999;">' + '<span style="background: red; padding: 2px 4px; border-radius: 2px;">ERROR</span>' + '<span style="top: 2px; margin-left: 5px; position: relative;">🚨</span>' + '<div style="font-size: 18px; font-weight: bold; margin-top: 20px;">' + message.innerHTML + '</div>' + '<pre>' + stackTrace.innerHTML + '</pre>' + '</div>';
  return overlay;
}

function getParents(bundle, id) {
  var modules = bundle.modules;

  if (!modules) {
    return [];
  }

  var parents = [];
  var k, d, dep;

  for (k in modules) {
    for (d in modules[k][1]) {
      dep = modules[k][1][d];

      if (dep === id || Array.isArray(dep) && dep[dep.length - 1] === id) {
        parents.push(k);
      }
    }
  }

  if (bundle.parent) {
    parents = parents.concat(getParents(bundle.parent, id));
  }

  return parents;
}

function hmrApply(bundle, asset) {
  var modules = bundle.modules;

  if (!modules) {
    return;
  }

  if (modules[asset.id] || !bundle.parent) {
    var fn = new Function('require', 'module', 'exports', asset.generated.js);
    asset.isNew = !modules[asset.id];
    modules[asset.id] = [fn, asset.deps];
  } else if (bundle.parent) {
    hmrApply(bundle.parent, asset);
  }
}

function hmrAcceptCheck(bundle, id) {
  var modules = bundle.modules;

  if (!modules) {
    return;
  }

  if (!modules[id] && bundle.parent) {
    return hmrAcceptCheck(bundle.parent, id);
  }

  if (checkedAssets[id]) {
    return;
  }

  checkedAssets[id] = true;
  var cached = bundle.cache[id];
  assetsToAccept.push([bundle, id]);

  if (cached && cached.hot && cached.hot._acceptCallbacks.length) {
    return true;
  }

  return getParents(global.parcelRequire, id).some(function (id) {
    return hmrAcceptCheck(global.parcelRequire, id);
  });
}

function hmrAcceptRun(bundle, id) {
  var cached = bundle.cache[id];
  bundle.hotData = {};

  if (cached) {
    cached.hot.data = bundle.hotData;
  }

  if (cached && cached.hot && cached.hot._disposeCallbacks.length) {
    cached.hot._disposeCallbacks.forEach(function (cb) {
      cb(bundle.hotData);
    });
  }

  delete bundle.cache[id];
  bundle(id);
  cached = bundle.cache[id];

  if (cached && cached.hot && cached.hot._acceptCallbacks.length) {
    cached.hot._acceptCallbacks.forEach(function (cb) {
      cb();
    });

    return true;
  }
}
},{}],"../node_modules/parcel/src/builtins/loaders/browser/js-loader.js":[function(require,module,exports) {
module.exports = function loadJSBundle(bundle) {
  return new Promise(function (resolve, reject) {
    var script = document.createElement('script');
    script.async = true;
    script.type = 'text/javascript';
    script.charset = 'utf-8';
    script.src = bundle;

    script.onerror = function (e) {
      script.onerror = script.onload = null;
      reject(e);
    };

    script.onload = function () {
      script.onerror = script.onload = null;
      resolve();
    };

    document.getElementsByTagName('head')[0].appendChild(script);
  });
};
},{}],0:[function(require,module,exports) {
var b=require("../node_modules/parcel/src/builtins/bundle-loader.js");b.register("js",require("../node_modules/parcel/src/builtins/loaders/browser/js-loader.js"));
},{}]},{},["../node_modules/parcel/src/builtins/hmr-runtime.js",0,"index.js"], null)
//# sourceMappingURL=/example.e31bb0bc.js.map