File size: 667 Bytes
4e039c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { useMemo } from 'react'
import { marked } from 'marked'
import DOMPurify from 'dompurify'

marked.setOptions({ gfm: true, breaks: true })

// 連結一律開新分頁
DOMPurify.addHook('afterSanitizeAttributes', (node) => {
  if (node.tagName === 'A') {
    node.setAttribute('target', '_blank')
    node.setAttribute('rel', 'noopener noreferrer')
  }
})

/** 模型輸出 → Markdown → HTML,經 DOMPurify 消毒後才插入,避免 XSS */
export default function Markdown({ text }) {
  const html = useMemo(() => DOMPurify.sanitize(marked.parse(String(text || ''))), [text])
  return <div className="md" dangerouslySetInnerHTML={{ __html: html }} />
}