-
Notifications
You must be signed in to change notification settings - Fork 0
/
documentEntriesPlugin.ts
66 lines (55 loc) · 1.56 KB
/
documentEntriesPlugin.ts
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
import * as fs from "node:fs";
const importRegex = /\/\/documentEntriesImport/;
const fileRegex = /\.(js|jsx|ts|tsx)$/;
export default function documentEntriesPlugin() {
return {
name: "transform-file",
enforce: "pre",
transform(src: string, id: string) {
if (fileRegex.test(id) && importRegex.test(src)) {
console.log("\nimported DocumentEntryButtons in " + id);
return {
code: src
.replace(
"//documentEntriesImport",
`import DocumentEntryButton, { ChildDocumentEntryButton, } from "../components/DocumentEntryButton";`
)
.replace("{/*documentEntriesPlace*/}", generateButtons()),
map: null,
};
}
},
};
}
function generateButtons(): string {
const data = fs.readFileSync("./documentEntries.json", "utf8");
const json = JSON.parse(data);
return generateButton(json, "DocumentEntryButton", "", 4);
}
function generateButton(
json: any,
elem: string,
basePath: string,
indent: number
): string {
let result = "";
if (json == null) return result;
json.forEach((entry: any) => {
let hasChildren = entry.children != undefined;
result = result.concat(
`<${elem} name="${entry.name}" path="${basePath}${
entry.path
}" indent={${indent}}>${
hasChildren
? generateButton(
entry.children,
"ChildDocumentEntryButton",
`${basePath}${entry.path}/`,
indent + 6
)
: ""
}</${elem}>`
);
});
return result;
}