index.umd.js 15.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('react-dom'), require('@popperjs/core')) :
  typeof define === 'function' && define.amd ? define(['exports', 'react', 'react-dom', '@popperjs/core'], factory) :
  (global = global || self, factory(global.ReactPopper = {}, global.React, global.ReactDOM, global.Popper));
}(this, (function (exports, React, ReactDOM, core) { 'use strict';

  var ManagerReferenceNodeContext = React.createContext();
  var ManagerReferenceNodeSetterContext = React.createContext();
  function Manager(_ref) {
    var children = _ref.children;

    var _React$useState = React.useState(null),
        referenceNode = _React$useState[0],
        setReferenceNode = _React$useState[1];

    var hasUnmounted = React.useRef(false);
    React.useEffect(function () {
      return function () {
        hasUnmounted.current = true;
      };
    }, []);
    var handleSetReferenceNode = React.useCallback(function (node) {
      if (!hasUnmounted.current) {
        setReferenceNode(node);
      }
    }, []);
    return /*#__PURE__*/React.createElement(ManagerReferenceNodeContext.Provider, {
      value: referenceNode
    }, /*#__PURE__*/React.createElement(ManagerReferenceNodeSetterContext.Provider, {
      value: handleSetReferenceNode
    }, children));
  }

  /**
   * Takes an argument and if it's an array, returns the first item in the array,
   * otherwise returns the argument. Used for Preact compatibility.
   */
  var unwrapArray = function unwrapArray(arg) {
    return Array.isArray(arg) ? arg[0] : arg;
  };
  /**
   * Takes a maybe-undefined function and arbitrary args and invokes the function
   * only if it is defined.
   */

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

      return fn.apply(void 0, args);
    }
  };
  /**
   * Sets a ref using either a ref callback or a ref object
   */

  var setRef = function setRef(ref, node) {
    // if its a function call it
    if (typeof ref === 'function') {
      return safeInvoke(ref, node);
    } // otherwise we should treat it as a ref object
    else if (ref != null) {
        ref.current = node;
      }
  };
  /**
   * Simple ponyfill for Object.fromEntries
   */

  var fromEntries = function fromEntries(entries) {
    return entries.reduce(function (acc, _ref) {
      var key = _ref[0],
          value = _ref[1];
      acc[key] = value;
      return acc;
    }, {});
  };
  /**
   * Small wrapper around `useLayoutEffect` to get rid of the warning on SSR envs
   */

  var useIsomorphicLayoutEffect = typeof window !== 'undefined' && window.document && window.document.createElement ? React.useLayoutEffect : React.useEffect;

  /* global Map:readonly, Set:readonly, ArrayBuffer:readonly */

  var hasElementType = typeof Element !== 'undefined';
  var hasMap = typeof Map === 'function';
  var hasSet = typeof Set === 'function';
  var hasArrayBuffer = typeof ArrayBuffer === 'function';

  // Note: We **don't** need `envHasBigInt64Array` in fde es6/index.js

  function equal(a, b) {
    // START: fast-deep-equal es6/index.js 3.1.1
    if (a === b) return true;

    if (a && b && typeof a == 'object' && typeof b == 'object') {
      if (a.constructor !== b.constructor) return false;

      var length, i, keys;
      if (Array.isArray(a)) {
        length = a.length;
        if (length != b.length) return false;
        for (i = length; i-- !== 0;)
          if (!equal(a[i], b[i])) return false;
        return true;
      }

      // START: Modifications:
      // 1. Extra `has<Type> &&` helpers in initial condition allow es6 code
      //    to co-exist with es5.
      // 2. Replace `for of` with es5 compliant iteration using `for`.
      //    Basically, take:
      //
      //    ```js
      //    for (i of a.entries())
      //      if (!b.has(i[0])) return false;
      //    ```
      //
      //    ... and convert to:
      //
      //    ```js
      //    it = a.entries();
      //    while (!(i = it.next()).done)
      //      if (!b.has(i.value[0])) return false;
      //    ```
      //
      //    **Note**: `i` access switches to `i.value`.
      var it;
      if (hasMap && (a instanceof Map) && (b instanceof Map)) {
        if (a.size !== b.size) return false;
        it = a.entries();
        while (!(i = it.next()).done)
          if (!b.has(i.value[0])) return false;
        it = a.entries();
        while (!(i = it.next()).done)
          if (!equal(i.value[1], b.get(i.value[0]))) return false;
        return true;
      }

      if (hasSet && (a instanceof Set) && (b instanceof Set)) {
        if (a.size !== b.size) return false;
        it = a.entries();
        while (!(i = it.next()).done)
          if (!b.has(i.value[0])) return false;
        return true;
      }
      // END: Modifications

      if (hasArrayBuffer && ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {
        length = a.length;
        if (length != b.length) return false;
        for (i = length; i-- !== 0;)
          if (a[i] !== b[i]) return false;
        return true;
      }

      if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
      if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
      if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();

      keys = Object.keys(a);
      length = keys.length;
      if (length !== Object.keys(b).length) return false;

      for (i = length; i-- !== 0;)
        if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
      // END: fast-deep-equal

      // START: react-fast-compare
      // custom handling for DOM elements
      if (hasElementType && a instanceof Element) return false;

      // custom handling for React
      for (i = length; i-- !== 0;) {
        if (keys[i] === '_owner' && a.$$typeof) {
          // React-specific: avoid traversing React elements' _owner.
          //  _owner contains circular references
          // and is not needed when comparing the actual elements (and not their owners)
          // .$$typeof and ._store on just reasonable markers of a react element
          continue;
        }

        // all other properties should be traversed as usual
        if (!equal(a[keys[i]], b[keys[i]])) return false;
      }
      // END: react-fast-compare

      // START: fast-deep-equal
      return true;
    }

    return a !== a && b !== b;
  }
  // end fast-deep-equal

  var reactFastCompare = function isEqual(a, b) {
    try {
      return equal(a, b);
    } catch (error) {
      if (((error.message || '').match(/stack|recursion/i))) {
        // warn on circular references, don't crash
        // browsers give this different errors name and messages:
        // chrome/safari: "RangeError", "Maximum call stack size exceeded"
        // firefox: "InternalError", too much recursion"
        // edge: "Error", "Out of stack space"
        console.warn('react-fast-compare cannot handle circular refs');
        return false;
      }
      // some other error. we should definitely know about these
      throw error;
    }
  };

  var EMPTY_MODIFIERS = [];
  var usePopper = function usePopper(referenceElement, popperElement, options) {
    if (options === void 0) {
      options = {};
    }

    var prevOptions = React.useRef(null);
    var optionsWithDefaults = {
      onFirstUpdate: options.onFirstUpdate,
      placement: options.placement || 'bottom',
      strategy: options.strategy || 'absolute',
      modifiers: options.modifiers || EMPTY_MODIFIERS
    };

    var _React$useState = React.useState({
      styles: {
        popper: {
          position: optionsWithDefaults.strategy,
          left: '0',
          top: '0'
        },
        arrow: {
          position: 'absolute'
        }
      },
      attributes: {}
    }),
        state = _React$useState[0],
        setState = _React$useState[1];

    var updateStateModifier = React.useMemo(function () {
      return {
        name: 'updateState',
        enabled: true,
        phase: 'write',
        fn: function fn(_ref) {
          var state = _ref.state;
          var elements = Object.keys(state.elements);
          ReactDOM.flushSync(function () {
            setState({
              styles: fromEntries(elements.map(function (element) {
                return [element, state.styles[element] || {}];
              })),
              attributes: fromEntries(elements.map(function (element) {
                return [element, state.attributes[element]];
              }))
            });
          });
        },
        requires: ['computeStyles']
      };
    }, []);
    var popperOptions = React.useMemo(function () {
      var newOptions = {
        onFirstUpdate: optionsWithDefaults.onFirstUpdate,
        placement: optionsWithDefaults.placement,
        strategy: optionsWithDefaults.strategy,
        modifiers: [].concat(optionsWithDefaults.modifiers, [updateStateModifier, {
          name: 'applyStyles',
          enabled: false
        }])
      };

      if (reactFastCompare(prevOptions.current, newOptions)) {
        return prevOptions.current || newOptions;
      } else {
        prevOptions.current = newOptions;
        return newOptions;
      }
    }, [optionsWithDefaults.onFirstUpdate, optionsWithDefaults.placement, optionsWithDefaults.strategy, optionsWithDefaults.modifiers, updateStateModifier]);
    var popperInstanceRef = React.useRef();
    useIsomorphicLayoutEffect(function () {
      if (popperInstanceRef.current) {
        popperInstanceRef.current.setOptions(popperOptions);
      }
    }, [popperOptions]);
    useIsomorphicLayoutEffect(function () {
      if (referenceElement == null || popperElement == null) {
        return;
      }

      var createPopper = options.createPopper || core.createPopper;
      var popperInstance = createPopper(referenceElement, popperElement, popperOptions);
      popperInstanceRef.current = popperInstance;
      return function () {
        popperInstance.destroy();
        popperInstanceRef.current = null;
      };
    }, [referenceElement, popperElement, options.createPopper]);
    return {
      state: popperInstanceRef.current ? popperInstanceRef.current.state : null,
      styles: state.styles,
      attributes: state.attributes,
      update: popperInstanceRef.current ? popperInstanceRef.current.update : null,
      forceUpdate: popperInstanceRef.current ? popperInstanceRef.current.forceUpdate : null
    };
  };

  var NOOP = function NOOP() {
    return void 0;
  };

  var NOOP_PROMISE = function NOOP_PROMISE() {
    return Promise.resolve(null);
  };

  var EMPTY_MODIFIERS$1 = [];
  function Popper(_ref) {
    var _ref$placement = _ref.placement,
        placement = _ref$placement === void 0 ? 'bottom' : _ref$placement,
        _ref$strategy = _ref.strategy,
        strategy = _ref$strategy === void 0 ? 'absolute' : _ref$strategy,
        _ref$modifiers = _ref.modifiers,
        modifiers = _ref$modifiers === void 0 ? EMPTY_MODIFIERS$1 : _ref$modifiers,
        referenceElement = _ref.referenceElement,
        onFirstUpdate = _ref.onFirstUpdate,
        innerRef = _ref.innerRef,
        children = _ref.children;
    var referenceNode = React.useContext(ManagerReferenceNodeContext);

    var _React$useState = React.useState(null),
        popperElement = _React$useState[0],
        setPopperElement = _React$useState[1];

    var _React$useState2 = React.useState(null),
        arrowElement = _React$useState2[0],
        setArrowElement = _React$useState2[1];

    React.useEffect(function () {
      setRef(innerRef, popperElement);
    }, [innerRef, popperElement]);
    var options = React.useMemo(function () {
      return {
        placement: placement,
        strategy: strategy,
        onFirstUpdate: onFirstUpdate,
        modifiers: [].concat(modifiers, [{
          name: 'arrow',
          enabled: arrowElement != null,
          options: {
            element: arrowElement
          }
        }])
      };
    }, [placement, strategy, onFirstUpdate, modifiers, arrowElement]);

    var _usePopper = usePopper(referenceElement || referenceNode, popperElement, options),
        state = _usePopper.state,
        styles = _usePopper.styles,
        forceUpdate = _usePopper.forceUpdate,
        update = _usePopper.update;

    var childrenProps = React.useMemo(function () {
      return {
        ref: setPopperElement,
        style: styles.popper,
        placement: state ? state.placement : placement,
        hasPopperEscaped: state && state.modifiersData.hide ? state.modifiersData.hide.hasPopperEscaped : null,
        isReferenceHidden: state && state.modifiersData.hide ? state.modifiersData.hide.isReferenceHidden : null,
        arrowProps: {
          style: styles.arrow,
          ref: setArrowElement
        },
        forceUpdate: forceUpdate || NOOP,
        update: update || NOOP_PROMISE
      };
    }, [setPopperElement, setArrowElement, placement, state, styles, update, forceUpdate]);
    return unwrapArray(children)(childrenProps);
  }

  /**
   * 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 warning = function() {};

  {
    var printWarning = function printWarning(format, args) {
      var len = arguments.length;
      args = new Array(len > 1 ? len - 1 : 0);
      for (var key = 1; key < len; key++) {
        args[key - 1] = arguments[key];
      }
      var argIndex = 0;
      var message = 'Warning: ' +
        format.replace(/%s/g, function() {
          return args[argIndex++];
        });
      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) {}
    };

    warning = function(condition, format, args) {
      var len = arguments.length;
      args = new Array(len > 2 ? len - 2 : 0);
      for (var key = 2; key < len; key++) {
        args[key - 2] = arguments[key];
      }
      if (format === undefined) {
        throw new Error(
            '`warning(condition, format, ...args)` requires a warning ' +
            'message argument'
        );
      }
      if (!condition) {
        printWarning.apply(null, [format].concat(args));
      }
    };
  }

  var warning_1 = warning;

  function Reference(_ref) {
    var children = _ref.children,
        innerRef = _ref.innerRef;
    var setReferenceNode = React.useContext(ManagerReferenceNodeSetterContext);
    var refHandler = React.useCallback(function (node) {
      setRef(innerRef, node);
      safeInvoke(setReferenceNode, node);
    }, [innerRef, setReferenceNode]); // ran on unmount
    // eslint-disable-next-line react-hooks/exhaustive-deps

    React.useEffect(function () {
      return function () {
        return setRef(innerRef, null);
      };
    }, []);
    React.useEffect(function () {
      warning_1(Boolean(setReferenceNode), '`Reference` should not be used outside of a `Manager` component.');
    }, [setReferenceNode]);
    return unwrapArray(children)({
      ref: refHandler
    });
  }

  exports.Manager = Manager;
  exports.Popper = Popper;
  exports.Reference = Reference;
  exports.usePopper = usePopper;

  Object.defineProperty(exports, '__esModule', { value: true });

})));