import MarkdownIt from "markdown-it"; import hljs from "highlight.js"; import mila from "markdown-it-link-attributes"; import mdKatex from "@traptitech/markdown-it-katex"; /** * Markdown */ const MarkdownUtils = { mdi: null, mds: null, formatMsg: (text) => { const array = text.match(/]*?>/g); if (array) { array.some(res => { text = text.replace(res, `
${res}
`); }) } return text }, highlightBlock: (str, lang = '') => { return `
${lang}${$A.L('复制代码')}
${str}
` }, } export function MarkdownConver(text) { if (text === '...') { return '

 

' } if (MarkdownUtils.mdi === null) { MarkdownUtils.mdi = new MarkdownIt({ linkify: true, highlight(code, language) { const validLang = !!(language && hljs.getLanguage(language)) if (validLang) { const lang = language ?? '' return MarkdownUtils.highlightBlock(hljs.highlight(code, {language: lang}).value, lang) } return MarkdownUtils.highlightBlock(hljs.highlightAuto(code).value, '') }, }) MarkdownUtils.mdi.use(mila, {attrs: {target: '_blank', rel: 'noopener'}}) MarkdownUtils.mdi.use(mdKatex, {blockClass: 'katexmath-block rounded-md p-[10px]', errorColor: ' #cc0000'}) } return MarkdownUtils.formatMsg(MarkdownUtils.mdi.render(text)) } export function MarkdownPreview(text) { if (MarkdownUtils.mds === null) { MarkdownUtils.mds = MarkdownIt() } return MarkdownUtils.mds.render(text) } export function isMarkdownFormat(html) { if (html === '') { return false } if (/<\/(strong|s|em|u|ol|ul|li|blockquote|pre|img|a)>/i.test(html)) { return false } if (/]+?class="mention"[^>]*?>/i.test(html)) { return false } // let el = document.createElement('div') el.innerHTML = html const text = el.innerText el = null // if ( /(^|\s+)#+\s(.*)$/m.test(text) // 标题 || /\*\*(.*)\*\*/m.test(text) // 粗体 || /__(.*)__/m.test(text) // 粗体 || /\*(.*)\*/m.test(text) // 斜体 || /_(.*)_/m.test(text) // 斜体 || /~~(.*)~~/m.test(text) // 删除线 || /\[(.*?)\]\((.*?)\)/m.test(text) // 链接 || /!\[(.*?)\]\((.*?)\)/m.test(text) // 图片 || /`(.*?)`/m.test(text) // 行内代码 || /```([\s\S]*?)```/m.test(text) // 代码块 ) { return true } return false }