2023-09-07 09:39:16 +00:00
|
|
|
import { EditorState, Plugin, PluginKey, Transaction } from "@tiptap/pm/state";
|
2023-09-03 13:20:30 +00:00
|
|
|
import { Node as ProseMirrorNode } from "@tiptap/pm/model";
|
2023-09-01 11:12:30 +00:00
|
|
|
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-01 11:12:30 +00:00
|
|
|
|
2023-09-07 09:39:16 +00:00
|
|
|
interface ImageNode extends ProseMirrorNode {
|
|
|
|
attrs: {
|
|
|
|
src: string;
|
|
|
|
id: string;
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
const TrackImageDeletionPlugin = (): Plugin =>
|
2023-09-01 11:12:30 +00:00
|
|
|
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);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2023-09-01 11:12:30 +00:00
|
|
|
transactions.forEach((transaction) => {
|
|
|
|
if (!transaction.docChanged) return;
|
|
|
|
|
2023-09-07 09:39:16 +00:00
|
|
|
const removedImages: ImageNode[] = [];
|
2023-09-01 11:12:30 +00:00
|
|
|
|
|
|
|
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;
|
2023-09-01 11:12:30 +00:00
|
|
|
if (!newState.doc.resolve(oldPos).parent) return;
|
2023-09-07 09:39:16 +00:00
|
|
|
|
2023-09-01 11:12:30 +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-01 11:12:30 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2023-09-07 09:39:16 +00:00
|
|
|
removedImages.forEach(async (node) => {
|
2023-09-01 11:12:30 +00:00
|
|
|
const src = node.attrs.src;
|
2023-09-07 09:39:16 +00:00
|
|
|
await onNodeDeleted(src);
|
2023-09-01 11:12:30 +00:00
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
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);
|
2023-09-01 11:12:30 +00:00
|
|
|
}
|
|
|
|
}
|