import { getFilteredTags, getLinkTags, addLanguageClass, formatElements, linkTypeSpiltStr, getfilesize } from "@/assets/js/utils"; import marked from "marked"; import DOMPurify from "dompurify"; export default { methods: { async transferMarkdown(val) { this.rerender(); marked.setOptions({ breaks: true, gfm: true, langPrefix: "language-", highlight: function(code, lang, callback) { let html = require("highlight.js").highlightAuto(code).value; return html; } }); const str = val + ""; const html = marked(str); // 解析markdown const virtualDom = addLanguageClass(html); // 如果没指定语言,添加默认语言 const cleanHtml = DOMPurify.sanitize(virtualDom.innerHTML, { FORBID_TAGS: [ "style", "script", "select", "option", "textarea", "form", "button" ] }); // 去除标签 const filteredTags = getFilteredTags(html, cleanHtml); // 计算是否有标签被过滤 // 链接转换为卡片 // 获取标题列表 const { vDom, links, dirTags } = getLinkTags(this.id, cleanHtml); const { callUserList, userHtml } = formatElements(cleanHtml); // const videoHtml = await renderVideo(this.id, userHtml); this.$emit("callUserList", callUserList); this.$emit("getFilteredTags", filteredTags); this.$emit("update:html", userHtml); if (links.length) this.$emit("renderLinksHtml", { vDom, links }); if (dirTags.length) this.$emit("getDirTags", { vDom, dirTags }); }, rerender() { const _this = this; const renderer = { image(href, title, text) { if (href === null) { return text; } // ![file](...)渲染文件,只可以下载 if (text === "file") { const size = title.split(" ").pop(); const name = title .split(" ") .slice(0, -1) .join(" "); return `
${name} ${getfilesize(size)}
`; } if (text === "video") { return `

`; } // ![img](...)渲染图片 let out = '

' +
            text +
            '' + text + "\n" ); } // ignore IDs return "" + text + "\n"; }, link(href, title, text) { if (text && text.toLowerCase() === "toc") { return `

${href}

`; } if (!href && !title) return ""; if (href === null) { return text; } const linkTypeArr = href.split(linkTypeSpiltStr); const linkType = linkTypeArr[1]; href = linkTypeArr[0]; text = text.split(linkTypeSpiltStr)[0]; let invalidText = ""; if (href === text) { const invalidRule = /[)】}\]]*$/; if (href.match(invalidRule)) { invalidText = href.match(invalidRule)[0]; href = href.replace(invalidRule, ""); text = href; } } let out = '"; if (invalidText) { out += invalidText; } return out; }, text(text) { const newText = text .replace(/(\@\S+\s{0,1})/g, function(val) { const user = _this.getUserByName(val.slice(1).trim()); return `${val}`; }) // tab缩进 .replace(/^\s{2,3}(.+)/, function(val) { return `${val}`; }) .replace( /@?\[TOC\]/i, `

目录

` ); return newText; } }; marked.use({ renderer }); } } };