forked from OnedocLabs/react-print-pdf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.ts
103 lines (83 loc) · 2.58 KB
/
utils.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
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
import * as ts from "typescript";
import { DocConfig, ExtendedDocConfig } from "./types";
import * as prettier from "prettier";
export const formatCamelCaseToTitle = (str: string) => {
// Convert camelCase to Title Case with spaces
return str
.replace(/([A-Z])/g, " $1")
.replace(/^./, (str) => str.toUpperCase());
};
const listProperties = (node: ts.ObjectLiteralExpression) => {
const properties = {};
node.properties.forEach((property) => {
if (ts.isPropertyAssignment(property)) {
properties[property.name.getText()] = property.initializer;
}
});
return properties;
};
const extractTemplates = (node) => {
const templates = {};
const components = listProperties(
listProperties(node)["components"] as ts.ObjectLiteralExpression
);
Object.entries(components).forEach(([componentName, value]) => {
templates[componentName] = {};
let examples = {};
try {
examples = listProperties(
listProperties(value as ts.ObjectLiteralExpression)[
"examples"
] as ts.ObjectLiteralExpression
);
} catch (e) {}
Object.entries(examples).forEach(([exampleName, value]) => {
const template = listProperties(value as ts.ObjectLiteralExpression)[
"template"
];
templates[componentName][exampleName] = template.getText();
});
});
return templates;
};
export const getTemplateContents = (filePath: string) => {
// Load the file contents to the typescript ast
const sourceFile = ts.createSourceFile(
filePath,
ts.sys.readFile(filePath) || "",
ts.ScriptTarget.Latest,
true
);
let templates = {};
sourceFile.forEachChild((node) => {
if (ts.isVariableStatement(node)) {
node.declarationList.declarations.forEach((declaration) => {
if (declaration.name.getText() === "__docConfig") {
templates = extractTemplates(declaration.initializer);
}
});
}
});
return templates;
};
export const mergeTemplateInfo = (
docInfo: DocConfig,
templates: any
): ExtendedDocConfig => {
Object.entries(docInfo.components).forEach(([componentName, value]) => {
Object.entries(value.examples || {}).forEach(([exampleName, example]) => {
// @ts-ignore
example.templateString = templates[componentName][exampleName];
});
});
return docInfo as ExtendedDocConfig;
};
export const formatSnippet = (snippet: string) => {
return prettier.format(snippet, {
parser: "typescript",
});
};
export const safePropType = (str: string) => {
// Replace all " by ' to avoid conflicts with markdown
return str.replace(/"/g, "'");
};