You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
59 lines
1.7 KiB
TypeScript
59 lines
1.7 KiB
TypeScript
import { useContext, useEffect, useRef } from 'preact/hooks'
|
|
|
|
import { unified } from 'unified'
|
|
import remarkParse from 'remark-parse'
|
|
import remarkMath from 'remark-math'
|
|
import remarkRehype from 'remark-rehype'
|
|
import rehypeKatex from 'rehype-katex'
|
|
import rehypeStringify from 'rehype-stringify'
|
|
import { ServerContext } from '../hooks'
|
|
|
|
async function renderMarkdownAsync(source: string) {
|
|
return await unified()
|
|
.use(remarkParse)
|
|
.use(remarkMath)
|
|
.use(remarkRehype)
|
|
.use(rehypeKatex, { throwOnError: false, errorColor: '#c60' })
|
|
.use(rehypeStringify)
|
|
.process(source)
|
|
}
|
|
|
|
// function renderMarkdownSync(source: string): string {
|
|
// return unified()
|
|
// .use(remarkParse)
|
|
// .use(remarkMath)
|
|
// .use(remarkRehype)
|
|
// .use(rehypeKatex, { throwOnError: false, errorColor: '#c60' })
|
|
// .use(rehypeStringify)
|
|
// .processSync(source)
|
|
// .toString()
|
|
// }
|
|
|
|
export const Markdown = ({ source }: { source: string }) => {
|
|
// Magia nera per renderizzare il markdown lato server
|
|
//
|
|
// const isServer = useContext(ServerContext)
|
|
// if (isServer) {
|
|
// return (
|
|
// <div
|
|
// class="markdown"
|
|
// dangerouslySetInnerHTML={{
|
|
// __html: renderMarkdownSync(source),
|
|
// }}
|
|
// ></div>
|
|
// )
|
|
// }
|
|
|
|
const elementRef = useRef<HTMLDivElement>(null)
|
|
|
|
useEffect(() => {
|
|
renderMarkdownAsync(source).then(data => {
|
|
if (elementRef.current) {
|
|
elementRef.current.innerHTML = data.toString()
|
|
}
|
|
})
|
|
}, [source])
|
|
|
|
return <div class="markdown" ref={elementRef}></div>
|
|
}
|