From 0e5f82bebab77d8b6b15cd7f4b3de4ec451efa19 Mon Sep 17 00:00:00 2001 From: Palanikannan1437 <73993394+Palanikannan1437@users.noreply.github.com> Date: Tue, 5 Sep 2023 02:20:09 +0530 Subject: [PATCH] impoved complexity to O(1) from O(n) for large docs --- web/components/tiptap/plugins/delete-image.tsx | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/web/components/tiptap/plugins/delete-image.tsx b/web/components/tiptap/plugins/delete-image.tsx index 85844178c..fdf515ccc 100644 --- a/web/components/tiptap/plugins/delete-image.tsx +++ b/web/components/tiptap/plugins/delete-image.tsx @@ -3,7 +3,6 @@ import { Node as ProseMirrorNode } from "@tiptap/pm/model"; import fileService from "services/file.service"; const deleteKey = new PluginKey("delete-image"); - const IMAGE_NODE_TYPE = "image"; interface ImageNode extends ProseMirrorNode { @@ -17,6 +16,13 @@ const TrackImageDeletionPlugin = (): Plugin => new Plugin({ key: deleteKey, 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; @@ -31,14 +37,7 @@ const TrackImageDeletionPlugin = (): Plugin => // Check if the node has been deleted or replaced if (!newNode || newNode.type.name !== IMAGE_NODE_TYPE) { - // Check if the node still exists elsewhere in the document - let nodeExists = false; - newState.doc.descendants((node) => { - if (node.attrs.src === oldNode.attrs.src) { - nodeExists = true; - } - }); - if (!nodeExists) { + if (!newImageSources.has(oldNode.attrs.src)) { removedImages.push(oldNode as ImageNode); } }