index.js 2.0 KB

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