Files
YGChatCS/uni_modules/zero-markdown-view/components/mp-html/markdown/index.js

54 lines
1.8 KiB
JavaScript

/**
* @fileoverview markdown 插件
* Include marked (https://github.com/markedjs/marked)
* Include github-markdown-css (https://github.com/sindresorhus/github-markdown-css)
*/
import marked from './marked.min'
let index = 0
function Markdown (vm) {
this.vm = vm
vm._ids = {}
}
Markdown.prototype.onUpdate = function (content) {
if (this.vm.markdown) {
// return marked(content)
// 先处理内容,确保只有双波浪号才被解析为删除线
// 使用临时占位符保护单个波浪号
let processedContent = content;
// 1. 先保护双波浪号删除线语法
processedContent = processedContent.replace(/~~([^~]+?)~~/g, '__STRIKETHROUGH_START__$1__STRIKETHROUGH_END__');
// 2. 将剩余的单个波浪号转换为HTML实体
processedContent = processedContent.replace(/~/g, '~');
// 3. 恢复双波浪号删除线语法
processedContent = processedContent.replace(/__STRIKETHROUGH_START__/g, '~~').replace(/__STRIKETHROUGH_END__/g, '~~');
return marked(processedContent, {
gfm: true,
breaks: false,
pedantic: false,
sanitize: false,
});
}
}
Markdown.prototype.onParse = function (node, vm) {
if (vm.options.markdown) {
// 中文 id 需要转换,否则无法跳转
if (vm.options.useAnchor && node.attrs && /[\u4e00-\u9fa5]/.test(node.attrs.id)) {
const id = 't' + index++
this.vm._ids[node.attrs.id] = id
node.attrs.id = id
}
if (node.name === 'p' || node.name === 'table' || node.name === 'tr' || node.name === 'th' || node.name === 'td' || node.name === 'blockquote' || node.name === 'pre' || node.name === 'code') {
node.attrs.class = `md-${node.name} ${node.attrs.class || ''}`
}
}
}
export default Markdown