(editor: Editor, deleteHandler: TFileHandler["delete"])
| 20 | const DELETE_PLUGIN_KEY = new PluginKey("delete-utility"); |
| 21 | |
| 22 | export const TrackFileDeletionPlugin = (editor: Editor, deleteHandler: TFileHandler["delete"]): Plugin => |
| 23 | new Plugin({ |
| 24 | key: DELETE_PLUGIN_KEY, |
| 25 | appendTransaction: (transactions: readonly Transaction[], oldState: EditorState, newState: EditorState) => { |
| 26 | const newFileSources: { |
| 27 | [nodeType: string]: Set<string> | undefined; |
| 28 | } = {}; |
| 29 | if (!transactions.some((tr) => tr.docChanged)) return null; |
| 30 | if (transactions.some((tr) => tr.getMeta(CORE_EDITOR_META.SKIP_FILE_DELETION))) return null; |
| 31 | |
| 32 | newState.doc.descendants((node) => { |
| 33 | const nodeType = node.type.name as keyof NodeFileMapType; |
| 34 | const nodeFileSetDetails = NODE_FILE_MAP[nodeType]; |
| 35 | if (nodeFileSetDetails) { |
| 36 | if (newFileSources[nodeType]) { |
| 37 | newFileSources[nodeType].add(node.attrs.src); |
| 38 | } else { |
| 39 | newFileSources[nodeType] = new Set([node.attrs.src]); |
| 40 | } |
| 41 | } |
| 42 | }); |
| 43 | |
| 44 | const removedFiles: TFileNode[] = []; |
| 45 | |
| 46 | // iterate through all the nodes in the old state |
| 47 | oldState.doc.descendants((node) => { |
| 48 | const nodeType = node.type.name as keyof NodeFileMapType; |
| 49 | const isAValidNode = NODE_FILE_MAP[nodeType]; |
| 50 | // if the node doesn't match, then return as no point in checking |
| 51 | if (!isAValidNode) return; |
| 52 | // Check if the node has been deleted or replaced |
| 53 | if (!newFileSources[nodeType]?.has(node.attrs.src)) { |
| 54 | removedFiles.push(node as TFileNode); |
| 55 | } |
| 56 | }); |
| 57 | |
| 58 | removedFiles.forEach(async (node) => { |
| 59 | const nodeType = node.type.name as keyof NodeFileMapType; |
| 60 | const src = node.attrs.src; |
| 61 | const nodeFileSetDetails = NODE_FILE_MAP[nodeType]; |
| 62 | if (!nodeFileSetDetails || !src) return; |
| 63 | try { |
| 64 | editor.storage[nodeType]?.[nodeFileSetDetails.fileSetName]?.set(src, true); |
| 65 | // update assets list storage value |
| 66 | editor.commands.updateAssetsList?.({ |
| 67 | idToRemove: node.attrs.id, |
| 68 | }); |
| 69 | await deleteHandler(src); |
| 70 | } catch (error) { |
| 71 | console.error("Error deleting file via delete utility plugin:", error); |
| 72 | } |
| 73 | }); |
| 74 | |
| 75 | return null; |
| 76 | }, |
| 77 | }); |
no test coverage detected