-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
Copy pathMarkdownRenderer.ts
230 lines (198 loc) · 6.86 KB
/
MarkdownRenderer.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
import { marked } from 'marked';
import { highlight, safeSlugify, unescapeHTMLChars } from '../utils';
import { RedocNormalizedOptions } from './RedocNormalizedOptions';
import type { MarkdownHeading, MDXComponentMeta } from './types';
const renderer = new marked.Renderer();
marked.setOptions({
renderer,
highlight: (str, lang) => {
return highlight(str, lang);
},
});
export const LEGACY_REGEXP = '^ {0,3}<!-- ReDoc-Inject:\\s+?<({component}).*?/?>\\s+?-->\\s*$';
// prettier-ignore
export const MDX_COMPONENT_REGEXP = '(?:^ {0,3}<({component})([\\s\\S]*?)>([\\s\\S]*?)</\\2>' // with children
+ '|^ {0,3}<({component})([\\s\\S]*?)(?:/>|\\n{2,}))'; // self-closing
export const COMPONENT_REGEXP = '(?:' + LEGACY_REGEXP + '|' + MDX_COMPONENT_REGEXP + ')';
export function buildComponentComment(name: string) {
return `<!-- ReDoc-Inject: <${name}> -->`;
}
export class MarkdownRenderer {
static containsComponent(rawText: string, componentName: string) {
const compRegexp = new RegExp(COMPONENT_REGEXP.replace(/{component}/g, componentName), 'gmi');
return compRegexp.test(rawText);
}
static getTextBeforeHading(md: string, heading: string): string {
const headingLinePos = md.search(new RegExp(`^##?\\s+${heading}`, 'm'));
if (headingLinePos > -1) {
return md.substring(0, headingLinePos);
}
return md;
}
headings: MarkdownHeading[] = [];
currentTopHeading: MarkdownHeading;
public parser: marked.Parser; // required initialization, `parser` is used by `marked.Renderer` instance under the hood
private headingEnhanceRenderer: marked.Renderer;
private originalHeadingRule: typeof marked.Renderer.prototype.heading;
constructor(public options?: RedocNormalizedOptions, public parentId?: string) {
this.parentId = parentId;
this.parser = new marked.Parser();
this.headingEnhanceRenderer = new marked.Renderer();
this.originalHeadingRule = this.headingEnhanceRenderer.heading.bind(
this.headingEnhanceRenderer,
);
this.headingEnhanceRenderer.heading = this.headingRule;
}
saveHeading(
name: string,
level: number,
container: MarkdownHeading[] = this.headings,
parentId?: string,
): MarkdownHeading {
name = unescapeHTMLChars(name);
const item: MarkdownHeading = {
id: parentId
? `${parentId}/${safeSlugify(name)}`
: `${this.parentId || 'section'}/${safeSlugify(name)}`,
name,
level,
items: [],
};
container.push(item);
return item;
}
flattenHeadings(container?: MarkdownHeading[]): MarkdownHeading[] {
if (container === undefined) {
return [];
}
const res: MarkdownHeading[] = [];
for (const heading of container) {
res.push(heading);
res.push(...this.flattenHeadings(heading.items));
}
return res;
}
attachHeadingsDescriptions(rawText: string) {
const buildRegexp = (heading: MarkdownHeading) => {
return new RegExp(
`##?\\s+${heading.name.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')}\s*(\n|\r\n|$|\s*)`,
);
};
const flatHeadings = this.flattenHeadings(this.headings);
if (flatHeadings.length < 1) {
return;
}
let prevHeading = flatHeadings[0];
let prevRegexp = buildRegexp(prevHeading);
let prevPos = rawText.search(prevRegexp);
for (let i = 1; i < flatHeadings.length; i++) {
const heading = flatHeadings[i];
const regexp = buildRegexp(heading);
const currentPos = rawText.substr(prevPos + 1).search(regexp) + prevPos + 1;
prevHeading.description = rawText
.substring(prevPos, currentPos)
.replace(prevRegexp, '')
.trim();
prevHeading = heading;
prevRegexp = regexp;
prevPos = currentPos;
}
prevHeading.description = rawText.substring(prevPos).replace(prevRegexp, '').trim();
}
headingRule = (
text: string,
level: 1 | 2 | 3 | 4 | 5 | 6,
raw: string,
slugger: marked.Slugger,
): string => {
if (level === 1) {
this.currentTopHeading = this.saveHeading(text, level);
} else if (level === 2) {
this.saveHeading(
text,
level,
this.currentTopHeading && this.currentTopHeading.items,
this.currentTopHeading && this.currentTopHeading.id,
);
}
return this.originalHeadingRule(text, level, raw, slugger);
};
renderMd(rawText: string, extractHeadings: boolean = false): string {
const opts = extractHeadings ? { renderer: this.headingEnhanceRenderer } : undefined;
const res = marked(rawText.toString(), opts);
return res;
}
extractHeadings(rawText: string): MarkdownHeading[] {
this.renderMd(rawText, true);
this.attachHeadingsDescriptions(rawText);
const res = this.headings;
this.headings = [];
return res;
}
// regexp-based 👎: remark is slow and too big so for now using marked + regexps soup
renderMdWithComponents(rawText: string): Array<string | MDXComponentMeta> {
const components = this.options && this.options.allowedMdComponents;
if (!components || Object.keys(components).length === 0) {
return [this.renderMd(rawText)];
}
const names = Object.keys(components).join('|');
const componentsRegexp = new RegExp(COMPONENT_REGEXP.replace(/{component}/g, names), 'mig');
const htmlParts: string[] = [];
const componentDefs: MDXComponentMeta[] = [];
let match = componentsRegexp.exec(rawText);
let lasxtIdx = 0;
while (match) {
htmlParts.push(rawText.substring(lasxtIdx, match.index));
lasxtIdx = componentsRegexp.lastIndex;
const compName = match[1] || match[2] || match[5];
const componentMeta = components[compName];
const props = match[3] || match[6];
const children = match[4];
if (componentMeta) {
componentDefs.push({
component: componentMeta.component,
propsSelector: componentMeta.propsSelector,
props: { ...parseProps(props), ...componentMeta.props, children },
});
}
match = componentsRegexp.exec(rawText);
}
htmlParts.push(rawText.substring(lasxtIdx));
const res: any[] = [];
for (let i = 0; i < htmlParts.length; i++) {
const htmlPart = htmlParts[i];
if (htmlPart) {
res.push(this.renderMd(htmlPart));
}
if (componentDefs[i]) {
res.push(componentDefs[i]);
}
}
return res;
}
}
function parseProps(props: string): object {
if (!props) {
return {};
}
const regex = /([\w-]+)\s*=\s*(?:{([^}]+?)}|"([^"]+?)")/gim;
const parsed = {};
let match;
// tslint:disable-next-line
while ((match = regex.exec(props)) !== null) {
if (match[3]) {
// string prop match (in double quotes)
parsed[match[1]] = match[3];
} else if (match[2]) {
// jsx prop match (in curly braces)
let val;
try {
val = JSON.parse(match[2]);
} catch (e) {
/* noop */
}
parsed[match[1]] = val;
}
}
return parsed;
}