From 7166f4e3d6a5c83c06eaaf3a2bc7d82398237cde Mon Sep 17 00:00:00 2001 From: Danny Coates Date: Mon, 1 Oct 2018 17:46:09 -0700 Subject: [PATCH] improved paste to handle text and pasted file's names --- app/pasteManager.js | 38 +++++++++++++++++++++++++++++--------- 1 file changed, 29 insertions(+), 9 deletions(-) diff --git a/app/pasteManager.js b/app/pasteManager.js index 482183cb..33b180b4 100644 --- a/app/pasteManager.js +++ b/app/pasteManager.js @@ -1,15 +1,35 @@ +function getString(item) { + return new Promise(resolve => { + item.getAsString(resolve); + }); +} + export default function(state, emitter) { - window.addEventListener('paste', event => { + window.addEventListener('paste', async event => { if (state.route !== '/' || state.uploading) return; - for (const item of event.clipboardData.items) { - if (!item.type.includes('image')) continue; - - const file = item.getAsFile(); - - if (!file) continue; // Sometimes null - - emitter.emit('addFiles', { files: [file] }); + const items = Array.from(event.clipboardData.items); + const transferFiles = items.filter(item => item.kind === 'file'); + const strings = items.filter(item => item.kind === 'string'); + if (transferFiles.length) { + const promises = transferFiles.map(async (f, i) => { + const blob = f.getAsFile(); + if (!blob) { + return null; + } + const name = await getString(strings[i]); + const file = new File([blob], name, { type: blob.type }); + return file; + }); + const files = (await Promise.all(promises)).filter(f => !!f); + if (files.length) { + emitter.emit('addFiles', { files }); + } + } else if (strings.length) { + strings[0].getAsString(s => { + const file = new File([s], 'pasted.txt', { type: 'text/plain' }); + emitter.emit('addFiles', { files: [file] }); + }); } }); }