copySelection.js 906 B

123456789101112131415161718192021222324252627
  1. import { createDataTransfer } from '../utils/dataTransfer/DataTransfer.js';
  2. import '../utils/dataTransfer/Clipboard.js';
  3. import { getWindow } from '../utils/misc/getWindow.js';
  4. import { hasOwnSelection } from '../utils/focus/selection.js';
  5. import { getUISelection, getUIValue } from './UI.js';
  6. function copySelection(target) {
  7. const data = hasOwnSelection(target) ? {
  8. 'text/plain': readSelectedValueFromInput(target)
  9. } : {
  10. 'text/plain': String(target.ownerDocument.getSelection())
  11. };
  12. const dt = createDataTransfer(getWindow(target));
  13. for(const type in data){
  14. if (data[type]) {
  15. dt.setData(type, data[type]);
  16. }
  17. }
  18. return dt;
  19. }
  20. function readSelectedValueFromInput(target) {
  21. const sel = getUISelection(target);
  22. const val = getUIValue(target);
  23. return val.substring(sel.startOffset, sel.endOffset);
  24. }
  25. export { copySelection };