handle-key.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import { stopEventPropagation, fireClick } from './handle-dom';
  2. import { setFocusStyle } from './handle-swal-dom';
  3. var handleKeyDown = function(event, params, modal) {
  4. var e = event || window.event;
  5. var keyCode = e.keyCode || e.which;
  6. var $okButton = modal.querySelector('button.confirm');
  7. var $cancelButton = modal.querySelector('button.cancel');
  8. var $modalButtons = modal.querySelectorAll('button[tabindex]');
  9. if ([9, 13, 32, 27].indexOf(keyCode) === -1) {
  10. // Don't do work on keys we don't care about.
  11. return;
  12. }
  13. var $targetElement = e.target || e.srcElement;
  14. var btnIndex = -1; // Find the button - note, this is a nodelist, not an array.
  15. for (var i = 0; i < $modalButtons.length; i++) {
  16. if ($targetElement === $modalButtons[i]) {
  17. btnIndex = i;
  18. break;
  19. }
  20. }
  21. if (keyCode === 9) {
  22. // TAB
  23. if (btnIndex === -1) {
  24. // No button focused. Jump to the confirm button.
  25. $targetElement = $okButton;
  26. } else {
  27. // Cycle to the next button
  28. if (btnIndex === $modalButtons.length - 1) {
  29. $targetElement = $modalButtons[0];
  30. } else {
  31. $targetElement = $modalButtons[btnIndex + 1];
  32. }
  33. }
  34. stopEventPropagation(e);
  35. $targetElement.focus();
  36. if (params.confirmButtonColor) {
  37. setFocusStyle($targetElement, params.confirmButtonColor);
  38. }
  39. } else {
  40. if (keyCode === 13) {
  41. if ($targetElement.tagName === 'INPUT') {
  42. $targetElement = $okButton;
  43. $okButton.focus();
  44. }
  45. if (btnIndex === -1) {
  46. // ENTER/SPACE clicked outside of a button.
  47. $targetElement = $okButton;
  48. } else {
  49. // Do nothing - let the browser handle it.
  50. $targetElement = undefined;
  51. }
  52. } else if (keyCode === 27 && params.allowEscapeKey === true) {
  53. $targetElement = $cancelButton;
  54. fireClick($targetElement, e);
  55. } else {
  56. // Fallback - let the browser handle it.
  57. $targetElement = undefined;
  58. }
  59. }
  60. };
  61. export default handleKeyDown;