improved paste to handle text and pasted file's names

This commit is contained in:
Danny Coates 2018-10-01 17:46:09 -07:00
parent f7f8944e00
commit 7166f4e3d6
No known key found for this signature in database
GPG Key ID: 4C442633C62E00CB
1 changed files with 29 additions and 9 deletions

View File

@ -1,15 +1,35 @@
function getString(item) {
return new Promise(resolve => {
item.getAsString(resolve);
});
}
export default function(state, emitter) { export default function(state, emitter) {
window.addEventListener('paste', event => { window.addEventListener('paste', async event => {
if (state.route !== '/' || state.uploading) return; if (state.route !== '/' || state.uploading) return;
for (const item of event.clipboardData.items) { const items = Array.from(event.clipboardData.items);
if (!item.type.includes('image')) continue; const transferFiles = items.filter(item => item.kind === 'file');
const strings = items.filter(item => item.kind === 'string');
const file = item.getAsFile(); if (transferFiles.length) {
const promises = transferFiles.map(async (f, i) => {
if (!file) continue; // Sometimes null 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] }); emitter.emit('addFiles', { files: [file] });
});
} }
}); });
} }