b71cd941e369fd71f188c24ecd964e9175a42be96d624af3054e6a4b0e5fe71b840d51c8ac21cfbc156a06e4f508488736330a7e2369020be43a3a0ef0faac 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. if (FOCUS_STACK.length === 0)
  9. return;
  10. const focusableElement = FOCUS_STACK[FOCUS_STACK.length - 1][FOCUSABLE_CHILDREN];
  11. if (focusableElement.length > 0 && e.code === EVENT_CODE.tab) {
  12. if (focusableElement.length === 1) {
  13. e.preventDefault();
  14. if (document.activeElement !== focusableElement[0]) {
  15. focusableElement[0].focus();
  16. }
  17. return;
  18. }
  19. const goingBackward = e.shiftKey;
  20. const isFirst = e.target === focusableElement[0];
  21. const isLast = e.target === focusableElement[focusableElement.length - 1];
  22. if (isFirst && goingBackward) {
  23. e.preventDefault();
  24. focusableElement[focusableElement.length - 1].focus();
  25. }
  26. if (isLast && !goingBackward) {
  27. e.preventDefault();
  28. focusableElement[0].focus();
  29. }
  30. }
  31. };
  32. const TrapFocus = {
  33. beforeMount(el) {
  34. el[FOCUSABLE_CHILDREN] = obtainAllFocusableElements(el);
  35. FOCUS_STACK.push(el);
  36. if (FOCUS_STACK.length <= 1) {
  37. document.addEventListener("keydown", FOCUS_HANDLER);
  38. }
  39. },
  40. updated(el) {
  41. nextTick(() => {
  42. el[FOCUSABLE_CHILDREN] = obtainAllFocusableElements(el);
  43. });
  44. },
  45. unmounted() {
  46. FOCUS_STACK.shift();
  47. if (FOCUS_STACK.length === 0) {
  48. document.removeEventListener("keydown", FOCUS_HANDLER);
  49. }
  50. }
  51. };
  52. export { FOCUSABLE_CHILDREN, TRAP_FOCUS_HANDLER, TrapFocus as default };
  53. //# sourceMappingURL=index.mjs.map