handle-key.js 2.2 KB

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