useTrapFocus.js 979 B

12345678910111213141516171819202122232425262728293031323334
  1. import React from 'react';
  2. export function useTrapFocus(_ref) {
  3. var container = _ref.container;
  4. React.useEffect(function () {
  5. if (!container) {
  6. return undefined;
  7. }
  8. var focusableElements = container.querySelectorAll('a[href]:not([disabled]), button:not([disabled]), input:not([disabled])');
  9. var firstElement = focusableElements[0];
  10. var lastElement = focusableElements[focusableElements.length - 1];
  11. function trapFocus(event) {
  12. if (event.key !== 'Tab') {
  13. return;
  14. }
  15. if (event.shiftKey) {
  16. if (document.activeElement === firstElement) {
  17. event.preventDefault();
  18. lastElement.focus();
  19. }
  20. } else if (document.activeElement === lastElement) {
  21. event.preventDefault();
  22. firstElement.focus();
  23. }
  24. }
  25. container.addEventListener('keydown', trapFocus);
  26. return function () {
  27. container.removeEventListener('keydown', trapFocus);
  28. };
  29. }, [container]);
  30. }