paste.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.paste = paste;
  6. var _dom = require("@testing-library/dom");
  7. var _utils = require("./utils");
  8. function isSupportedElement(element) {
  9. return (0, _utils.isElementType)(element, 'input') && Boolean(_utils.editableInputTypes[element.type]) || (0, _utils.isElementType)(element, 'textarea');
  10. }
  11. function paste(element, text, init, {
  12. initialSelectionStart,
  13. initialSelectionEnd
  14. } = {}) {
  15. // TODO: implement for contenteditable
  16. if (!isSupportedElement(element)) {
  17. throw new TypeError(`The given ${element.tagName} element is currently unsupported.
  18. A PR extending this implementation would be very much welcome at https://github.com/testing-library/user-event`);
  19. }
  20. if ((0, _utils.isDisabled)(element)) {
  21. return;
  22. }
  23. (0, _utils.eventWrapper)(() => element.focus()); // by default, a new element has it's selection start and end at 0
  24. // but most of the time when people call "paste", they expect it to paste
  25. // at the end of the current input value. So, if the selection start
  26. // and end are both the default of 0, then we'll go ahead and change
  27. // them to the length of the current value.
  28. // the only time it would make sense to pass the initialSelectionStart or
  29. // initialSelectionEnd is if you have an input with a value and want to
  30. // explicitely start typing with the cursor at 0. Not super common.
  31. if (element.selectionStart === 0 && element.selectionEnd === 0) {
  32. (0, _utils.setSelectionRange)(element, initialSelectionStart != null ? initialSelectionStart : element.value.length, initialSelectionEnd != null ? initialSelectionEnd : element.value.length);
  33. }
  34. _dom.fireEvent.paste(element, init);
  35. if (element.readOnly) {
  36. return;
  37. }
  38. text = text.substr(0, (0, _utils.getSpaceUntilMaxLength)(element));
  39. const {
  40. newValue,
  41. newSelectionStart
  42. } = (0, _utils.calculateNewValue)(text, element);
  43. _dom.fireEvent.input(element, {
  44. inputType: 'insertFromPaste',
  45. target: {
  46. value: newValue
  47. }
  48. });
  49. (0, _utils.setSelectionRange)(element, // TODO: investigate why the selection caused by invalid parameters was expected
  50. {
  51. newSelectionStart,
  52. selectionEnd: newSelectionStart
  53. }, {});
  54. }