Skip to content

Commit

Permalink
feat: Add image paste plugin (#31)
Browse files Browse the repository at this point in the history
  • Loading branch information
muhsin-k authored Sep 11, 2024
1 parent c3540b9 commit f92276a
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 1 deletion.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@chatwoot/prosemirror-schema",
"version": "1.0.16",
"version": "1.0.17",
"description": "Schema setup for using prosemirror in chatwoot. Based on 👉 https://github.com/ProseMirror/prosemirror-example-setup/",
"main": "dist/index.js",
"scripts": {
Expand Down
58 changes: 58 additions & 0 deletions src/plugins/image.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { Plugin } from "prosemirror-state";

/**
* Replaces an image node in the editor with a new image URL.
*
* @param {string} currentUrl - The current URL of the image to be replaced.
* @param {string} newUrl - The new URL to replace the current image with.
* @param {EditorView} view - The ProseMirror editor view.
*/
function replaceImage(currentUrl, newUrl, view) {
view.state.doc.descendants((node, pos) => {
if (node.type.name === "image" && node.attrs.src === currentUrl) {
const tr = view.state.tr.setNodeMarkup(pos, null, {
...node.attrs,
src: newUrl,
});
view.dispatch(tr);
}
});
}

/**
* Creates a ProseMirror plugin that handles image pasting and uploading.
*
* @param {Function} uploadImage - A function that takes an image URL and returns a Promise
* that resolves to the new URL after uploading.
* @returns {Plugin} A ProseMirror plugin that handles image pasting.
*/
const imagePastePlugin = (uploadImage) =>
new Plugin({
props: {
/**
* Handles the paste event in the editor.
*
* @param {EditorView} view - The ProseMirror editor view.
* @param {Event} event - The paste event.
* @param {Slice} slice - The ProseMirror Slice object representing the pasted content.
*/
handlePaste(view, event, slice) {
const imageUrls = [];
slice.content.descendants((node) => {
if (node.type.name === "image") {
imageUrls.push(node.attrs.src);
}
});
Promise.all(imageUrls.map(async (url) => {
try {
const newUrl = await uploadImage(url);
replaceImage(url, newUrl, view);
} catch (error) {
console.error("Error uploading image:", error);
}
}));
},
},
});

export default imagePastePlugin;

0 comments on commit f92276a

Please sign in to comment.