-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
106 lines (78 loc) · 2.63 KB
/
main.js
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import { join } from "https://deno.land/[email protected]/path/mod.ts";
import { stringToDocument } from "./main/_exports.js";
/**
* @typedef {import("https://deno.land/x/[email protected]/server.ts").Plugin} Plugin
*/
const {
cwd,
readTextFile
} = Deno;
/**
* The SVG inject plugin.
*
* @param {object} [options] - The options object.
* @param {string} [options.staticFolder] - The static folder path.
*
* @returns {Plugin} - The plugin.
*/
const plugin = ({ staticFolder = "./static" } = {}) => ({
name: "svg-inject",
renderAsync: async (context) => {
const staticFolderPath = join(cwd(), staticFolder);
const result = await context.renderAsync();
const document = stringToDocument(result.htmlText);
if (document) {
const imgSvgElements = [...document.querySelectorAll("img[src*=\".svg\"]")];
for (const [index, imgSvgElement] of imgSvgElements.entries()) {
if (imgSvgElement.hasAttribute("src")) {
const imgSource = imgSvgElement.getAttribute("src");
const oldAttributes = [...imgSvgElement.attributes];
if (imgSource !== null) {
let svg;
try {
const svgUrl = new URL(imgSource);
svg = await (await fetch(svgUrl)).text();
}
catch {
const imgSourceFilePath = join(staticFolderPath, imgSource);
const { pathname: imgSourceFilePathCleaned } = new URL(imgSourceFilePath, "http://localhost:8000");
svg = await readTextFile(imgSourceFilePathCleaned);
}
const svgDocument = stringToDocument(svg);
const elementsWithId = [...svgDocument.querySelectorAll("[id]")];
const idsMap = new Map();
for (const elementWithId of elementsWithId) {
const id = elementWithId.getAttribute("id");
if (id !== null) {
const newId = `${id}-inject${index + 1}`;
idsMap.set(id, newId);
elementWithId.setAttribute("id", newId);
}
}
for (const oldAttribute of oldAttributes) {
if (oldAttribute.name !== "src") {
const svgDocumentSvgElement = svgDocument.querySelector("svg");
if (svgDocumentSvgElement) {
svgDocumentSvgElement
.setAttribute(oldAttribute.name, oldAttribute.value);
}
}
}
let newSvgText = svgDocument.documentElement.outerHTML
.trim()
.replace(/^<html><head><\/head><body>(?<svg>(?:.|\n)*?)<\/body><\/html>$/u, "$<svg>");
for (const [id, newId] of idsMap) {
newSvgText = newSvgText.replaceAll(`#${id}`, `#${newId}`);
}
imgSvgElement.outerHTML = newSvgText;
}
}
}
return {
htmlText: document.documentElement.outerHTML
};
}
return {};
}
});
export default plugin;