flat:AI+
This commit is contained in:
57
utils/markdownParser.js
Normal file
57
utils/markdownParser.js
Normal file
@@ -0,0 +1,57 @@
|
||||
import MarkdownIt from '@/lib/markdown-it.min.js';
|
||||
// import MarkdownIt from '@/lib/markdown-it.esm.js'
|
||||
import hljs from "@/lib/highlight/highlight-uni.min.js";
|
||||
import parseHtml from '@/lib/html-parser.js';
|
||||
// import DOMPurify from '@/lib/dompurify@3.2.4es.js';
|
||||
|
||||
export let codeDataList = []
|
||||
|
||||
const md = new MarkdownIt({
|
||||
html: true, // 允许 HTML 标签
|
||||
linkify: true, // 自动解析 URL
|
||||
typographer: true, // 美化标点符号
|
||||
tables: true,
|
||||
breaks: true, // 让 \n 自动换行
|
||||
langPrefix: 'language-', // 代码高亮前缀
|
||||
// 如果结果以 <pre ... 开头,内部包装器则会跳过。
|
||||
highlight: function(str, lang) {
|
||||
let preCode = ""
|
||||
try {
|
||||
preCode = hljs.highlightAuto(str).value
|
||||
} catch (err) {
|
||||
preCode = markdownIt.utils.escapeHtml(str);
|
||||
}
|
||||
|
||||
// 以换行进行分割
|
||||
// 按行拆分代码
|
||||
const lines = preCode.split(/\n/).slice(0, -1);
|
||||
const html = lines
|
||||
.map((line, index) =>
|
||||
line ?
|
||||
`<li><span class="line-num" data-line="${index + 1}"></span>${line}</li>` :
|
||||
''
|
||||
)
|
||||
.join('');
|
||||
|
||||
// 代码复制功能
|
||||
const cacheIndex = codeDataList.length;
|
||||
codeDataList.push(str);
|
||||
return `
|
||||
<div class="code-container">
|
||||
<div class="code-header">
|
||||
<span class="lang-label">${lang || 'plaintext'}</span>
|
||||
<a class="copy-btn" data-copy-index="${cacheIndex}">复制代码</a>
|
||||
</div>
|
||||
<pre class="hljs"><code><ol>${html}</ol></code></pre>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
})
|
||||
|
||||
export function parseMarkdown(content) {
|
||||
if (!content) {
|
||||
return //处理特殊情况,比如网络异常导致的响应的 content 的值为空
|
||||
}
|
||||
const unsafeHtml = md.render(content || '')
|
||||
return unsafeHtml
|
||||
}
|
Reference in New Issue
Block a user