import React__default, { useCallback } from 'react';
import './_rollupPluginBabelHelpers-fbdd2755.js';
import '@emotion/core';
import './_commonjsHelpers-f108cd30.js';
import './index-f63a05a4.js';
import { a as __assign, _ as __rest, b as __makeTemplateObject } from './_tslib-5c49bd3f.js';
import { jsxs, jsx } from '@emotion/react/jsx-runtime';
import '@emotion/styled';
import '@emotion/react';
import { s as styled, c as css, k as keyframes } from './css-efbd0d2d.js';
import './index-e10049cf.js';
import { p as propTypes } from './index-fe1f8e20.js';
import { u as useId } from './auto-id.esm-bfe8e225.js';
import './createIconComponent-a0408d76.js';
import { u as useCustomCss, a as usePrevious } from './utilities-357c56e6.js';
import ReactDOM from 'react-dom';
import { l as lib } from './index-3d4509d3.js';
import { IconButton } from './IconButton.js';
import { C as Cross } from './cross-heavy-07fbc3e7.js';

/*!
* tabbable 5.1.5
* @license MIT, https://github.com/focus-trap/tabbable/blob/master/LICENSE
*/
var candidateSelectors = ['input', 'select', 'textarea', 'a[href]', 'button', '[tabindex]', 'audio[controls]', 'video[controls]', '[contenteditable]:not([contenteditable="false"])', 'details>summary:first-of-type', 'details'];
var candidateSelector = /* #__PURE__ */candidateSelectors.join(',');
var matches = typeof Element === 'undefined' ? function () {} : Element.prototype.matches || Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector;

var getCandidates = function getCandidates(el, includeContainer, filter) {
  var candidates = Array.prototype.slice.apply(el.querySelectorAll(candidateSelector));

  if (includeContainer && matches.call(el, candidateSelector)) {
    candidates.unshift(el);
  }

  candidates = candidates.filter(filter);
  return candidates;
};

var isContentEditable = function isContentEditable(node) {
  return node.contentEditable === 'true';
};

var getTabindex = function getTabindex(node) {
  var tabindexAttr = parseInt(node.getAttribute('tabindex'), 10);

  if (!isNaN(tabindexAttr)) {
    return tabindexAttr;
  } // Browsers do not return `tabIndex` correctly for contentEditable nodes;
  // so if they don't have a tabindex attribute specifically set, assume it's 0.


  if (isContentEditable(node)) {
    return 0;
  } // in Chrome, <details/>, <audio controls/> and <video controls/> elements get a default
  //  `tabIndex` of -1 when the 'tabindex' attribute isn't specified in the DOM,
  //  yet they are still part of the regular tab order; in FF, they get a default
  //  `tabIndex` of 0; since Chrome still puts those elements in the regular tab
  //  order, consider their tab index to be 0.


  if ((node.nodeName === 'AUDIO' || node.nodeName === 'VIDEO' || node.nodeName === 'DETAILS') && node.getAttribute('tabindex') === null) {
    return 0;
  }

  return node.tabIndex;
};

var sortOrderedTabbables = function sortOrderedTabbables(a, b) {
  return a.tabIndex === b.tabIndex ? a.documentOrder - b.documentOrder : a.tabIndex - b.tabIndex;
};

var isInput = function isInput(node) {
  return node.tagName === 'INPUT';
};

var isHiddenInput = function isHiddenInput(node) {
  return isInput(node) && node.type === 'hidden';
};

var isDetailsWithSummary = function isDetailsWithSummary(node) {
  var r = node.tagName === 'DETAILS' && Array.prototype.slice.apply(node.children).some(function (child) {
    return child.tagName === 'SUMMARY';
  });
  return r;
};

var getCheckedRadio = function getCheckedRadio(nodes, form) {
  for (var i = 0; i < nodes.length; i++) {
    if (nodes[i].checked && nodes[i].form === form) {
      return nodes[i];
    }
  }
};

var isTabbableRadio = function isTabbableRadio(node) {
  if (!node.name) {
    return true;
  }

  var radioScope = node.form || node.ownerDocument;

  var queryRadios = function queryRadios(name) {
    return radioScope.querySelectorAll('input[type="radio"][name="' + name + '"]');
  };

  var radioSet;

  if (typeof window !== 'undefined' && typeof window.CSS !== 'undefined' && typeof window.CSS.escape === 'function') {
    radioSet = queryRadios(window.CSS.escape(node.name));
  } else {
    try {
      radioSet = queryRadios(node.name);
    } catch (err) {
      // eslint-disable-next-line no-console
      console.error('Looks like you have a radio button with a name attribute containing invalid CSS selector characters and need the CSS.escape polyfill: %s', err.message);
      return false;
    }
  }

  var checked = getCheckedRadio(radioSet, node.form);
  return !checked || checked === node;
};

var isRadio = function isRadio(node) {
  return isInput(node) && node.type === 'radio';
};

var isNonTabbableRadio = function isNonTabbableRadio(node) {
  return isRadio(node) && !isTabbableRadio(node);
};

var isHidden = function isHidden(node) {
  if (getComputedStyle(node).visibility === 'hidden') {
    return true;
  }

  var isDirectSummary = matches.call(node, 'details>summary:first-of-type');
  var nodeUnderDetails = isDirectSummary ? node.parentElement : node;

  if (matches.call(nodeUnderDetails, 'details:not([open]) *')) {
    return true;
  }

  while (node) {
    if (getComputedStyle(node).display === 'none') {
      return true;
    }

    node = node.parentElement;
  }

  return false;
};

var isNodeMatchingSelectorFocusable = function isNodeMatchingSelectorFocusable(node) {
  if (node.disabled || isHiddenInput(node) || isHidden(node) ||
  /* For a details element with a summary, the summary element gets the focused  */
  isDetailsWithSummary(node)) {
    return false;
  }

  return true;
};

var isNodeMatchingSelectorTabbable = function isNodeMatchingSelectorTabbable(node) {
  if (!isNodeMatchingSelectorFocusable(node) || isNonTabbableRadio(node) || getTabindex(node) < 0) {
    return false;
  }

  return true;
};

var tabbable = function tabbable(el, options) {
  options = options || {};
  var regularTabbables = [];
  var orderedTabbables = [];
  var candidates = getCandidates(el, options.includeContainer, isNodeMatchingSelectorTabbable);
  candidates.forEach(function (candidate, i) {
    var candidateTabindex = getTabindex(candidate);

    if (candidateTabindex === 0) {
      regularTabbables.push(candidate);
    } else {
      orderedTabbables.push({
        documentOrder: i,
        tabIndex: candidateTabindex,
        node: candidate
      });
    }
  });
  var tabbableNodes = orderedTabbables.sort(sortOrderedTabbables).map(function (a) {
    return a.node;
  }).concat(regularTabbables);
  return tabbableNodes;
};

var focusableCandidateSelector = /* #__PURE__ */candidateSelectors.concat('iframe').join(',');

var isFocusable = function isFocusable(node) {
  if (!node) {
    throw new Error('No node provided');
  }

  if (matches.call(node, focusableCandidateSelector) === false) {
    return false;
  }

  return isNodeMatchingSelectorFocusable(node);
};

/*!
* focus-trap 6.3.0
* @license MIT, https://github.com/focus-trap/focus-trap/blob/master/LICENSE
*/

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

  return obj;
}

function 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 _objectSpread2(target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i] != null ? arguments[i] : {};

    if (i % 2) {
      ownKeys(Object(source), true).forEach(function (key) {
        _defineProperty(target, key, source[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
    } else {
      ownKeys(Object(source)).forEach(function (key) {
        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
      });
    }
  }

  return target;
}

var activeFocusDelay;

var activeFocusTraps = function () {
  var trapQueue = [];
  return {
    activateTrap: function activateTrap(trap) {
      if (trapQueue.length > 0) {
        var activeTrap = trapQueue[trapQueue.length - 1];

        if (activeTrap !== trap) {
          activeTrap.pause();
        }
      }

      var trapIndex = trapQueue.indexOf(trap);

      if (trapIndex === -1) {
        trapQueue.push(trap);
      } else {
        // move this existing trap to the front of the queue
        trapQueue.splice(trapIndex, 1);
        trapQueue.push(trap);
      }
    },
    deactivateTrap: function deactivateTrap(trap) {
      var trapIndex = trapQueue.indexOf(trap);

      if (trapIndex !== -1) {
        trapQueue.splice(trapIndex, 1);
      }

      if (trapQueue.length > 0) {
        trapQueue[trapQueue.length - 1].unpause();
      }
    }
  };
}();

var isSelectableInput = function isSelectableInput(node) {
  return node.tagName && node.tagName.toLowerCase() === 'input' && typeof node.select === 'function';
};

var isEscapeEvent = function isEscapeEvent(e) {
  return e.key === 'Escape' || e.key === 'Esc' || e.keyCode === 27;
};

var isTabEvent = function isTabEvent(e) {
  return e.key === 'Tab' || e.keyCode === 9;
};

var delay = function delay(fn) {
  return setTimeout(fn, 0);
}; // Array.find/findIndex() are not supported on IE; this replicates enough
//  of Array.findIndex() for our needs


var findIndex = function findIndex(arr, fn) {
  var idx = -1;
  arr.every(function (value, i) {
    if (fn(value)) {
      idx = i;
      return false; // break
    }

    return true; // next
  });
  return idx;
};
/**
 * Get an option's value when it could be a plain value, or a handler that provides
 *  the value.
 * @param {*} value Option's value to check.
 * @param {...*} [params] Any parameters to pass to the handler, if `value` is a function.
 * @returns {*} The `value`, or the handler's returned value.
 */


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

  return typeof value === 'function' ? value.apply(void 0, params) : value;
};

var createFocusTrap = function createFocusTrap(elements, userOptions) {
  var doc = document;

  var config = _objectSpread2({
    returnFocusOnDeactivate: true,
    escapeDeactivates: true,
    delayInitialFocus: true
  }, userOptions);

  var state = {
    // @type {Array<HTMLElement>}
    containers: [],
    // list of objects identifying the first and last tabbable nodes in all containers/groups in
    //  the trap
    // NOTE: it's possible that a group has no tabbable nodes if nodes get removed while the trap
    //  is active, but the trap should never get to a state where there isn't at least one group
    //  with at least one tabbable node in it (that would lead to an error condition that would
    //  result in an error being thrown)
    // @type {Array<{ container: HTMLElement, firstTabbableNode: HTMLElement|null, lastTabbableNode: HTMLElement|null }>}
    tabbableGroups: [],
    nodeFocusedBeforeActivation: null,
    mostRecentlyFocusedNode: null,
    active: false,
    paused: false
  };
  var trap; // eslint-disable-line prefer-const -- some private functions reference it, and its methods reference private functions, so we must declare here and define later

  var containersContain = function containersContain(element) {
    return state.containers.some(function (container) {
      return container.contains(element);
    });
  };

  var getNodeForOption = function getNodeForOption(optionName) {
    var optionValue = config[optionName];

    if (!optionValue) {
      return null;
    }

    var node = optionValue;

    if (typeof optionValue === 'string') {
      node = doc.querySelector(optionValue);

      if (!node) {
        throw new Error("`".concat(optionName, "` refers to no known node"));
      }
    }

    if (typeof optionValue === 'function') {
      node = optionValue();

      if (!node) {
        throw new Error("`".concat(optionName, "` did not return a node"));
      }
    }

    return node;
  };

  var getInitialFocusNode = function getInitialFocusNode() {
    var node;

    if (getNodeForOption('initialFocus') !== null) {
      node = getNodeForOption('initialFocus');
    } else if (containersContain(doc.activeElement)) {
      node = doc.activeElement;
    } else {
      var firstTabbableGroup = state.tabbableGroups[0];
      var firstTabbableNode = firstTabbableGroup && firstTabbableGroup.firstTabbableNode;
      node = firstTabbableNode || getNodeForOption('fallbackFocus');
    }

    if (!node) {
      throw new Error('Your focus-trap needs to have at least one focusable element');
    }

    return node;
  };

  var updateTabbableNodes = function updateTabbableNodes() {
    state.tabbableGroups = state.containers.map(function (container) {
      var tabbableNodes = tabbable(container);

      if (tabbableNodes.length > 0) {
        return {
          container: container,
          firstTabbableNode: tabbableNodes[0],
          lastTabbableNode: tabbableNodes[tabbableNodes.length - 1]
        };
      }

      return undefined;
    }).filter(function (group) {
      return !!group;
    }); // remove groups with no tabbable nodes
    // throw if no groups have tabbable nodes and we don't have a fallback focus node either

    if (state.tabbableGroups.length <= 0 && !getNodeForOption('fallbackFocus')) {
      throw new Error('Your focus-trap must have at least one container with at least one tabbable node in it at all times');
    }
  };

  var tryFocus = function tryFocus(node) {
    if (node === doc.activeElement) {
      return;
    }

    if (!node || !node.focus) {
      tryFocus(getInitialFocusNode());
      return;
    }

    node.focus({
      preventScroll: !!config.preventScroll
    });
    state.mostRecentlyFocusedNode = node;

    if (isSelectableInput(node)) {
      node.select();
    }
  };

  var getReturnFocusNode = function getReturnFocusNode(previousActiveElement) {
    var node = getNodeForOption('setReturnFocus');
    return node ? node : previousActiveElement;
  }; // This needs to be done on mousedown and touchstart instead of click
  // so that it precedes the focus event.


  var checkPointerDown = function checkPointerDown(e) {
    if (containersContain(e.target)) {
      // allow the click since it ocurred inside the trap
      return;
    }

    if (valueOrHandler(config.clickOutsideDeactivates, e)) {
      // immediately deactivate the trap
      trap.deactivate({
        // if, on deactivation, we should return focus to the node originally-focused
        //  when the trap was activated (or the configured `setReturnFocus` node),
        //  then assume it's also OK to return focus to the outside node that was
        //  just clicked, causing deactivation, as long as that node is focusable;
        //  if it isn't focusable, then return focus to the original node focused
        //  on activation (or the configured `setReturnFocus` node)
        // NOTE: by setting `returnFocus: false`, deactivate() will do nothing,
        //  which will result in the outside click setting focus to the node
        //  that was clicked, whether it's focusable or not; by setting
        //  `returnFocus: true`, we'll attempt to re-focus the node originally-focused
        //  on activation (or the configured `setReturnFocus` node)
        returnFocus: config.returnFocusOnDeactivate && !isFocusable(e.target)
      });
      return;
    } // This is needed for mobile devices.
    // (If we'll only let `click` events through,
    // then on mobile they will be blocked anyways if `touchstart` is blocked.)


    if (valueOrHandler(config.allowOutsideClick, e)) {
      // allow the click outside the trap to take place
      return;
    } // otherwise, prevent the click


    e.preventDefault();
  }; // In case focus escapes the trap for some strange reason, pull it back in.


  var checkFocusIn = function checkFocusIn(e) {
    var targetContained = containersContain(e.target); // In Firefox when you Tab out of an iframe the Document is briefly focused.

    if (targetContained || e.target instanceof Document) {
      if (targetContained) {
        state.mostRecentlyFocusedNode = e.target;
      }
    } else {
      // escaped! pull it back in to where it just left
      e.stopImmediatePropagation();
      tryFocus(state.mostRecentlyFocusedNode || getInitialFocusNode());
    }
  }; // Hijack Tab events on the first and last focusable nodes of the trap,
  // in order to prevent focus from escaping. If it escapes for even a
  // moment it can end up scrolling the page and causing confusion so we
  // kind of need to capture the action at the keydown phase.


  var checkTab = function checkTab(e) {
    updateTabbableNodes();
    var destinationNode = null;

    if (state.tabbableGroups.length > 0) {
      // make sure the target is actually contained in a group
      var containerIndex = findIndex(state.tabbableGroups, function (_ref) {
        var container = _ref.container;
        return container.contains(e.target);
      });

      if (containerIndex < 0) {
        // target not found in any group: quite possible focus has escaped the trap,
        //  so bring it back in to...
        if (e.shiftKey) {
          // ...the last node in the last group
          destinationNode = state.tabbableGroups[state.tabbableGroups.length - 1].lastTabbableNode;
        } else {
          // ...the first node in the first group
          destinationNode = state.tabbableGroups[0].firstTabbableNode;
        }
      } else if (e.shiftKey) {
        // REVERSE
        var startOfGroupIndex = findIndex(state.tabbableGroups, function (_ref2) {
          var firstTabbableNode = _ref2.firstTabbableNode;
          return e.target === firstTabbableNode;
        });

        if (startOfGroupIndex >= 0) {
          var destinationGroupIndex = startOfGroupIndex === 0 ? state.tabbableGroups.length - 1 : startOfGroupIndex - 1;
          var destinationGroup = state.tabbableGroups[destinationGroupIndex];
          destinationNode = destinationGroup.lastTabbableNode;
        }
      } else {
        // FORWARD
        var lastOfGroupIndex = findIndex(state.tabbableGroups, function (_ref3) {
          var lastTabbableNode = _ref3.lastTabbableNode;
          return e.target === lastTabbableNode;
        });

        if (lastOfGroupIndex >= 0) {
          var _destinationGroupIndex = lastOfGroupIndex === state.tabbableGroups.length - 1 ? 0 : lastOfGroupIndex + 1;

          var _destinationGroup = state.tabbableGroups[_destinationGroupIndex];
          destinationNode = _destinationGroup.firstTabbableNode;
        }
      }
    } else {
      destinationNode = getNodeForOption('fallbackFocus');
    }

    if (destinationNode) {
      e.preventDefault();
      tryFocus(destinationNode);
    }
  };

  var checkKey = function checkKey(e) {
    if (config.escapeDeactivates !== false && isEscapeEvent(e)) {
      e.preventDefault();
      trap.deactivate();
      return;
    }

    if (isTabEvent(e)) {
      checkTab(e);
      return;
    }
  };

  var checkClick = function checkClick(e) {
    if (valueOrHandler(config.clickOutsideDeactivates, e)) {
      return;
    }

    if (containersContain(e.target)) {
      return;
    }

    if (valueOrHandler(config.allowOutsideClick, e)) {
      return;
    }

    e.preventDefault();
    e.stopImmediatePropagation();
  }; //
  // EVENT LISTENERS
  //


  var addListeners = function addListeners() {
    if (!state.active) {
      return;
    } // There can be only one listening focus trap at a time


    activeFocusTraps.activateTrap(trap); // Delay ensures that the focused element doesn't capture the event
    // that caused the focus trap activation.

    activeFocusDelay = config.delayInitialFocus ? delay(function () {
      tryFocus(getInitialFocusNode());
    }) : tryFocus(getInitialFocusNode());
    doc.addEventListener('focusin', checkFocusIn, true);
    doc.addEventListener('mousedown', checkPointerDown, {
      capture: true,
      passive: false
    });
    doc.addEventListener('touchstart', checkPointerDown, {
      capture: true,
      passive: false
    });
    doc.addEventListener('click', checkClick, {
      capture: true,
      passive: false
    });
    doc.addEventListener('keydown', checkKey, {
      capture: true,
      passive: false
    });
    return trap;
  };

  var removeListeners = function removeListeners() {
    if (!state.active) {
      return;
    }

    doc.removeEventListener('focusin', checkFocusIn, true);
    doc.removeEventListener('mousedown', checkPointerDown, true);
    doc.removeEventListener('touchstart', checkPointerDown, true);
    doc.removeEventListener('click', checkClick, true);
    doc.removeEventListener('keydown', checkKey, true);
    return trap;
  }; //
  // TRAP DEFINITION
  //


  trap = {
    activate: function activate(activateOptions) {
      if (state.active) {
        return this;
      }

      updateTabbableNodes();
      state.active = true;
      state.paused = false;
      state.nodeFocusedBeforeActivation = doc.activeElement;
      var onActivate = activateOptions && activateOptions.onActivate ? activateOptions.onActivate : config.onActivate;

      if (onActivate) {
        onActivate();
      }

      addListeners();
      return this;
    },
    deactivate: function deactivate(deactivateOptions) {
      if (!state.active) {
        return this;
      }

      clearTimeout(activeFocusDelay);
      removeListeners();
      state.active = false;
      state.paused = false;
      activeFocusTraps.deactivateTrap(trap);
      var onDeactivate = deactivateOptions && deactivateOptions.onDeactivate !== undefined ? deactivateOptions.onDeactivate : config.onDeactivate;

      if (onDeactivate) {
        onDeactivate();
      }

      var returnFocus = deactivateOptions && deactivateOptions.returnFocus !== undefined ? deactivateOptions.returnFocus : config.returnFocusOnDeactivate;

      if (returnFocus) {
        delay(function () {
          tryFocus(getReturnFocusNode(state.nodeFocusedBeforeActivation));
        });
      }

      return this;
    },
    pause: function pause() {
      if (state.paused || !state.active) {
        return this;
      }

      state.paused = true;
      removeListeners();
      return this;
    },
    unpause: function unpause() {
      if (!state.paused || !state.active) {
        return this;
      }

      state.paused = false;
      updateTabbableNodes();
      addListeners();
      return this;
    },
    updateContainerElements: function updateContainerElements(containerElements) {
      var elementsAsArray = [].concat(containerElements).filter(Boolean);
      state.containers = elementsAsArray.map(function (element) {
        return typeof element === 'string' ? doc.querySelector(element) : element;
      });

      if (state.active) {
        updateTabbableNodes();
      }

      return this;
    }
  }; // initialize container elements

  trap.updateContainerElements(elements);
  return trap;
};

var focusTrap_esm = /*#__PURE__*/Object.freeze({
  __proto__: null,
  createFocusTrap: createFocusTrap
});

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 _createSuperInternal() {
    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 createFocusTrap$1 = focusTrap_esm.createFocusTrap; // TODO: These issues are related to older React features which we'll likely need
//  to fix in order to move the code forward to the next major version of React.
//  @see https://github.com/davidtheclark/focus-trap-react/issues/77

/* eslint-disable react/no-find-dom-node */

var FocusTrap = /*#__PURE__*/function (_React$Component) {
  _inherits(FocusTrap, _React$Component);

  var _super = _createSuper(FocusTrap);

  function FocusTrap(props) {
    var _this;

    _classCallCheck(this, FocusTrap);

    _this = _super.call(this, props); // We need to hijack the returnFocusOnDeactivate option,
    // because React can move focus into the element before we arrived at
    // this lifecycle hook (e.g. with autoFocus inputs). So the component
    // captures the previouslyFocusedElement in componentWillMount,
    // then (optionally) returns focus to it in componentWillUnmount.

    _this.tailoredFocusTrapOptions = {
      returnFocusOnDeactivate: false
    }; // because of the above, we maintain our own flag for this option, and
    //  default it to `true` because that's focus-trap's default

    _this.returnFocusOnDeactivate = true;
    var focusTrapOptions = props.focusTrapOptions;

    for (var optionName in focusTrapOptions) {
      if (!Object.prototype.hasOwnProperty.call(focusTrapOptions, optionName)) {
        continue;
      }

      if (optionName === 'returnFocusOnDeactivate') {
        _this.returnFocusOnDeactivate = !!focusTrapOptions[optionName];
        continue;
      }

      _this.tailoredFocusTrapOptions[optionName] = focusTrapOptions[optionName];
    } // elements from which to create the focus trap on mount; if a child is used
    //  instead of the `containerElements` prop, we'll get the child's related
    //  element when the trap renders and then is declared 'mounted'


    _this.focusTrapElements = props.containerElements || []; // now we remember what the currently focused element is, not relying on focus-trap

    _this.updatePreviousElement();

    return _this;
  }
  /** Update the previously focused element with the currently focused element. */


  _createClass(FocusTrap, [{
    key: "updatePreviousElement",
    value: function updatePreviousElement() {
      if (typeof document !== 'undefined') {
        this.previouslyFocusedElement = document.activeElement;
      }
    }
    /** Returns focus to the element that had focus when the trap was activated. */

  }, {
    key: "returnFocus",
    value: function returnFocus() {
      if (this.previouslyFocusedElement && this.previouslyFocusedElement.focus) {
        this.previouslyFocusedElement.focus();
      }
    }
  }, {
    key: "setupFocusTrap",
    value: function setupFocusTrap() {
      if (!this.focusTrap) {
        var focusTrapElementDOMNodes = this.focusTrapElements.map( // NOTE: `findDOMNode()` does not support CSS selectors; it'll just return
        //  a new text node with the text wrapped in it instead of treating the
        //  string as a selector and resolving it to a node in the DOM
        ReactDOM.findDOMNode);
        var nodesExist = focusTrapElementDOMNodes.some(Boolean);

        if (nodesExist) {
          // eslint-disable-next-line react/prop-types -- _createFocusTrap is an internal prop
          this.focusTrap = this.props._createFocusTrap(focusTrapElementDOMNodes, this.tailoredFocusTrapOptions);

          if (this.props.active) {
            this.focusTrap.activate();
          }

          if (this.props.paused) {
            this.focusTrap.pause();
          }
        }
      }
    }
  }, {
    key: "componentDidMount",
    value: function componentDidMount() {
      this.setupFocusTrap();
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps) {
      if (this.focusTrap) {
        if (prevProps.containerElements !== this.props.containerElements) {
          this.focusTrap.updateContainerElements(this.props.containerElements);
        }

        if (prevProps.active && !this.props.active) {
          // NOTE: we never let the trap return the focus since we do that ourselves
          this.focusTrap.deactivate({
            returnFocus: false
          });

          if (this.returnFocusOnDeactivate) {
            this.returnFocus();
          }

          return; // un/pause does nothing on an inactive trap
        }

        if (!prevProps.active && this.props.active) {
          this.updatePreviousElement();
          this.focusTrap.activate();
        }

        if (prevProps.paused && !this.props.paused) {
          this.focusTrap.unpause();
        } else if (!prevProps.paused && this.props.paused) {
          this.focusTrap.pause();
        }
      } else if (prevProps.containerElements !== this.props.containerElements) {
        this.focusTrapElements = this.props.containerElements;
        this.setupFocusTrap();
      }
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      if (this.focusTrap) {
        // NOTE: we never let the trap return the focus since we do that ourselves
        this.focusTrap.deactivate({
          returnFocus: false
        });
      }

      if (this.returnFocusOnDeactivate) {
        this.returnFocus();
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;

      var child = this.props.children ? React__default.Children.only(this.props.children) : undefined;

      if (child) {
        var composedRefCallback = function composedRefCallback(element) {
          var containerElements = _this2.props.containerElements;

          if (child) {
            if (typeof child.ref === 'function') {
              child.ref(element);
            } else if (child.ref) {
              child.ref.current = element;
            }
          }

          _this2.focusTrapElements = containerElements ? containerElements : [element];
        };

        var childWithRef = React__default.cloneElement(child, {
          ref: composedRefCallback
        });
        return childWithRef;
      }

      return null;
    }
  }]);

  return FocusTrap;
}(React__default.Component); // support server-side rendering where `Element` will not be defined


var ElementType = typeof Element === 'undefined' ? Function : Element;
FocusTrap.propTypes = {
  active: propTypes.bool,
  paused: propTypes.bool,
  focusTrapOptions: propTypes.shape({
    onActivate: propTypes.func,
    onDeactivate: propTypes.func,
    initialFocus: propTypes.oneOfType([propTypes.instanceOf(ElementType), propTypes.string, propTypes.func]),
    fallbackFocus: propTypes.oneOfType([propTypes.instanceOf(ElementType), propTypes.string, propTypes.func]),
    escapeDeactivates: propTypes.bool,
    clickOutsideDeactivates: propTypes.oneOfType([propTypes.bool, propTypes.func]),
    returnFocusOnDeactivate: propTypes.bool,
    setReturnFocus: propTypes.oneOfType([propTypes.instanceOf(ElementType), propTypes.string, propTypes.func]),
    allowOutsideClick: propTypes.oneOfType([propTypes.bool, propTypes.func]),
    preventScroll: propTypes.bool
  }),
  containerElements: propTypes.arrayOf(propTypes.instanceOf(ElementType)),
  children: propTypes.oneOfType([propTypes.element, // React element
  propTypes.instanceOf(ElementType) // DOM element
  ]) // NOTE: _createFocusTrap is internal, for testing purposes only, so we don't
  //  specify it here. It's expected to be set to the function returned from
  //  require('focus-trap'), or one with a compatible interface.

};
FocusTrap.defaultProps = {
  active: true,
  paused: false,
  focusTrapOptions: {},
  _createFocusTrap: createFocusTrap$1
};
var focusTrapReact = FocusTrap;

var useMachine = function (machine, initial) {
    var _a = React__default.useState(initial), state = _a[0], setState = _a[1];
    var next = function () {
        setState(machine[state].next);
    };
    return [state, next];
};
var SectionedModal = function (_a) {
    var title = _a.title, onRequestClose = _a.onRequestClose, isOpen = _a.isOpen, children = _a.children, userProvidedId = _a.id, _b = _a.customCss, customCss = _b === void 0 ? '' : _b;
    var resolvedCss = useCustomCss(customCss);
    var id = useId(userProvidedId);
    var prevIsOpen = usePrevious(isOpen);
    var _c = useMachine({
        UNMOUNTED: { next: 'ENTERING' },
        ENTERING: { next: 'ENTERED' },
        ENTERED: { next: 'EXITING' },
        EXITING: { next: 'UNMOUNTED' },
    }, 'UNMOUNTED'), state = _c[0], next = _c[1];
    var handleAnimationEnd = useCallback(function () {
        next();
        if (state === 'EXITING') {
            onRequestClose();
        }
    }, [next, onRequestClose, state]);
    var escFunction = useCallback(function (event) {
        if (event.keyCode === 27) {
            handleAnimationEnd();
        }
    }, [handleAnimationEnd]);
    React__default.useEffect(function () {
        if (!prevIsOpen && isOpen) {
            next();
        }
    }, [prevIsOpen, isOpen, next]);
    React__default.useEffect(function () {
        document.addEventListener('keydown', escFunction, false);
        return function () {
            document.removeEventListener('keydown', escFunction, false);
        };
    }, [escFunction]);
    var getAnimation = function () {
        if (state === 'EXITING') {
            return 'fadeDown';
        }
        else {
            return 'fadeUp';
        }
    };
    if (state === 'UNMOUNTED') {
        return null;
    }
    return (jsxs(ModalPortal, __assign({ isOpened: isOpen }, { children: [jsx(StyledModalOverlay, { animation: state === 'EXITING' ? 'fadeDown' : 'fadeUp' }, void 0),
            jsx(focusTrapReact, { children: jsx(StyledModalWrapper, __assign({ "aria-modal": true, role: "dialog", "aria-label": title, animation: getAnimation(), onAnimationEnd: handleAnimationEnd, id: id, css: resolvedCss }, { children: React__default.Children.map(children, function (child, index) {
                        if (index === 0) {
                            return React__default.cloneElement(child, {
                                closeButton: true,
                                next: next,
                            });
                        }
                        else {
                            return child;
                        }
                    }) }), void 0) }, void 0)] }), void 0));
};
var ModalSection = function (_a) {
    var closeButton = _a.closeButton, next = _a.next, children = _a.children, style = _a.style, props = __rest(_a, ["closeButton", "next", "children", "style"]);
    return (jsxs(StyledModal, __assign({}, props, { style: style }, { children: [closeButton && (jsx(StyledModalHeader, { children: jsx(IconButton, { icon: jsx(Cross, {}, void 0), label: "close", onClick: next, customCss: "font-size: 0.8em;" }, void 0) }, void 0)), children] }), void 0));
};
var ModalPortal = function (_a) {
    var children = _a.children, isOpened = _a.isOpened, props = __rest(_a, ["children", "isOpened"]);
    if (!isOpened)
        return null;
    return jsx(lib.Portal, __assign({}, props, { children: children }), void 0);
};
var StyledModalOverlay = styled('div')(templateObject_2 || (templateObject_2 = __makeTemplateObject(["\n  position: fixed;\n  top: 0;\n  left: 0;\n  z-index: 1040;\n  width: 100vw;\n  height: 100vh;\n  background: black;\n  filter: blur(20px);\n  -webkit-filter: blur(20px);\n  opacity: 0.6;\n  animation: ", ";\n"], ["\n  position: fixed;\n  top: 0;\n  left: 0;\n  z-index: 1040;\n  width: 100vw;\n  height: 100vh;\n  background: black;\n  filter: blur(20px);\n  -webkit-filter: blur(20px);\n  opacity: 0.6;\n  animation: ",
    ";\n"])), function (_a) {
    var animation = _a.animation;
    return css(templateObject_1 || (templateObject_1 = __makeTemplateObject(["\n      ", " 600ms\n    "], ["\n      ", " 600ms\n    "])), animations[animation].overlay);
});
var StyledModalWrapper = styled('div')(templateObject_4 || (templateObject_4 = __makeTemplateObject(["\n  position: fixed;\n  top: 0;\n  left: 0;\n  z-index: 1050;\n  width: 100%;\n  height: 100%;\n  overflow-x: hidden;\n  overflow-y: auto;\n  outline: 0;\n  animation: ", ";\n"], ["\n  position: fixed;\n  top: 0;\n  left: 0;\n  z-index: 1050;\n  width: 100%;\n  height: 100%;\n  overflow-x: hidden;\n  overflow-y: auto;\n  outline: 0;\n  animation: ",
    ";\n"])), function (_a) {
    var animation = _a.animation;
    return css(templateObject_3 || (templateObject_3 = __makeTemplateObject(["\n      ", " ", " 600ms\n    "], ["\n      ", " ", " 600ms\n    "])), animations[animation].animation, animations[animation].timing);
});
var StyledModal = styled('div')(templateObject_5 || (templateObject_5 = __makeTemplateObject(["\n  z-index: 100;\n  background: white;\n  position: relative;\n  margin: 1rem auto;\n  border-radius: 15px;\n  box-shadow: 0px 23px 40px #00000060;\n  max-width: 500px;\n  padding: 0.4rem;\n"], ["\n  z-index: 100;\n  background: white;\n  position: relative;\n  margin: 1rem auto;\n  border-radius: 15px;\n  box-shadow: 0px 23px 40px #00000060;\n  max-width: 500px;\n  padding: 0.4rem;\n"])));
var StyledModalHeader = styled('div')(templateObject_6 || (templateObject_6 = __makeTemplateObject(["\n  display: flex;\n  justify-content: flex-end;\n"], ["\n  display: flex;\n  justify-content: flex-end;\n"])));
var fadeUp = keyframes(templateObject_7 || (templateObject_7 = __makeTemplateObject(["\n  0% {\n    transform: scale(1) translate(0%, 80%);\n    opacity: 0;\n  }\n  30% {\n    opacity: 0.75;\n  }\n  100% {\n    transform: scale(1) translate(0px, 0px);\n    opacity: 1;\n  }\n"], ["\n  0% {\n    transform: scale(1) translate(0%, 80%);\n    opacity: 0;\n  }\n  30% {\n    opacity: 0.75;\n  }\n  100% {\n    transform: scale(1) translate(0px, 0px);\n    opacity: 1;\n  }\n"])));
var fadeDown = keyframes(templateObject_8 || (templateObject_8 = __makeTemplateObject(["\n0% {\n  transform: scale(1) translate(0px, 0px);\n  opacity: 1;\n}\n50% {\n  opacity: 0.75;\n}\n100% {\n  transform: scale(1) translate(0%, 40%);\n  opacity: 0;\n}\n"], ["\n0% {\n  transform: scale(1) translate(0px, 0px);\n  opacity: 1;\n}\n50% {\n  opacity: 0.75;\n}\n100% {\n  transform: scale(1) translate(0%, 40%);\n  opacity: 0;\n}\n"])));
var overlayUp = keyframes(templateObject_9 || (templateObject_9 = __makeTemplateObject([" \n0% {\n  opacity: 0;\n}\n100% {\n  opacity: 0.6;\n}\n"], [" \n0% {\n  opacity: 0;\n}\n100% {\n  opacity: 0.6;\n}\n"])));
var overlayDown = keyframes(templateObject_10 || (templateObject_10 = __makeTemplateObject(["\n0% {\n  opacity: 0.2;\n}\n100% {\n  opacity: 0;\n}\n"], ["\n0% {\n  opacity: 0.2;\n}\n100% {\n  opacity: 0;\n}\n"])));
var animations = {
    fadeUp: {
        animation: fadeUp,
        overlay: overlayUp,
        timing: 'cubic-bezier(0, 0.92, 0.22, 1)',
    },
    fadeDown: {
        animation: fadeDown,
        overlay: overlayDown,
        timing: 'cubic-bezier(0.1, 0.81, 0.43, 5.93)',
    },
};
var templateObject_1, templateObject_2, templateObject_3, templateObject_4, templateObject_5, templateObject_6, templateObject_7, templateObject_8, templateObject_9, templateObject_10;

export { ModalPortal, ModalSection, SectionedModal };
//# sourceMappingURL=SectionedModal.js.map
