UNPKG

947 BPlain TextView Raw
1const getVectorDefinitions = (document: Document): Map<string, Element> => {
2 const map = new Map<string, Element>();
3
4 for (const definition of Array.from(document.querySelectorAll(`svg > defs > *[id!='']`))) {
5 const identifier = definition.getAttribute('id');
6 if (identifier) {
7 map.set(identifier, definition.children.item(0));
8 }
9 }
10
11 return map;
12};
13
14export const inlineVectorGraphics = (document: Document): void => {
15 const definitions = getVectorDefinitions(document);
16
17 const links = Array.from(document.querySelectorAll('svg > use'));
18
19 for (const link of links) {
20 const identifier = link.getAttribute('xlink:href');
21
22 const matchingDefinition = definitions.get(identifier.split(/[#\/]/g).pop());
23 if (matchingDefinition == null) {
24 throw new Error(`Cannot find matching SVG definition for ${identifier}`);
25 }
26
27 link.parentElement.replaceChild(matchingDefinition.cloneNode(true), link);
28 }
29};