copy.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import select from 'select';
  2. import command from '../common/command';
  3. import createFakeElement from '../common/create-fake-element';
  4. /**
  5. * Create fake copy action wrapper using a fake element.
  6. * @param {String} target
  7. * @param {Object} options
  8. * @return {String}
  9. */
  10. const fakeCopyAction = (value, options) => {
  11. const fakeElement = createFakeElement(value);
  12. options.container.appendChild(fakeElement);
  13. const selectedText = select(fakeElement);
  14. command('copy');
  15. fakeElement.remove();
  16. return selectedText;
  17. };
  18. /**
  19. * Copy action wrapper.
  20. * @param {String|HTMLElement} target
  21. * @param {Object} options
  22. * @return {String}
  23. */
  24. const ClipboardActionCopy = (
  25. target,
  26. options = { container: document.body }
  27. ) => {
  28. let selectedText = '';
  29. if (typeof target === 'string') {
  30. selectedText = fakeCopyAction(target, options);
  31. } else if (
  32. target instanceof HTMLInputElement &&
  33. !['text', 'search', 'url', 'tel', 'password'].includes(target?.type)
  34. ) {
  35. // If input type doesn't support `setSelectionRange`. Simulate it. https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange
  36. selectedText = fakeCopyAction(target.value, options);
  37. } else {
  38. selectedText = select(target);
  39. command('copy');
  40. }
  41. return selectedText;
  42. };
  43. export default ClipboardActionCopy;