Files
cwd/docs/widget/src/utils/markdown.js
anghunk 969d9019fb feat(widget): 为评论编辑器添加Markdown预览功能
- 引入 marked 和 DOMPurify 依赖以支持 Markdown 解析与安全渲染
- 在评论表单和回复编辑器中添加预览按钮,支持实时预览
- 新增预览区域样式,优化操作按钮布局间距
- 修复表单状态初始化问题,确保预览功能稳定
2026-01-27 17:41:44 +08:00

35 lines
1.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { marked } from 'marked';
import DOMPurify from 'dompurify';
// 配置 marked
try {
marked.setOptions({
gfm: true, // 启用 GitHub Flavored Markdown
breaks: true, // 启用换行符转 <br>
});
} catch (e) {
console.error('Failed to configure marked:', e);
}
/**
* 渲染 Markdown 为 HTML并进行净化
* @param {string} content Markdown 内容
* @returns {string} 净化后的 HTML
*/
export function renderMarkdown(content) {
if (!content) return '';
try {
const html = marked.parse(content);
// marked.parse can return a Promise if async is enabled, but we are using sync mode
// Just in case, handle potential Promise (though unlikely with current config)
if (html instanceof Promise) {
console.warn('marked.parse returned a Promise. Async markdown rendering is not fully supported in this sync flow.');
return '';
}
return DOMPurify.sanitize(html);
} catch (error) {
console.error('Markdown rendering error:', error);
return DOMPurify.sanitize(content); // Fallback to plain text (sanitized)
}
}