/
MarkedPlugin.tsx
251 lines (215 loc) · 8.79 KB
/
MarkedPlugin.tsx
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
import * as fs from "fs";
import * as Path from "path";
import * as Marked from "marked";
import { Component, ContextAwareRendererComponent } from "../components";
import { RendererEvent, MarkdownEvent, PageEvent } from "../events";
import { Option, readFile, copySync, isFile, JSX, renderElement } from "../../utils";
import { highlight, isSupportedLanguage } from "../../utils/highlighter";
import type { Theme } from "shiki";
import { escapeHtml, getTextContent } from "../../utils/html";
import { anchorIcon } from "./default/partials/anchor-icon";
import type { DefaultThemeRenderContext } from "..";
/**
* Implements markdown and relativeURL helpers for templates.
* @internal
*/
@Component({ name: "marked" })
export class MarkedPlugin extends ContextAwareRendererComponent {
@Option("includes")
accessor includeSource!: string;
@Option("media")
accessor mediaSource!: string;
@Option("lightHighlightTheme")
accessor lightTheme!: Theme;
@Option("darkHighlightTheme")
accessor darkTheme!: Theme;
/**
* This needing to be here really feels hacky... probably some nicer way to do this.
* Revisit when adding support for arbitrary pages.
*/
private renderContext: DefaultThemeRenderContext = null!;
/**
* The path referenced files are located in.
*/
private includes?: string;
/**
* Path to the output media directory.
*/
private mediaDirectory?: string;
/**
* The pattern used to find references in markdown.
*/
private includePattern = /\[\[include:([^\]]+?)\]\]/g;
/**
* The pattern used to find media links.
*/
private mediaPattern = /media:\/\/([^ ")\]}]+)/g;
private sources?: { fileName: string; line: number }[];
private outputFileName?: string;
/**
* Create a new MarkedPlugin instance.
*/
override initialize() {
super.initialize();
this.listenTo(this.owner, MarkdownEvent.PARSE, this.onParseMarkdown);
}
/**
* Highlight the syntax of the given text using HighlightJS.
*
* @param text The text that should be highlighted.
* @param lang The language that should be used to highlight the string.
* @return A html string with syntax highlighting.
*/
public getHighlighted(text: string, lang?: string): string {
lang = lang || "typescript";
lang = lang.toLowerCase();
if (!isSupportedLanguage(lang)) {
// Extra newline because of the progress bar
this.application.logger.warn(`
Unsupported highlight language "${lang}" will not be highlighted. Run typedoc --help for a list of supported languages.
target code block :
\t${text.split("\n").join("\n\t")}
source files :${this.sources?.map((source) => `\n\t${source.fileName}`).join()}
output file :
\t${this.outputFileName}`);
return text;
}
return highlight(text, lang);
}
/**
* Parse the given markdown string and return the resulting html.
*
* @param text The markdown string that should be parsed.
* @returns The resulting html string.
*/
public parseMarkdown(text: string, page: PageEvent<any>, context: DefaultThemeRenderContext) {
this.renderContext = context;
if (this.includes) {
text = text.replace(this.includePattern, (_match, path) => {
path = Path.join(this.includes!, path.trim());
if (isFile(path)) {
const contents = readFile(path);
const event = new MarkdownEvent(MarkdownEvent.INCLUDE, page, contents, contents);
this.owner.trigger(event);
return event.parsedText;
} else {
this.application.logger.warn("Could not find file to include: " + path);
return "";
}
});
}
if (this.mediaDirectory) {
text = text.replace(this.mediaPattern, (match: string, path: string) => {
const fileName = Path.join(this.mediaDirectory!, path);
if (isFile(fileName)) {
return this.getRelativeUrl("media") + "/" + path;
} else {
this.application.logger.warn("Could not find media file: " + fileName);
return match;
}
});
}
const event = new MarkdownEvent(MarkdownEvent.PARSE, page, text, text);
this.owner.trigger(event);
this.renderContext = null!;
return event.parsedText;
}
/**
* Triggered before the renderer starts rendering a project.
*
* @param event An event object describing the current render operation.
*/
protected override onBeginRenderer(event: RendererEvent) {
super.onBeginRenderer(event);
Marked.marked.setOptions(this.createMarkedOptions());
delete this.includes;
if (this.includeSource) {
if (fs.existsSync(this.includeSource) && fs.statSync(this.includeSource).isDirectory()) {
this.includes = this.includeSource;
} else {
this.application.logger.warn("Could not find provided includes directory: " + this.includeSource);
}
}
if (this.mediaSource) {
if (fs.existsSync(this.mediaSource) && fs.statSync(this.mediaSource).isDirectory()) {
this.mediaDirectory = Path.join(event.outputDirectory, "media");
copySync(this.mediaSource, this.mediaDirectory);
} else {
this.mediaDirectory = undefined;
this.application.logger.warn("Could not find provided media directory: " + this.mediaSource);
}
}
}
/**
* Creates an object with options that are passed to the markdown parser.
*
* @returns The options object for the markdown parser.
*/
private createMarkedOptions(): Marked.marked.MarkedOptions {
const markedOptions = (this.application.options.getValue("markedOptions") ?? {}) as Marked.marked.MarkedOptions;
// Set some default values if they are not specified via the TypeDoc option
markedOptions.highlight ??= (text, lang) => this.getHighlighted(text, lang);
if (!markedOptions.renderer) {
markedOptions.renderer = new Marked.Renderer();
markedOptions.renderer.link = (href, title, text) => {
// Prefix the #anchor links `#md:`.
const target = href?.replace(/^#(?:md:)?(.+)/, "#md:$1") || undefined;
return renderElement(
<a href={target} title={title || undefined}>
<JSX.Raw html={text} />
</a>,
);
};
markedOptions.renderer.heading = (text, level, _, slugger) => {
const slug = slugger.slug(text);
// Prefix the slug with an extra `md:` to prevent conflicts with TypeDoc's anchors.
this.page!.pageHeadings.push({
link: `#md:${slug}`,
text: getTextContent(text),
level,
});
const H = `h${level}`;
return renderElement(
<>
<a id={`md:${slug}`} class="tsd-anchor" />
<H class="tsd-anchor-link">
<JSX.Raw html={text} />
{anchorIcon(this.renderContext, `md:${slug}`)}
</H>
</>,
);
};
markedOptions.renderer.code = renderCode;
}
markedOptions.mangle ??= false; // See https://github.com/TypeStrong/typedoc/issues/1395
return markedOptions;
}
/**
* Triggered when {@link MarkedPlugin} parses a markdown string.
*
* @param event
*/
onParseMarkdown(event: MarkdownEvent) {
event.parsedText = Marked.marked(event.parsedText);
}
}
// Basically a copy/paste of Marked's code, with the addition of the button
// https://github.com/markedjs/marked/blob/v4.3.0/src/Renderer.js#L15-L39
// cSpell:ignore infostring
function renderCode(this: Marked.marked.Renderer, code: string, infostring: string | undefined, escaped: boolean) {
const lang = (infostring || "").match(/\S*/)![0];
if (this.options.highlight) {
const out = this.options.highlight(code, lang);
if (out != null && out !== code) {
escaped = true;
code = out;
}
}
code = code.replace(/\n$/, "") + "\n";
if (!lang) {
return `<pre><code>${escaped ? code : escapeHtml(code)}</code><button>Copy</button></pre>\n`;
}
return `<pre><code class="${this.options.langPrefix + escapeHtml(lang)}">${
escaped ? code : escapeHtml(code)
}</code><button>Copy</button></pre>\n`;
}