(currentXML: string, nodes: string)
| 139 | * @returns The updated XML string with replaced nodes |
| 140 | */ |
| 141 | export function replaceNodes(currentXML: string, nodes: string): string { |
| 142 | // Check for valid inputs |
| 143 | if (!currentXML || !nodes) { |
| 144 | throw new Error("Both currentXML and nodes must be provided") |
| 145 | } |
| 146 | |
| 147 | try { |
| 148 | // Parse the XML strings to create DOM objects |
| 149 | const parser = new DOMParser() |
| 150 | const currentDoc = parser.parseFromString(currentXML, "text/xml") |
| 151 | |
| 152 | // Handle nodes input - if it doesn't contain <root>, wrap it |
| 153 | let nodesString = nodes |
| 154 | if (!nodes.includes("<root>")) { |
| 155 | nodesString = `<root>${nodes}</root>` |
| 156 | } |
| 157 | |
| 158 | const nodesDoc = parser.parseFromString(nodesString, "text/xml") |
| 159 | |
| 160 | // Find the root element in the current document |
| 161 | let currentRoot = currentDoc.querySelector("mxGraphModel > root") |
| 162 | if (!currentRoot) { |
| 163 | // If no root element is found, create the proper structure |
| 164 | const mxGraphModel = |
| 165 | currentDoc.querySelector("mxGraphModel") || |
| 166 | currentDoc.createElement("mxGraphModel") |
| 167 | |
| 168 | if (!currentDoc.contains(mxGraphModel)) { |
| 169 | currentDoc.appendChild(mxGraphModel) |
| 170 | } |
| 171 | |
| 172 | currentRoot = currentDoc.createElement("root") |
| 173 | mxGraphModel.appendChild(currentRoot) |
| 174 | } |
| 175 | |
| 176 | // Find the root element in the nodes document |
| 177 | const nodesRoot = nodesDoc.querySelector("root") |
| 178 | if (!nodesRoot) { |
| 179 | throw new Error( |
| 180 | "Invalid nodes: Could not find or create <root> element", |
| 181 | ) |
| 182 | } |
| 183 | |
| 184 | // Clear all existing child elements from the current root |
| 185 | while (currentRoot.firstChild) { |
| 186 | currentRoot.removeChild(currentRoot.firstChild) |
| 187 | } |
| 188 | |
| 189 | // Ensure the base cells exist |
| 190 | const hasCell0 = Array.from(nodesRoot.childNodes).some( |
| 191 | (node) => |
| 192 | node.nodeName === "mxCell" && |
| 193 | (node as Element).getAttribute("id") === "0", |
| 194 | ) |
| 195 | |
| 196 | const hasCell1 = Array.from(nodesRoot.childNodes).some( |
| 197 | (node) => |
| 198 | node.nodeName === "mxCell" && |
no outgoing calls
no test coverage detected