-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathtransformsvg.ts
More file actions
48 lines (36 loc) · 1.29 KB
/
transformsvg.ts
File metadata and controls
48 lines (36 loc) · 1.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import { DOMParser, Element, Node } from "@xmldom/xmldom";
export function transformSVG(svgText: string): string {
if (svgText.startsWith('export default "')) {
svgText = JSON.parse(svgText.substring("export default ".length));
}
const doc = new DOMParser().parseFromString(svgText, "image/svg+xml");
const ret: string[] = [];
ret.push("(function buildSVG(parent) {");
ret.push("const builder = new DOMBuilder(parent);");
function traverse(node: Element): void {
const attributes: Record<string, string> = {};
for (const attr of Array.from(node.attributes)) {
attributes[attr.name] = attr.value;
}
ret.push(
`builder.openTag("${node.tagName}", ${JSON.stringify(attributes)}, undefined, "http://www.w3.org/2000/svg");`,
);
for (const child of Array.from(node.childNodes)) {
if (child.nodeType === Node.ELEMENT_NODE) {
traverse(child as Element);
} else if (
child.nodeType === Node.TEXT_NODE &&
child.textContent?.trim()
) {
ret.push(`builder.text(${JSON.stringify(child.textContent.trim())});`);
}
}
ret.push("builder.closeTag();");
}
const root = doc.documentElement;
if (root) {
traverse(root);
}
ret.push("return parent.firstElementChild; });");
return ret.join("\n");
}