Starting with this code snippet: convert
utilizes svgInjector to start and terminate a resource.
export async function convert(
serializedSvg: string,
svgSourceId: string,
containerId: string
): Promise<string> {
const svgInjector = new SvgInjector(serializedSvg, containerId).inject();
if (!svgInjector.injectedElement) {
throw new Error("Svg not injected");
}
const doc = new TargetDocument({});
const xml = convertRecursively(
svgInjector.injectedElement,
doc,
{
svgSourceId,
}
);
svgInjector.remove();
return doc.saveXML();
}
Is there a way to refactor this to have a higher order function handle the initiation, provision, and destruction of the resource svgInjector.injectedElement
for the convert function?
UPDATE:
Below is a simple reproducible demo:
var svg = '<svg xmlns="http://www.w3.org/2000/svg"><text x="20" y="20">I am made available in DOM</text></svg>'
function convert(
serializedSvg,
containerId
) {
// make resource accessible (cross-cutting concern)
var container = document.getElementById(containerId);
var resource = new DOMParser().parseFromString(serializedSvg, "image/svg+xml").documentElement;
container.appendChild(resource);
// core conversion functionality manipulates the resource
console.log(resource.getBBox())
// clean up resource (cross-cutting concern)
resource.remove()
}
convert(svg, "container")
<!DOCTYPE html>
<html>
<head>
<title>Minimal</title>
</head>
<body>
<div id="container">
</div>
</body>
</html>
UPDATE 2
Presenting a TypeScript version based on the JavaScript from the previous update
var svg = '<svg xmlns="http://www.w3.org/2000/svg"><text x="20" y="20">I am made available in DOM</text></svg>'
function convert(
serializedSvg: string,
containerId: string
) {
// make resource accessible (cross-cutting concern)
var container = document.getElementById(containerId);
if (!(container instanceof HTMLDivElement)) {
throw new Error("Expected a div element")
}
var resource = new DOMParser().parseFromString(serializedSvg, "image/svg+xml").documentElement;
if (!(resource instanceof SVGSVGElement)) {
throw new Error("Expected an SVG element")
}
container.appendChild(resource);
// core conversion functionality manipulates the resource
console.log(resource.getBBox())
// clean up resource (cross-cutting concern)
resource.remove()
}
convert(svg, "container")