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

48 lines
1.4 KiB
React
Raw Normal View History

2020-04-28 17:23:34 +08:00
import React, { useEffect, useRef } from 'react'
import 'katex/dist/katex.min.css';
2020-05-09 09:43:44 +08:00
import marked, { getTocContent, cleanToc } from '../common/marked'
2020-04-28 17:23:34 +08:00
let preRegex = /<pre[^>]*>/g
2020-05-09 09:43:44 +08:00
2020-04-28 17:23:34 +08:00
export default ({ value = '', is_md = true, className, style = {} }) => {
2020-05-09 09:43:44 +08:00
let str = String(value)
let html = is_md ? marked(str) : value
if (str.match(/\[TOC\]/)) {
html = html.replace("<p>[TOC]</p>", getTocContent())
cleanToc()
}
2020-04-29 15:27:55 +08:00
html = html.replace(/▁/g, "▁▁▁")
2020-04-28 17:23:34 +08:00
const el = useRef()
2020-05-09 09:43:44 +08:00
function onAncherHandler(e) {
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('#', ''))
if (viewEl) {
viewEl.parentNode.scrollTop = viewEl.offsetTop
}
}
}
}
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-04-28 17:23:34 +08:00
window.PR.prettyPrint()
}
}
2020-05-09 09:43:44 +08:00
if (el.current) {
el.current.addEventListener('click', onAncherHandler)
return () => {
el.current.removeEventListener('click', onAncherHandler)
}
}
}, [html, el.current, onAncherHandler])
2020-04-28 17:23:34 +08:00
2020-05-09 09:43:44 +08:00
return (<div ref={el} style={style} className={`${className ? className : ''} markdown-body`} dangerouslySetInnerHTML={{ __html: html }}></div>)
2020-04-28 17:23:34 +08:00
}