index.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 event = require('../../utils/dom/event.js');
  6. var aria$1 = require('../../constants/aria.js');
  7. const FOCUSABLE_CHILDREN = "_trap-focus-children";
  8. const TRAP_FOCUS_HANDLER = "_trap-focus-handler";
  9. const FOCUS_STACK = [];
  10. const FOCUS_HANDLER = (e) => {
  11. if (FOCUS_STACK.length === 0)
  12. return;
  13. const code = event.getEventCode(e);
  14. const focusableElement = FOCUS_STACK[FOCUS_STACK.length - 1][FOCUSABLE_CHILDREN];
  15. if (focusableElement.length > 0 && code === aria$1.EVENT_CODE.tab) {
  16. if (focusableElement.length === 1) {
  17. e.preventDefault();
  18. if (document.activeElement !== focusableElement[0]) {
  19. focusableElement[0].focus();
  20. }
  21. return;
  22. }
  23. const goingBackward = e.shiftKey;
  24. const isFirst = e.target === focusableElement[0];
  25. const isLast = e.target === focusableElement[focusableElement.length - 1];
  26. if (isFirst && goingBackward) {
  27. e.preventDefault();
  28. focusableElement[focusableElement.length - 1].focus();
  29. }
  30. if (isLast && !goingBackward) {
  31. e.preventDefault();
  32. focusableElement[0].focus();
  33. }
  34. }
  35. };
  36. const TrapFocus = {
  37. beforeMount(el) {
  38. el[FOCUSABLE_CHILDREN] = aria.obtainAllFocusableElements(el);
  39. FOCUS_STACK.push(el);
  40. if (FOCUS_STACK.length <= 1) {
  41. document.addEventListener("keydown", FOCUS_HANDLER);
  42. }
  43. },
  44. updated(el) {
  45. vue.nextTick(() => {
  46. el[FOCUSABLE_CHILDREN] = aria.obtainAllFocusableElements(el);
  47. });
  48. },
  49. unmounted() {
  50. FOCUS_STACK.shift();
  51. if (FOCUS_STACK.length === 0) {
  52. document.removeEventListener("keydown", FOCUS_HANDLER);
  53. }
  54. }
  55. };
  56. exports.FOCUSABLE_CHILDREN = FOCUSABLE_CHILDREN;
  57. exports.TRAP_FOCUS_HANDLER = TRAP_FOCUS_HANDLER;
  58. exports["default"] = TrapFocus;
  59. //# sourceMappingURL=index.js.map