index.mjs 1.9 KB

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