focus-trap.esm.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  1. /*!
  2. * focus-trap 7.0.0
  3. * @license MIT, https://github.com/focus-trap/focus-trap/blob/master/LICENSE
  4. */
  5. import { tabbable, focusable, isTabbable, isFocusable } from 'tabbable';
  6. function ownKeys(object, enumerableOnly) {
  7. var keys = Object.keys(object);
  8. if (Object.getOwnPropertySymbols) {
  9. var symbols = Object.getOwnPropertySymbols(object);
  10. enumerableOnly && (symbols = symbols.filter(function (sym) {
  11. return Object.getOwnPropertyDescriptor(object, sym).enumerable;
  12. })), keys.push.apply(keys, symbols);
  13. }
  14. return keys;
  15. }
  16. function _objectSpread2(target) {
  17. for (var i = 1; i < arguments.length; i++) {
  18. var source = null != arguments[i] ? arguments[i] : {};
  19. i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {
  20. _defineProperty(target, key, source[key]);
  21. }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {
  22. Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
  23. });
  24. }
  25. return target;
  26. }
  27. function _defineProperty(obj, key, value) {
  28. if (key in obj) {
  29. Object.defineProperty(obj, key, {
  30. value: value,
  31. enumerable: true,
  32. configurable: true,
  33. writable: true
  34. });
  35. } else {
  36. obj[key] = value;
  37. }
  38. return obj;
  39. }
  40. var activeFocusTraps = function () {
  41. var trapQueue = [];
  42. return {
  43. activateTrap: function activateTrap(trap) {
  44. if (trapQueue.length > 0) {
  45. var activeTrap = trapQueue[trapQueue.length - 1];
  46. if (activeTrap !== trap) {
  47. activeTrap.pause();
  48. }
  49. }
  50. var trapIndex = trapQueue.indexOf(trap);
  51. if (trapIndex === -1) {
  52. trapQueue.push(trap);
  53. } else {
  54. // move this existing trap to the front of the queue
  55. trapQueue.splice(trapIndex, 1);
  56. trapQueue.push(trap);
  57. }
  58. },
  59. deactivateTrap: function deactivateTrap(trap) {
  60. var trapIndex = trapQueue.indexOf(trap);
  61. if (trapIndex !== -1) {
  62. trapQueue.splice(trapIndex, 1);
  63. }
  64. if (trapQueue.length > 0) {
  65. trapQueue[trapQueue.length - 1].unpause();
  66. }
  67. }
  68. };
  69. }();
  70. var isSelectableInput = function isSelectableInput(node) {
  71. return node.tagName && node.tagName.toLowerCase() === 'input' && typeof node.select === 'function';
  72. };
  73. var isEscapeEvent = function isEscapeEvent(e) {
  74. return e.key === 'Escape' || e.key === 'Esc' || e.keyCode === 27;
  75. };
  76. var isTabEvent = function isTabEvent(e) {
  77. return e.key === 'Tab' || e.keyCode === 9;
  78. };
  79. var delay = function delay(fn) {
  80. return setTimeout(fn, 0);
  81. }; // Array.find/findIndex() are not supported on IE; this replicates enough
  82. // of Array.findIndex() for our needs
  83. var findIndex = function findIndex(arr, fn) {
  84. var idx = -1;
  85. arr.every(function (value, i) {
  86. if (fn(value)) {
  87. idx = i;
  88. return false; // break
  89. }
  90. return true; // next
  91. });
  92. return idx;
  93. };
  94. /**
  95. * Get an option's value when it could be a plain value, or a handler that provides
  96. * the value.
  97. * @param {*} value Option's value to check.
  98. * @param {...*} [params] Any parameters to pass to the handler, if `value` is a function.
  99. * @returns {*} The `value`, or the handler's returned value.
  100. */
  101. var valueOrHandler = function valueOrHandler(value) {
  102. for (var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  103. params[_key - 1] = arguments[_key];
  104. }
  105. return typeof value === 'function' ? value.apply(void 0, params) : value;
  106. };
  107. var getActualTarget = function getActualTarget(event) {
  108. // NOTE: If the trap is _inside_ a shadow DOM, event.target will always be the
  109. // shadow host. However, event.target.composedPath() will be an array of
  110. // nodes "clicked" from inner-most (the actual element inside the shadow) to
  111. // outer-most (the host HTML document). If we have access to composedPath(),
  112. // then use its first element; otherwise, fall back to event.target (and
  113. // this only works for an _open_ shadow DOM; otherwise,
  114. // composedPath()[0] === event.target always).
  115. return event.target.shadowRoot && typeof event.composedPath === 'function' ? event.composedPath()[0] : event.target;
  116. };
  117. var createFocusTrap = function createFocusTrap(elements, userOptions) {
  118. // SSR: a live trap shouldn't be created in this type of environment so this
  119. // should be safe code to execute if the `document` option isn't specified
  120. var doc = (userOptions === null || userOptions === void 0 ? void 0 : userOptions.document) || document;
  121. var config = _objectSpread2({
  122. returnFocusOnDeactivate: true,
  123. escapeDeactivates: true,
  124. delayInitialFocus: true
  125. }, userOptions);
  126. var state = {
  127. // containers given to createFocusTrap()
  128. // @type {Array<HTMLElement>}
  129. containers: [],
  130. // list of objects identifying tabbable nodes in `containers` in the trap
  131. // NOTE: it's possible that a group has no tabbable nodes if nodes get removed while the trap
  132. // is active, but the trap should never get to a state where there isn't at least one group
  133. // with at least one tabbable node in it (that would lead to an error condition that would
  134. // result in an error being thrown)
  135. // @type {Array<{
  136. // container: HTMLElement,
  137. // tabbableNodes: Array<HTMLElement>, // empty if none
  138. // focusableNodes: Array<HTMLElement>, // empty if none
  139. // firstTabbableNode: HTMLElement|null,
  140. // lastTabbableNode: HTMLElement|null,
  141. // nextTabbableNode: (node: HTMLElement, forward: boolean) => HTMLElement|undefined
  142. // }>}
  143. containerGroups: [],
  144. // same order/length as `containers` list
  145. // references to objects in `containerGroups`, but only those that actually have
  146. // tabbable nodes in them
  147. // NOTE: same order as `containers` and `containerGroups`, but __not necessarily__
  148. // the same length
  149. tabbableGroups: [],
  150. nodeFocusedBeforeActivation: null,
  151. mostRecentlyFocusedNode: null,
  152. active: false,
  153. paused: false,
  154. // timer ID for when delayInitialFocus is true and initial focus in this trap
  155. // has been delayed during activation
  156. delayInitialFocusTimer: undefined
  157. };
  158. 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
  159. /**
  160. * Gets a configuration option value.
  161. * @param {Object|undefined} configOverrideOptions If true, and option is defined in this set,
  162. * value will be taken from this object. Otherwise, value will be taken from base configuration.
  163. * @param {string} optionName Name of the option whose value is sought.
  164. * @param {string|undefined} [configOptionName] Name of option to use __instead of__ `optionName`
  165. * IIF `configOverrideOptions` is not defined. Otherwise, `optionName` is used.
  166. */
  167. var getOption = function getOption(configOverrideOptions, optionName, configOptionName) {
  168. return configOverrideOptions && configOverrideOptions[optionName] !== undefined ? configOverrideOptions[optionName] : config[configOptionName || optionName];
  169. };
  170. /**
  171. * Finds the index of the container that contains the element.
  172. * @param {HTMLElement} element
  173. * @returns {number} Index of the container in either `state.containers` or
  174. * `state.containerGroups` (the order/length of these lists are the same); -1
  175. * if the element isn't found.
  176. */
  177. var findContainerIndex = function findContainerIndex(element) {
  178. // NOTE: search `containerGroups` because it's possible a group contains no tabbable
  179. // nodes, but still contains focusable nodes (e.g. if they all have `tabindex=-1`)
  180. // and we still need to find the element in there
  181. return state.containerGroups.findIndex(function (_ref) {
  182. var container = _ref.container,
  183. tabbableNodes = _ref.tabbableNodes;
  184. return container.contains(element) || // fall back to explicit tabbable search which will take into consideration any
  185. // web components if the `tabbableOptions.getShadowRoot` option was used for
  186. // the trap, enabling shadow DOM support in tabbable (`Node.contains()` doesn't
  187. // look inside web components even if open)
  188. tabbableNodes.find(function (node) {
  189. return node === element;
  190. });
  191. });
  192. };
  193. /**
  194. * Gets the node for the given option, which is expected to be an option that
  195. * can be either a DOM node, a string that is a selector to get a node, `false`
  196. * (if a node is explicitly NOT given), or a function that returns any of these
  197. * values.
  198. * @param {string} optionName
  199. * @returns {undefined | false | HTMLElement | SVGElement} Returns
  200. * `undefined` if the option is not specified; `false` if the option
  201. * resolved to `false` (node explicitly not given); otherwise, the resolved
  202. * DOM node.
  203. * @throws {Error} If the option is set, not `false`, and is not, or does not
  204. * resolve to a node.
  205. */
  206. var getNodeForOption = function getNodeForOption(optionName) {
  207. var optionValue = config[optionName];
  208. if (typeof optionValue === 'function') {
  209. for (var _len2 = arguments.length, params = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  210. params[_key2 - 1] = arguments[_key2];
  211. }
  212. optionValue = optionValue.apply(void 0, params);
  213. }
  214. if (optionValue === true) {
  215. optionValue = undefined; // use default value
  216. }
  217. if (!optionValue) {
  218. if (optionValue === undefined || optionValue === false) {
  219. return optionValue;
  220. } // else, empty string (invalid), null (invalid), 0 (invalid)
  221. throw new Error("`".concat(optionName, "` was specified but was not a node, or did not return a node"));
  222. }
  223. var node = optionValue; // could be HTMLElement, SVGElement, or non-empty string at this point
  224. if (typeof optionValue === 'string') {
  225. node = doc.querySelector(optionValue); // resolve to node, or null if fails
  226. if (!node) {
  227. throw new Error("`".concat(optionName, "` as selector refers to no known node"));
  228. }
  229. }
  230. return node;
  231. };
  232. var getInitialFocusNode = function getInitialFocusNode() {
  233. var node = getNodeForOption('initialFocus'); // false explicitly indicates we want no initialFocus at all
  234. if (node === false) {
  235. return false;
  236. }
  237. if (node === undefined) {
  238. // option not specified: use fallback options
  239. if (findContainerIndex(doc.activeElement) >= 0) {
  240. node = doc.activeElement;
  241. } else {
  242. var firstTabbableGroup = state.tabbableGroups[0];
  243. var firstTabbableNode = firstTabbableGroup && firstTabbableGroup.firstTabbableNode; // NOTE: `fallbackFocus` option function cannot return `false` (not supported)
  244. node = firstTabbableNode || getNodeForOption('fallbackFocus');
  245. }
  246. }
  247. if (!node) {
  248. throw new Error('Your focus-trap needs to have at least one focusable element');
  249. }
  250. return node;
  251. };
  252. var updateTabbableNodes = function updateTabbableNodes() {
  253. state.containerGroups = state.containers.map(function (container) {
  254. var tabbableNodes = tabbable(container, config.tabbableOptions); // NOTE: if we have tabbable nodes, we must have focusable nodes; focusable nodes
  255. // are a superset of tabbable nodes
  256. var focusableNodes = focusable(container, config.tabbableOptions);
  257. return {
  258. container: container,
  259. tabbableNodes: tabbableNodes,
  260. focusableNodes: focusableNodes,
  261. firstTabbableNode: tabbableNodes.length > 0 ? tabbableNodes[0] : null,
  262. lastTabbableNode: tabbableNodes.length > 0 ? tabbableNodes[tabbableNodes.length - 1] : null,
  263. /**
  264. * Finds the __tabbable__ node that follows the given node in the specified direction,
  265. * in this container, if any.
  266. * @param {HTMLElement} node
  267. * @param {boolean} [forward] True if going in forward tab order; false if going
  268. * in reverse.
  269. * @returns {HTMLElement|undefined} The next tabbable node, if any.
  270. */
  271. nextTabbableNode: function nextTabbableNode(node) {
  272. var forward = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  273. // NOTE: If tabindex is positive (in order to manipulate the tab order separate
  274. // from the DOM order), this __will not work__ because the list of focusableNodes,
  275. // while it contains tabbable nodes, does not sort its nodes in any order other
  276. // than DOM order, because it can't: Where would you place focusable (but not
  277. // tabbable) nodes in that order? They have no order, because they aren't tabbale...
  278. // Support for positive tabindex is already broken and hard to manage (possibly
  279. // not supportable, TBD), so this isn't going to make things worse than they
  280. // already are, and at least makes things better for the majority of cases where
  281. // tabindex is either 0/unset or negative.
  282. // FYI, positive tabindex issue: https://github.com/focus-trap/focus-trap/issues/375
  283. var nodeIdx = focusableNodes.findIndex(function (n) {
  284. return n === node;
  285. });
  286. if (nodeIdx < 0) {
  287. return undefined;
  288. }
  289. if (forward) {
  290. return focusableNodes.slice(nodeIdx + 1).find(function (n) {
  291. return isTabbable(n, config.tabbableOptions);
  292. });
  293. }
  294. return focusableNodes.slice(0, nodeIdx).reverse().find(function (n) {
  295. return isTabbable(n, config.tabbableOptions);
  296. });
  297. }
  298. };
  299. });
  300. state.tabbableGroups = state.containerGroups.filter(function (group) {
  301. return group.tabbableNodes.length > 0;
  302. }); // throw if no groups have tabbable nodes and we don't have a fallback focus node either
  303. if (state.tabbableGroups.length <= 0 && !getNodeForOption('fallbackFocus') // returning false not supported for this option
  304. ) {
  305. throw new Error('Your focus-trap must have at least one container with at least one tabbable node in it at all times');
  306. }
  307. };
  308. var tryFocus = function tryFocus(node) {
  309. if (node === false) {
  310. return;
  311. }
  312. if (node === doc.activeElement) {
  313. return;
  314. }
  315. if (!node || !node.focus) {
  316. tryFocus(getInitialFocusNode());
  317. return;
  318. }
  319. node.focus({
  320. preventScroll: !!config.preventScroll
  321. });
  322. state.mostRecentlyFocusedNode = node;
  323. if (isSelectableInput(node)) {
  324. node.select();
  325. }
  326. };
  327. var getReturnFocusNode = function getReturnFocusNode(previousActiveElement) {
  328. var node = getNodeForOption('setReturnFocus', previousActiveElement);
  329. return node ? node : node === false ? false : previousActiveElement;
  330. }; // This needs to be done on mousedown and touchstart instead of click
  331. // so that it precedes the focus event.
  332. var checkPointerDown = function checkPointerDown(e) {
  333. var target = getActualTarget(e);
  334. if (findContainerIndex(target) >= 0) {
  335. // allow the click since it ocurred inside the trap
  336. return;
  337. }
  338. if (valueOrHandler(config.clickOutsideDeactivates, e)) {
  339. // immediately deactivate the trap
  340. trap.deactivate({
  341. // if, on deactivation, we should return focus to the node originally-focused
  342. // when the trap was activated (or the configured `setReturnFocus` node),
  343. // then assume it's also OK to return focus to the outside node that was
  344. // just clicked, causing deactivation, as long as that node is focusable;
  345. // if it isn't focusable, then return focus to the original node focused
  346. // on activation (or the configured `setReturnFocus` node)
  347. // NOTE: by setting `returnFocus: false`, deactivate() will do nothing,
  348. // which will result in the outside click setting focus to the node
  349. // that was clicked, whether it's focusable or not; by setting
  350. // `returnFocus: true`, we'll attempt to re-focus the node originally-focused
  351. // on activation (or the configured `setReturnFocus` node)
  352. returnFocus: config.returnFocusOnDeactivate && !isFocusable(target, config.tabbableOptions)
  353. });
  354. return;
  355. } // This is needed for mobile devices.
  356. // (If we'll only let `click` events through,
  357. // then on mobile they will be blocked anyways if `touchstart` is blocked.)
  358. if (valueOrHandler(config.allowOutsideClick, e)) {
  359. // allow the click outside the trap to take place
  360. return;
  361. } // otherwise, prevent the click
  362. e.preventDefault();
  363. }; // In case focus escapes the trap for some strange reason, pull it back in.
  364. var checkFocusIn = function checkFocusIn(e) {
  365. var target = getActualTarget(e);
  366. var targetContained = findContainerIndex(target) >= 0; // In Firefox when you Tab out of an iframe the Document is briefly focused.
  367. if (targetContained || target instanceof Document) {
  368. if (targetContained) {
  369. state.mostRecentlyFocusedNode = target;
  370. }
  371. } else {
  372. // escaped! pull it back in to where it just left
  373. e.stopImmediatePropagation();
  374. tryFocus(state.mostRecentlyFocusedNode || getInitialFocusNode());
  375. }
  376. }; // Hijack Tab events on the first and last focusable nodes of the trap,
  377. // in order to prevent focus from escaping. If it escapes for even a
  378. // moment it can end up scrolling the page and causing confusion so we
  379. // kind of need to capture the action at the keydown phase.
  380. var checkTab = function checkTab(e) {
  381. var target = getActualTarget(e);
  382. updateTabbableNodes();
  383. var destinationNode = null;
  384. if (state.tabbableGroups.length > 0) {
  385. // make sure the target is actually contained in a group
  386. // NOTE: the target may also be the container itself if it's focusable
  387. // with tabIndex='-1' and was given initial focus
  388. var containerIndex = findContainerIndex(target);
  389. var containerGroup = containerIndex >= 0 ? state.containerGroups[containerIndex] : undefined;
  390. if (containerIndex < 0) {
  391. // target not found in any group: quite possible focus has escaped the trap,
  392. // so bring it back in to...
  393. if (e.shiftKey) {
  394. // ...the last node in the last group
  395. destinationNode = state.tabbableGroups[state.tabbableGroups.length - 1].lastTabbableNode;
  396. } else {
  397. // ...the first node in the first group
  398. destinationNode = state.tabbableGroups[0].firstTabbableNode;
  399. }
  400. } else if (e.shiftKey) {
  401. // REVERSE
  402. // is the target the first tabbable node in a group?
  403. var startOfGroupIndex = findIndex(state.tabbableGroups, function (_ref2) {
  404. var firstTabbableNode = _ref2.firstTabbableNode;
  405. return target === firstTabbableNode;
  406. });
  407. if (startOfGroupIndex < 0 && (containerGroup.container === target || isFocusable(target, config.tabbableOptions) && !isTabbable(target, config.tabbableOptions) && !containerGroup.nextTabbableNode(target, false))) {
  408. // an exception case where the target is either the container itself, or
  409. // a non-tabbable node that was given focus (i.e. tabindex is negative
  410. // and user clicked on it or node was programmatically given focus)
  411. // and is not followed by any other tabbable node, in which
  412. // case, we should handle shift+tab as if focus were on the container's
  413. // first tabbable node, and go to the last tabbable node of the LAST group
  414. startOfGroupIndex = containerIndex;
  415. }
  416. if (startOfGroupIndex >= 0) {
  417. // YES: then shift+tab should go to the last tabbable node in the
  418. // previous group (and wrap around to the last tabbable node of
  419. // the LAST group if it's the first tabbable node of the FIRST group)
  420. var destinationGroupIndex = startOfGroupIndex === 0 ? state.tabbableGroups.length - 1 : startOfGroupIndex - 1;
  421. var destinationGroup = state.tabbableGroups[destinationGroupIndex];
  422. destinationNode = destinationGroup.lastTabbableNode;
  423. }
  424. } else {
  425. // FORWARD
  426. // is the target the last tabbable node in a group?
  427. var lastOfGroupIndex = findIndex(state.tabbableGroups, function (_ref3) {
  428. var lastTabbableNode = _ref3.lastTabbableNode;
  429. return target === lastTabbableNode;
  430. });
  431. if (lastOfGroupIndex < 0 && (containerGroup.container === target || isFocusable(target, config.tabbableOptions) && !isTabbable(target, config.tabbableOptions) && !containerGroup.nextTabbableNode(target))) {
  432. // an exception case where the target is the container itself, or
  433. // a non-tabbable node that was given focus (i.e. tabindex is negative
  434. // and user clicked on it or node was programmatically given focus)
  435. // and is not followed by any other tabbable node, in which
  436. // case, we should handle tab as if focus were on the container's
  437. // last tabbable node, and go to the first tabbable node of the FIRST group
  438. lastOfGroupIndex = containerIndex;
  439. }
  440. if (lastOfGroupIndex >= 0) {
  441. // YES: then tab should go to the first tabbable node in the next
  442. // group (and wrap around to the first tabbable node of the FIRST
  443. // group if it's the last tabbable node of the LAST group)
  444. var _destinationGroupIndex = lastOfGroupIndex === state.tabbableGroups.length - 1 ? 0 : lastOfGroupIndex + 1;
  445. var _destinationGroup = state.tabbableGroups[_destinationGroupIndex];
  446. destinationNode = _destinationGroup.firstTabbableNode;
  447. }
  448. }
  449. } else {
  450. // NOTE: the fallbackFocus option does not support returning false to opt-out
  451. destinationNode = getNodeForOption('fallbackFocus');
  452. }
  453. if (destinationNode) {
  454. e.preventDefault();
  455. tryFocus(destinationNode);
  456. } // else, let the browser take care of [shift+]tab and move the focus
  457. };
  458. var checkKey = function checkKey(e) {
  459. if (isEscapeEvent(e) && valueOrHandler(config.escapeDeactivates, e) !== false) {
  460. e.preventDefault();
  461. trap.deactivate();
  462. return;
  463. }
  464. if (isTabEvent(e)) {
  465. checkTab(e);
  466. return;
  467. }
  468. };
  469. var checkClick = function checkClick(e) {
  470. var target = getActualTarget(e);
  471. if (findContainerIndex(target) >= 0) {
  472. return;
  473. }
  474. if (valueOrHandler(config.clickOutsideDeactivates, e)) {
  475. return;
  476. }
  477. if (valueOrHandler(config.allowOutsideClick, e)) {
  478. return;
  479. }
  480. e.preventDefault();
  481. e.stopImmediatePropagation();
  482. }; //
  483. // EVENT LISTENERS
  484. //
  485. var addListeners = function addListeners() {
  486. if (!state.active) {
  487. return;
  488. } // There can be only one listening focus trap at a time
  489. activeFocusTraps.activateTrap(trap); // Delay ensures that the focused element doesn't capture the event
  490. // that caused the focus trap activation.
  491. state.delayInitialFocusTimer = config.delayInitialFocus ? delay(function () {
  492. tryFocus(getInitialFocusNode());
  493. }) : tryFocus(getInitialFocusNode());
  494. doc.addEventListener('focusin', checkFocusIn, true);
  495. doc.addEventListener('mousedown', checkPointerDown, {
  496. capture: true,
  497. passive: false
  498. });
  499. doc.addEventListener('touchstart', checkPointerDown, {
  500. capture: true,
  501. passive: false
  502. });
  503. doc.addEventListener('click', checkClick, {
  504. capture: true,
  505. passive: false
  506. });
  507. doc.addEventListener('keydown', checkKey, {
  508. capture: true,
  509. passive: false
  510. });
  511. return trap;
  512. };
  513. var removeListeners = function removeListeners() {
  514. if (!state.active) {
  515. return;
  516. }
  517. doc.removeEventListener('focusin', checkFocusIn, true);
  518. doc.removeEventListener('mousedown', checkPointerDown, true);
  519. doc.removeEventListener('touchstart', checkPointerDown, true);
  520. doc.removeEventListener('click', checkClick, true);
  521. doc.removeEventListener('keydown', checkKey, true);
  522. return trap;
  523. }; //
  524. // TRAP DEFINITION
  525. //
  526. trap = {
  527. get active() {
  528. return state.active;
  529. },
  530. get paused() {
  531. return state.paused;
  532. },
  533. activate: function activate(activateOptions) {
  534. if (state.active) {
  535. return this;
  536. }
  537. var onActivate = getOption(activateOptions, 'onActivate');
  538. var onPostActivate = getOption(activateOptions, 'onPostActivate');
  539. var checkCanFocusTrap = getOption(activateOptions, 'checkCanFocusTrap');
  540. if (!checkCanFocusTrap) {
  541. updateTabbableNodes();
  542. }
  543. state.active = true;
  544. state.paused = false;
  545. state.nodeFocusedBeforeActivation = doc.activeElement;
  546. if (onActivate) {
  547. onActivate();
  548. }
  549. var finishActivation = function finishActivation() {
  550. if (checkCanFocusTrap) {
  551. updateTabbableNodes();
  552. }
  553. addListeners();
  554. if (onPostActivate) {
  555. onPostActivate();
  556. }
  557. };
  558. if (checkCanFocusTrap) {
  559. checkCanFocusTrap(state.containers.concat()).then(finishActivation, finishActivation);
  560. return this;
  561. }
  562. finishActivation();
  563. return this;
  564. },
  565. deactivate: function deactivate(deactivateOptions) {
  566. if (!state.active) {
  567. return this;
  568. }
  569. var options = _objectSpread2({
  570. onDeactivate: config.onDeactivate,
  571. onPostDeactivate: config.onPostDeactivate,
  572. checkCanReturnFocus: config.checkCanReturnFocus
  573. }, deactivateOptions);
  574. clearTimeout(state.delayInitialFocusTimer); // noop if undefined
  575. state.delayInitialFocusTimer = undefined;
  576. removeListeners();
  577. state.active = false;
  578. state.paused = false;
  579. activeFocusTraps.deactivateTrap(trap);
  580. var onDeactivate = getOption(options, 'onDeactivate');
  581. var onPostDeactivate = getOption(options, 'onPostDeactivate');
  582. var checkCanReturnFocus = getOption(options, 'checkCanReturnFocus');
  583. var returnFocus = getOption(options, 'returnFocus', 'returnFocusOnDeactivate');
  584. if (onDeactivate) {
  585. onDeactivate();
  586. }
  587. var finishDeactivation = function finishDeactivation() {
  588. delay(function () {
  589. if (returnFocus) {
  590. tryFocus(getReturnFocusNode(state.nodeFocusedBeforeActivation));
  591. }
  592. if (onPostDeactivate) {
  593. onPostDeactivate();
  594. }
  595. });
  596. };
  597. if (returnFocus && checkCanReturnFocus) {
  598. checkCanReturnFocus(getReturnFocusNode(state.nodeFocusedBeforeActivation)).then(finishDeactivation, finishDeactivation);
  599. return this;
  600. }
  601. finishDeactivation();
  602. return this;
  603. },
  604. pause: function pause() {
  605. if (state.paused || !state.active) {
  606. return this;
  607. }
  608. state.paused = true;
  609. removeListeners();
  610. return this;
  611. },
  612. unpause: function unpause() {
  613. if (!state.paused || !state.active) {
  614. return this;
  615. }
  616. state.paused = false;
  617. updateTabbableNodes();
  618. addListeners();
  619. return this;
  620. },
  621. updateContainerElements: function updateContainerElements(containerElements) {
  622. var elementsAsArray = [].concat(containerElements).filter(Boolean);
  623. state.containers = elementsAsArray.map(function (element) {
  624. return typeof element === 'string' ? doc.querySelector(element) : element;
  625. });
  626. if (state.active) {
  627. updateTabbableNodes();
  628. }
  629. return this;
  630. }
  631. }; // initialize container elements
  632. trap.updateContainerElements(elements);
  633. return trap;
  634. };
  635. export { createFocusTrap };
  636. //# sourceMappingURL=focus-trap.esm.js.map