forgeplus-react/src/components/render-html.jsx

67 lines
2.1 KiB
React
Raw Normal View History

2020-08-12 18:13:18 +08:00
import React, { useEffect, useRef, useMemo } from "react";
2020-05-09 13:59:24 +08:00
import "katex/dist/katex.min.css";
2020-08-12 18:13:18 +08:00
import { renderToString } from 'katex';
import marked, { getTocContent, cleanToc, getMathExpressions, resetMathExpressions } from "../common/marked";
import 'code-prettify'
2020-05-09 09:43:44 +08:00
2020-08-12 18:13:18 +08:00
const preRegex = /<pre[^>]*>/g
2020-04-28 17:23:34 +08:00
2020-08-12 18:13:18 +08:00
function _unescape(str) {
let div = document.createElement('div')
div.innerHTML = str
return div.childNodes.length === 0 ? "" : div.childNodes[0].nodeValue;
}
2020-05-09 09:43:44 +08:00
2020-08-12 18:13:18 +08:00
export default ({ value = '', className, style = {} }) => {
let str = String(value)
2020-05-09 09:43:44 +08:00
2020-08-12 18:13:18 +08:00
const html = useMemo(() => {
let rs = marked(str)
const math_expressions = getMathExpressions()
if (str.match(/\[TOC\]/)) {
rs = rs.replace("<p>[TOC]</p>", getTocContent())
cleanToc()
}
rs = rs.replace(/(__special_katext_id_\d+__)/g, (_match, capture) => {
const { type, expression } = math_expressions[capture]
return renderToString(_unescape(expression), { displayMode: type === 'block', throwOnError: false, output: 'html' })
})
rs = rs.replace(/▁/g, "▁▁▁")
resetMathExpressions()
return rs
}, [str])
2020-04-28 17:23:34 +08:00
2020-08-12 18:13:18 +08:00
const el = useRef()
2020-05-09 09:43:44 +08:00
function onAncherHandler(e) {
2020-08-12 18:13:18 +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-08-12 18:13:18 +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-08-12 18:13:18 +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-08-12 18:13:18 +08:00
el.current.addEventListener('click', onAncherHandler)
2020-05-09 09:43:44 +08:00
return () => {
2020-08-12 18:13:18 +08:00
el.current.removeEventListener('click', onAncherHandler)
resetMathExpressions()
cleanToc()
}
2020-05-09 09:43:44 +08:00
}
2020-08-12 18:13:18 +08:00
}, [html, el.current, onAncherHandler])
2020-04-28 17:23:34 +08:00
2020-08-12 18:13:18 +08:00
return (<div ref={el} style={style} className={`${className ? className : ''} markdown-body`} dangerouslySetInnerHTML={{ __html: html }}></div>)
}