-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMarkdownPreview.js
86 lines (71 loc) · 2.02 KB
/
MarkdownPreview.js
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
import React from "react";
import marked from "marked";
import hljs from "highlight.js";
import PropTypes from "prop-types";
import createDOMPurify from "dompurify";
import { JSDOM } from "jsdom";
import { substitutePrefixes } from "./api";
// Initializing DOM Purify
const window = new JSDOM("").window;
const DOMPurify = createDOMPurify(window);
function MarkdownPreview({
markedOptions,
value,
className,
set,
titleMessage,
}) {
let options = {};
if (markedOptions) {
options = markedOptions;
options = {
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: true,
smartLists: true,
smartypants: false,
langPrefix: "hljs ",
...options
};
if (typeof hljs !== "undefined") {
options = {
...options,
highlight: (code, lang) => {
if (!!(lang && hljs.getLanguage(lang))) {
return hljs.highlight(lang, code).value;
}
return code;
}
};
}
marked.setOptions(options);
}
const renderer = new marked.Renderer();
// Remove null title problem when it is undefined by giving default value
// and you can define shortcuts for <a> in markdown
renderer.link = (href, title, text) => {
const lastHref = substitutePrefixes(href)(set);
return `<a target="_blank" rel="noopener noreferrer" href="${lastHref}" title="${
title === null ? `${titleMessage} ${lastHref}` : title
}" >${text}</a>`;
};
const html = DOMPurify.sanitize(marked(value || "", { renderer }));
return (
<div dangerouslySetInnerHTML={{ __html: html }} className={className} />
);
}
MarkdownPreview.propTypes = {
value: PropTypes.string,
className: PropTypes.string,
markedOptions: PropTypes.object,
set: PropTypes.array,
titleMessage: PropTypes.string
};
MarkdownPreview.defaultProps = {
value: "", // "**This is default value. Write Your own markdown**",
set: [["s-", "https://"]],
titleMessage: "Click it will open a new tab at"
};
export default MarkdownPreview;