Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Implement image insertion in notes/content via copy and paste -EXO-74768 - Meeds-io/MIPs#145 #1237

Merged
merged 1 commit into from
Dec 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ CKEDITOR.editorConfig = function (config) {
if (!webPageNote) {
mobileToolbar[mobileToolbar.findIndex(item => item.name ==='blocks')].items.push('attachFile');
}
let extraPlugins = `a11ychecker,balloonpanel,indent,indentblock,indentlist,codesnippet,sharedspace,copyformatting,table,tabletools,embedsemantic,autolink,colordialog${!webPageNote && ',tagSuggester' || ''},emoji,link,font,justify,widget,${!webPageNote && ',insertOptions' || ''},contextmenu,tabletools,tableresize,toc,linkBalloon,suggester, ${eXo.env.portal.insertImageOptionEnabled && 'image2, insertImage' || ''}`;
let extraPlugins = `a11ychecker,balloonpanel,indent,indentblock,indentlist,codesnippet,sharedspace,copyformatting,table,tabletools,embedsemantic,autolink,colordialog${!webPageNote && ',tagSuggester' || ''},emoji,link,font,justify,widget,${!webPageNote && ',insertOptions' || ''},contextmenu,tabletools,tableresize,toc,linkBalloon,suggester,${eXo.env.portal.insertImageOptionEnabled && 'image2,insertImage' || ''}`;
let removePlugins = `image,confirmBeforeReload,maximize,resize,autoembed${webPageNote && ',tagSuggester' || ''}`;

require(['SHARED/extensionRegistry'], function(extensionRegistry) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,13 @@ CKEDITOR.editorConfig = function (config) {
CKEDITOR.plugins.addExternal('insertOptions','/notes/javascript/eXo/wiki/ckeditor/plugins/insertOptions/','plugin.js');
CKEDITOR.plugins.addExternal('toc','/notes/javascript/eXo/wiki/ckeditor/plugins/toc/','plugin.js');
CKEDITOR.plugins.addExternal('linkBalloon', '/social/js/ckeditorPlugins/linkBalloon/', 'plugin.js');
if (eXo.env.portal.insertImageOptionEnabled) {
CKEDITOR.plugins.addExternal('insertImage','/notes/javascript/eXo/wiki/ckeditor/plugins/insertImage/','plugin.js');
}


let extraPlugins = 'simpleLink,a11ychecker,balloonpanel,indent,indentblock,indentlist,codesnippet,sharedspace,copyformatting,table,tabletools,embedsemantic,' +
`autolink,colordialog,emoji,link,font,justify,widget,insertOptions,contextmenu,tabletools,tableresize,toc,editorplaceholder,formatOption,linkBalloon,${eXo.env.portal.insertImageOptionEnabled && 'image2' || ''}`;
`autolink,colordialog,emoji,link,font,justify,widget,insertOptions,contextmenu,tabletools,tableresize,toc,editorplaceholder,formatOption,linkBalloon,${eXo.env.portal.insertImageOptionEnabled && 'image2,insertImage' || ''}`;

let removePlugins = 'image,confirmBeforeReload,maximize,resize,autoembed,tagSuggester,attachImage';

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,10 @@
input.onchange = function () {
const file = input.files[0];
if (file) {
handleFileUpload(file, false);
handleOnchangeFileUpload(file).then(() => {
document.dispatchEvent(new CustomEvent('notes-editor-upload-done'));
editor.fire('change');
});
}
};
}
Expand Down Expand Up @@ -140,56 +143,6 @@
}
return new Blob([u8Array], {type: mime});
}

function handleFileUpload(file, moveSelectionPosition) {
if (editor.getData().trim() === '') {
editor.insertHtml('<p></p>');
editor.focus();
}
const loader = editor.uploadRepository.create(file);
const reader = new FileReader();

reader.onload = function (e) {
const dataUrl = e.target.result;

const blob = dataURLtoBlob(dataUrl);
const blobUrl = URL.createObjectURL(blob);

// Create a temporary document to safely insert the image
const tempDoc = document.implementation.createHTMLDocument('');
const temp = new CKEDITOR.dom.element(tempDoc.body);
temp.data('cke-editable', 1);

temp.appendHtml(`<img class="cke_upload_uploading" cke_upload_id="${uploadId}" src="${blobUrl}" alt="" />`);

const img = temp.find('img').getItem(0);
loader.data = dataUrl;
loader.upload(editor.config.uploadUrl + uploadId); // Ensure unique upload URL

// Insert the image and trigger autogrow
editor.insertHtml(img.getOuterHtml());
editor.focus();

if (moveSelectionPosition) {
const range = editor.getSelection().getRanges()[0];
range.moveToPosition(range.endContainer, CKEDITOR.POSITION_AFTER_END);
editor.getSelection().selectRanges([range]);
}
editor.execCommand('autogrow');

// Bind notifications for the upload process
fileTools.bindNotifications(editor, loader);

loader.on('uploaded', function () {
// Clean up the uploaded image once done
cleanWidget(blobUrl);
editor.fire('change');
});
};

reader.readAsDataURL(file);
}

// handel temp upload
editor.on('fileUploadRequest', function (evt) {
evt.stop();
Expand Down Expand Up @@ -224,17 +177,85 @@
});

editor.on('paste', function (evt) {
// For performance reason do not parse data if it does not contain img.
const files = Array.from(evt.data.dataTransfer._.files);
if (files.length === 0) {
return;
const uploadSequentially = async () => {
document.dispatchEvent(new CustomEvent('notes-editor-upload-progress'));
for (const file of files) {
// eslint-disable-next-line
await handleFileUpload(file, true);
}
};
if (files.length > 0) {
uploadSequentially().then(() => {
document.dispatchEvent(new CustomEvent('notes-editor-upload-done'));
editor.fire('change');
evt.stop();
});
}
files.forEach((file) => {
handleFileUpload(file, true);
});
evt.stop();
});

async function handleOnchangeFileUpload(file) {
document.dispatchEvent(new CustomEvent('notes-editor-upload-progress'));
if (editor.getData().trim() === '') {
editor.insertHtml('<p></p>');
editor.focus();
}
await handleFileUpload(file, false);
}

// eslint-disable-next-line require-await
async function handleFileUpload(file, moveRange) {
return new Promise((resolve) => {
const loader = editor.uploadRepository.create(file);
const reader = new FileReader();

reader.onload = function (e) {
const dataUrl = e.target.result;

const blob = dataURLtoBlob(dataUrl);
const blobUrl = URL.createObjectURL(blob);

// Create a temporary document to safely insert the image
const tempDoc = document.implementation.createHTMLDocument('');
const temp = new CKEDITOR.dom.element(tempDoc.body);
temp.data('cke-editable', 1);
temp.appendHtml(`<img class="cke_upload_uploading" cke_upload_id="${uploadId}" src="${blobUrl}" alt="" />`);

const img = temp.find('img').getItem(0);
loader.data = dataUrl;

// Insert the temporary image into the editor
editor.insertHtml(img.getOuterHtml());
editor.focus();
editor.execCommand('autogrow');

const range = editor.getSelection().getRanges()[0];
if (range && moveRange) {
range.moveToPosition(range.endContainer, CKEDITOR.POSITION_AFTER_END);
editor.getSelection().selectRanges([range]);
editor.insertHtml('<p>&nbsp;</p>');
editor.focus();
editor.execCommand('autogrow');
}
// Handle notifications and upload progress
fileTools.bindNotifications(editor, loader);

loader.upload(editor.config.uploadUrl + uploadId); // Ensure unique upload URL

loader.on('uploaded', function () {
cleanWidget(blobUrl);
resolve(); // Resolve the promise to move to the next image
});

loader.on('error', function () {
img.remove(); // Remove failed image
resolve(); // Continue with the next file
});
};
reader.readAsDataURL(file); // Trigger file reading
});
}

function cleanWidget(dataUrl) {
const insertedImage = editor.document.findOne(`img[src="${dataUrl}"]`);
if (insertedImage) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,9 @@ export default {
},
newPublicationDrawerEnabled() {
return eXo?.env?.portal?.newPublicationDrawerEnabled;
},
isContentImagesUploadProgress() {
return this.contentImageUploadProgress;
}
},
created() {
Expand All @@ -296,6 +299,12 @@ export default {

document.addEventListener('note-custom-plugins', this.openCustomPluginsDrawer);
document.addEventListener('notes-extensions-updated', this.refreshEditorExtensions);
document.addEventListener('notes-editor-upload-progress', () => {
this.contentImageUploadProgress = true ;
});
document.addEventListener('notes-editor-upload-done', () => {
this.contentImageUploadProgress = false;
});
},
methods: {
metadataUpdated(properties) {
Expand Down Expand Up @@ -499,7 +508,7 @@ export default {
self.setToolBarEffect();
},
change: function (evt) {
if (!self.initialized || self.contentImageUploadProgress) {
if (!self.initialized || self.isContentImagesUploadProgress) {
// First time setting data
self.initialized = true;
return;
Expand All @@ -522,20 +531,6 @@ export default {
});
}
},
fileUploadRequest: function () {
self.contentImageUploadProgress = true;
},
fileUploadResponse: function() {
self.contentImageUploadProgress = false;
/*add plugin fileUploadResponse to handle file upload response ,
in this method we can get the response from server and update the editor content
this method is called when file upload is finished*/
self.editor.once('afterInsertHtml', ()=> {
window.setTimeout(() => {
self.editor.fire('mode');
}, 2000);
});
},
doubleclick: function(evt) {
const element = evt.data.element;
if ( element && element.is('a')) {
Expand Down
Loading