modal_handler.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. class KeyboardModalHandler {
  2. static setupFocusTrap() {
  3. const container = document.getElementById("modal-container");
  4. if (container !== null) {
  5. container.onkeydown = (e) => {
  6. if (e.key === 'Tab') {
  7. // Since there is only one focusable button in the keyboard modal we always want to focus it with the tab key. This handles
  8. // the special case of having just one focusable element in a dialog/ where keyboard focus is placed on an element that is not in the
  9. // tab order.
  10. container.querySelectorAll('button')[0].focus();
  11. e.preventDefault();
  12. }
  13. };
  14. }
  15. }
  16. static open(fragment, initialFocusElementId) {
  17. if (document.getElementById("modal-container") !== null){
  18. return;
  19. }
  20. this.activeElement = document.activeElement;
  21. const container = document.createElement("div");
  22. container.id = "modal-container";
  23. container.setAttribute("role", "dialog");
  24. container.appendChild(document.importNode(fragment, true));
  25. document.body.appendChild(container);
  26. const closeButton = document.querySelector("button.btn-close-modal");
  27. if (closeButton !== null) {
  28. closeButton.onclick = (event) => {
  29. event.preventDefault();
  30. KeyboardModalHandler.close();
  31. };
  32. }
  33. const initialFocusElement = document.getElementById(initialFocusElementId);
  34. if (initialFocusElement !== undefined) {
  35. initialFocusElement.focus();
  36. }
  37. this.setupFocusTrap();
  38. }
  39. static close() {
  40. const container = document.getElementById("modal-container");
  41. if (container !== null) {
  42. container.parentNode.removeChild(container);
  43. if (this.activeElement !== undefined && this.activeElement !== null) {
  44. this.activeElement.focus();
  45. }
  46. }
  47. }
  48. }