2020-05-09 13:59:24 +08:00
|
|
|
import React, { useEffect, useRef } from "react";
|
|
|
|
|
import "katex/dist/katex.min.css";
|
2020-05-09 09:43:44 +08:00
|
|
|
|
2020-05-09 13:59:24 +08:00
|
|
|
import marked, { getTocContent, cleanToc } from "../common/marked";
|
2020-04-28 17:23:34 +08:00
|
|
|
|
2020-05-09 13:59:24 +08:00
|
|
|
let preRegex = /<pre[^>]*>/g;
|
2020-05-09 09:43:44 +08:00
|
|
|
|
2020-05-09 13:59:24 +08:00
|
|
|
export default ({ value = "", is_md = true, className, style = {} }) => {
|
|
|
|
|
let str = String(value);
|
|
|
|
|
let html = is_md ? marked(str) : value;
|
2020-05-09 09:43:44 +08:00
|
|
|
if (str.match(/\[TOC\]/)) {
|
2020-05-09 13:59:24 +08:00
|
|
|
html = html.replace("<p>[TOC]</p>", getTocContent());
|
|
|
|
|
cleanToc();
|
2020-05-09 09:43:44 +08:00
|
|
|
}
|
|
|
|
|
|
2020-05-09 13:59:24 +08:00
|
|
|
html = html.replace(/▁/g, "▁▁▁");
|
2020-07-31 11:21:02 +08:00
|
|
|
// html = html.replace(/\n/g,"<br />");
|
2020-05-09 13:59:24 +08:00
|
|
|
const el = useRef();
|
2020-04-28 17:23:34 +08:00
|
|
|
|
2020-05-09 09:43:44 +08:00
|
|
|
function onAncherHandler(e) {
|
2020-05-09 13:59:24 +08:00
|
|
|
let target = e.target;
|
|
|
|
|
if (target.tagName.toUpperCase() === "A") {
|
|
|
|
|
let ancher = target.getAttribute("href");
|
|
|
|
|
if (ancher.startsWith("#")) {
|
|
|
|
|
e.preventDefault();
|
|
|
|
|
let viewEl = document.getElementById(ancher.replace("#", ""));
|
2020-05-09 09:43:44 +08:00
|
|
|
if (viewEl) {
|
2020-05-09 13:59:24 +08:00
|
|
|
viewEl.parentNode.scrollTop = viewEl.offsetTop;
|
2020-05-09 09:43:44 +08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2020-04-28 17:23:34 +08:00
|
|
|
useEffect(() => {
|
|
|
|
|
if (el.current && html) {
|
2020-04-29 15:27:55 +08:00
|
|
|
if (html.match(preRegex)) {
|
2020-05-09 13:59:24 +08:00
|
|
|
window.PR.prettyPrint();
|
2020-04-28 17:23:34 +08:00
|
|
|
}
|
|
|
|
|
}
|
2020-05-09 09:43:44 +08:00
|
|
|
if (el.current) {
|
2020-05-09 13:59:24 +08:00
|
|
|
el.current.addEventListener("click", onAncherHandler);
|
2020-05-09 09:43:44 +08:00
|
|
|
return () => {
|
2020-05-09 13:59:24 +08:00
|
|
|
el.current.removeEventListener("click", onAncherHandler);
|
|
|
|
|
};
|
2020-05-09 09:43:44 +08:00
|
|
|
}
|
2020-05-09 13:59:24 +08:00
|
|
|
}, [html, el.current, onAncherHandler]);
|
2020-04-28 17:23:34 +08:00
|
|
|
|
2020-05-09 13:59:24 +08:00
|
|
|
return (
|
|
|
|
|
<div
|
|
|
|
|
ref={el}
|
|
|
|
|
style={style}
|
|
|
|
|
className={`${className ? className : ""} markdown-body`}
|
|
|
|
|
dangerouslySetInnerHTML={{ __html: html }}
|
|
|
|
|
></div>
|
|
|
|
|
);
|
|
|
|
|
};
|