index.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var vue = require('vue');
  4. require('../../utils/index.js');
  5. require('../../constants/index.js');
  6. var aria = require('../../constants/aria.js');
  7. var aria$1 = require('../../utils/dom/aria.js');
  8. const FOCUSABLE_CHILDREN = "_trap-focus-children";
  9. const TRAP_FOCUS_HANDLER = "_trap-focus-handler";
  10. const FOCUS_STACK = [];
  11. const FOCUS_HANDLER = (e) => {
  12. var _a;
  13. if (FOCUS_STACK.length === 0)
  14. return;
  15. const focusableElement = FOCUS_STACK[FOCUS_STACK.length - 1][FOCUSABLE_CHILDREN];
  16. if (focusableElement.length > 0 && e.code === aria.EVENT_CODE.tab) {
  17. if (focusableElement.length === 1) {
  18. e.preventDefault();
  19. if (document.activeElement !== focusableElement[0]) {
  20. focusableElement[0].focus();
  21. }
  22. return;
  23. }
  24. const goingBackward = e.shiftKey;
  25. const isFirst = e.target === focusableElement[0];
  26. const isLast = e.target === focusableElement[focusableElement.length - 1];
  27. if (isFirst && goingBackward) {
  28. e.preventDefault();
  29. focusableElement[focusableElement.length - 1].focus();
  30. }
  31. if (isLast && !goingBackward) {
  32. e.preventDefault();
  33. focusableElement[0].focus();
  34. }
  35. if (process.env.NODE_ENV === "test") {
  36. const index = focusableElement.indexOf(e.target);
  37. if (index !== -1) {
  38. (_a = focusableElement[goingBackward ? index - 1 : index + 1]) == null ? void 0 : _a.focus();
  39. }
  40. }
  41. }
  42. };
  43. const TrapFocus = {
  44. beforeMount(el) {
  45. el[FOCUSABLE_CHILDREN] = aria$1.obtainAllFocusableElements(el);
  46. FOCUS_STACK.push(el);
  47. if (FOCUS_STACK.length <= 1) {
  48. document.addEventListener("keydown", FOCUS_HANDLER);
  49. }
  50. },
  51. updated(el) {
  52. vue.nextTick(() => {
  53. el[FOCUSABLE_CHILDREN] = aria$1.obtainAllFocusableElements(el);
  54. });
  55. },
  56. unmounted() {
  57. FOCUS_STACK.shift();
  58. if (FOCUS_STACK.length === 0) {
  59. document.removeEventListener("keydown", FOCUS_HANDLER);
  60. }
  61. }
  62. };
  63. exports.FOCUSABLE_CHILDREN = FOCUSABLE_CHILDREN;
  64. exports.TRAP_FOCUS_HANDLER = TRAP_FOCUS_HANDLER;
  65. exports["default"] = TrapFocus;
  66. //# sourceMappingURL=index.js.map