pasteManager.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536
  1. function getString(item) {
  2. return new Promise(resolve => {
  3. item.getAsString(resolve);
  4. });
  5. }
  6. export default function(state, emitter) {
  7. window.addEventListener('paste', async event => {
  8. if (state.route !== '/' || state.uploading) return;
  9. if (['password', 'text', 'email'].includes(event.target.type)) return;
  10. const items = Array.from(event.clipboardData.items);
  11. const transferFiles = items.filter(item => item.kind === 'file');
  12. const strings = items.filter(item => item.kind === 'string');
  13. if (transferFiles.length) {
  14. const promises = transferFiles.map(async (f, i) => {
  15. const blob = f.getAsFile();
  16. if (!blob) {
  17. return null;
  18. }
  19. const name = await getString(strings[i]);
  20. const file = new File([blob], name, { type: blob.type });
  21. return file;
  22. });
  23. const files = (await Promise.all(promises)).filter(f => !!f);
  24. if (files.length) {
  25. emitter.emit('addFiles', { files });
  26. }
  27. } else if (strings.length) {
  28. strings[0].getAsString(s => {
  29. const file = new File([s], 'pasted.txt', { type: 'text/plain' });
  30. emitter.emit('addFiles', { files: [file] });
  31. });
  32. }
  33. });
  34. }