navigation-key.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.navigationKey = navigationKey;
  6. var _dom = require("@testing-library/dom");
  7. var _utils = require("../utils");
  8. const keys = {
  9. Home: {
  10. keyCode: 36
  11. },
  12. End: {
  13. keyCode: 35
  14. },
  15. ArrowLeft: {
  16. keyCode: 37
  17. },
  18. ArrowRight: {
  19. keyCode: 39
  20. }
  21. };
  22. function getSelectionRange(currentElement, key) {
  23. const {
  24. selectionStart,
  25. selectionEnd
  26. } = currentElement();
  27. if (key === 'Home') {
  28. return {
  29. selectionStart: 0,
  30. selectionEnd: 0
  31. };
  32. }
  33. if (key === 'End') {
  34. return {
  35. selectionStart: selectionEnd + 1,
  36. selectionEnd: selectionEnd + 1
  37. };
  38. }
  39. const cursorChange = Number(key in keys) * (key === 'ArrowLeft' ? -1 : 1);
  40. return {
  41. selectionStart: selectionStart + cursorChange,
  42. selectionEnd: selectionEnd + cursorChange
  43. };
  44. }
  45. function navigationKey(key) {
  46. const event = {
  47. key,
  48. keyCode: keys[key].keyCode,
  49. which: keys[key].keyCode
  50. };
  51. return ({
  52. currentElement,
  53. eventOverrides
  54. }) => {
  55. _dom.fireEvent.keyDown(currentElement(), { ...event,
  56. ...eventOverrides
  57. });
  58. const range = getSelectionRange(currentElement, key);
  59. (0, _utils.setSelectionRangeIfNecessary)(currentElement(), range.selectionStart, range.selectionEnd);
  60. _dom.fireEvent.keyUp(currentElement(), { ...event,
  61. ...eventOverrides
  62. });
  63. };
  64. }