paste.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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 paste(element, text, init, {
  9. initialSelectionStart,
  10. initialSelectionEnd
  11. } = {}) {
  12. if (element.disabled) return;
  13. if (typeof element.value === 'undefined') {
  14. throw new TypeError(`the current element is of type ${element.tagName} and doesn't have a valid value`);
  15. }
  16. (0, _utils.eventWrapper)(() => element.focus()); // by default, a new element has it's selection start and end at 0
  17. // but most of the time when people call "paste", they expect it to paste
  18. // at the end of the current input value. So, if the selection start
  19. // and end are both the default of 0, then we'll go ahead and change
  20. // them to the length of the current value.
  21. // the only time it would make sense to pass the initialSelectionStart or
  22. // initialSelectionEnd is if you have an input with a value and want to
  23. // explicitely start typing with the cursor at 0. Not super common.
  24. if (element.selectionStart === 0 && element.selectionEnd === 0) {
  25. (0, _utils.setSelectionRangeIfNecessary)(element, initialSelectionStart != null ? initialSelectionStart : element.value.length, initialSelectionEnd != null ? initialSelectionEnd : element.value.length);
  26. }
  27. _dom.fireEvent.paste(element, init);
  28. if (!element.readOnly) {
  29. const {
  30. newValue,
  31. newSelectionStart
  32. } = (0, _utils.calculateNewValue)(text, element);
  33. _dom.fireEvent.input(element, {
  34. inputType: 'insertFromPaste',
  35. target: {
  36. value: newValue
  37. }
  38. });
  39. (0, _utils.setSelectionRangeIfNecessary)(element, {
  40. newSelectionStart,
  41. newSelectionEnd: newSelectionStart
  42. });
  43. }
  44. }