plane/space/components/tiptap/plugins/delete-image.tsx

69 lines
2.0 KiB
TypeScript
Raw Normal View History

2023-09-07 09:39:16 +00:00
import { EditorState, Plugin, PluginKey, Transaction } from "@tiptap/pm/state";
import { Node as ProseMirrorNode } from "@tiptap/pm/model";
import fileService from "services/file.service";
const deleteKey = new PluginKey("delete-image");
2023-09-07 09:39:16 +00:00
const IMAGE_NODE_TYPE = "image";
2023-09-07 09:39:16 +00:00
interface ImageNode extends ProseMirrorNode {
attrs: {
src: string;
id: string;
};
}
const TrackImageDeletionPlugin = (): Plugin =>
new Plugin({
key: deleteKey,
2023-09-07 09:39:16 +00:00
appendTransaction: (transactions: readonly Transaction[], oldState: EditorState, newState: EditorState) => {
const newImageSources = new Set();
newState.doc.descendants((node) => {
if (node.type.name === IMAGE_NODE_TYPE) {
newImageSources.add(node.attrs.src);
}
});
transactions.forEach((transaction) => {
if (!transaction.docChanged) return;
2023-09-07 09:39:16 +00:00
const removedImages: ImageNode[] = [];
oldState.doc.descendants((oldNode, oldPos) => {
2023-09-07 09:39:16 +00:00
if (oldNode.type.name !== IMAGE_NODE_TYPE) return;
if (oldPos < 0 || oldPos > newState.doc.content.size) return;
if (!newState.doc.resolve(oldPos).parent) return;
2023-09-07 09:39:16 +00:00
const newNode = newState.doc.nodeAt(oldPos);
// Check if the node has been deleted or replaced
2023-09-07 09:39:16 +00:00
if (!newNode || newNode.type.name !== IMAGE_NODE_TYPE) {
if (!newImageSources.has(oldNode.attrs.src)) {
removedImages.push(oldNode as ImageNode);
}
}
});
2023-09-07 09:39:16 +00:00
removedImages.forEach(async (node) => {
const src = node.attrs.src;
2023-09-07 09:39:16 +00:00
await onNodeDeleted(src);
});
});
return null;
},
});
export default TrackImageDeletionPlugin;
2023-09-07 09:39:16 +00:00
async function onNodeDeleted(src: string): Promise<void> {
try {
const assetUrlWithWorkspaceId = new URL(src).pathname.substring(1);
const resStatus = await fileService.deleteImage(assetUrlWithWorkspaceId);
if (resStatus === 204) {
console.log("Image deleted successfully");
}
} catch (error) {
console.error("Error deleting image: ", error);
}
}