-
Notifications
You must be signed in to change notification settings - Fork 112
/
Copy pathmarkdown.ts
89 lines (82 loc) · 2.23 KB
/
markdown.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
/**
* Markdown module.
*
* This deals with creating markdown content. It is relatively simple so not worth relying on a
* library for.
*/
import markdownIt from "markdown-it";
import { IMdImage, IMdImageWithLink } from "./markdown.d";
const md = new markdownIt({ html: true });
/**
* Create Markdown link code.
*
* TODO: Use object destructuring.
*/
export function mdLink(altText: string, linkTarget: string, hoverTitle = "") {
if (hoverTitle) {
linkTarget = `${linkTarget} "${hoverTitle}"`;
}
return `[${altText}](${linkTarget})`;
}
/**
* Create Markdown image code.
*
* @param altText Fallback text.
* @param imageTarget Path or URL of the image to show.
* @param hoverTitle Optional title of the image, to display on hover over.
* e.g. "Go to website".
*/
export function mdImage({ altText, imageTarget, hoverTitle }: IMdImage) {
if (hoverTitle) {
imageTarget = `${imageTarget} "${hoverTitle}"`;
}
return `![${altText}](${imageTarget})`;
}
/**
* Create Markdown image code, with an external link.
*
* This performs no encoding - the inputs should be encoded already to be a URL
* without spaces and to be a valid URL for shields.io API.
*
* @param altText Fallback text.
* @param imageTarget Path or URL of the image to show.
* @param hoverTitle Optional title of the image, to display on hover over.
* e.g. "Go to website".
* @param linkTarget Path or URL destination for when the image is clicked.
*/
export function mdImageWithLink({
altText,
imageTarget,
hoverTitle,
linkTarget,
}: IMdImageWithLink) {
const image = mdImage({ altText, imageTarget });
if (linkTarget) {
return mdLink(image, linkTarget, hoverTitle);
}
return image;
}
/**
* Markdown to HTML.
*
* Render Markdown code as HTML code.
*/
export function mdToHTML(value: string): string {
return md.render(value);
}
/**
* Clean HTML.
*
* Expect HTML code that was rendered from Markdown and convert it into more
* typical and readable HTML.
*/
export function cleanHtml(value: String) {
return value
.replaceAll("<p>", "")
.replaceAll("</p>", "\n")
.replaceAll("<em>", "<i>")
.replaceAll("</em>", "</i>")
.replaceAll("<strong>", "<b>")
.replaceAll("</strong>", "</b>")
.replaceAll("&", "&");
}