Skip to content

Commit

Permalink
Merge pull request #497 from pinkary-project/feat/496-image-upload-on…
Browse files Browse the repository at this point in the history
…-paste

Add paste support for images into textarea
  • Loading branch information
nunomaduro authored Aug 14, 2024
2 parents d7ed8e1 + f069510 commit 276e4e6
Showing 1 changed file with 26 additions and 2 deletions.
28 changes: 26 additions & 2 deletions resources/js/image-upload.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,10 @@ const imageUpload = () => ({
textarea: null,

init() {
this.textarea = this.$el.querySelector('textarea[x-ref="content"]');
if (this.$refs.imageButton !== undefined) {
this.setupListeners();
}

this.textarea = this.$el.querySelector('textarea[x-ref="content"]');
},

setupListeners() {
Expand All @@ -25,6 +24,8 @@ const imageUpload = () => ({
event.target.value = '';
});

this.textarea.addEventListener('paste', this.handleImagePaste.bind(this));

Livewire.on('image.uploaded', (event) => {
this.createMarkdownImage(event);
});
Expand All @@ -42,6 +43,29 @@ const imageUpload = () => ({
});
},

handleImagePaste(event) {
// if no files, handle paste event as normal
if (event.clipboardData.files.length === 0) {
return;
}

// prevent default behavior to avoid pasting the title of the image
event.preventDefault();

// build out the file list from the clipboard, filtering only for images.
const dataTransfer = new DataTransfer();
for (const item of event.clipboardData.files) {
if (!item.type.startsWith('image/')) {
this.addErrors(['The file must be an image.']);
return;
}

dataTransfer.items.add(item);
}

this.checkFileSize(dataTransfer.files);
},

addErrors(errors) {
this.$nextTick(() => {
const incomingErrors = Object.values(errors).flat()
Expand Down

0 comments on commit 276e4e6

Please sign in to comment.