Files
aichat/src/utils/markdown.ts
T
2026-11-05 10:46:36 +08:00

127 lines
4.7 KiB
TypeScript
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 MarkdownIt from 'markdown-it'
// 界面侧兜底:禁止任何代码展示(模型侧行为准则已禁止输出代码,这里防漏网)。
// - 围栏代码块(``` / ~~~)与缩进代码块:整块不渲染,用户看不到任何代码
// - 行内 code:只保留文字、不输出 <code> 标签 —— 行内片段通常是字段名等,
// 删掉文字会伤句子可读性,去掉「代码」外观即可
const markdown: MarkdownIt = new MarkdownIt({
html: false,
linkify: true,
breaks: true,
typographer: true,
})
// 围栏代码块(``` / ~~~):整块不输出到 html
markdown.renderer.rules.fence = () => ''
// 缩进代码块:同样属于代码展示,一并整块丢弃
markdown.renderer.rules.code_block = () => ''
// 行内 code:只保留转义后的文字,不包裹任何标签
markdown.renderer.rules.code_inline = (tokens, index) => markdown.utils.escapeHtml(tokens[index].content)
const defaultLinkOpenRenderer = markdown.renderer.rules.link_open
markdown.renderer.rules.link_open = (tokens, index, options, env, self) => {
const token = tokens[index]
const hrefIndex = token.attrIndex('href')
if (hrefIndex >= 0) {
token.attrSet('target', '_blank')
token.attrSet('rel', 'noopener noreferrer')
}
return defaultLinkOpenRenderer ? defaultLinkOpenRenderer(tokens, index, options, env, self) : self.renderToken(tokens, index, options)
}
markdown.renderer.rules.table_open = () => '<div class="md-table-wrapper"><table>\n'
markdown.renderer.rules.table_close = () => '</table></div>\n'
// 裸 JSON 段落:模型不加围栏直接输出一段 JSON 时,会作为普通段落漏出来,等于代码展示漏网。
// 判定是精确的:整段文本 trim 后能被 JSON.parse 成功,且解析结果是**对象或数组** ⇒ 判定为 json ⇒ 整段丢弃。
// 纯标量(数字 / 字符串 / 布尔 / null)虽然也能 parse 成功,但那是正常回复内容(例如模型答「42」),必须保留。
// 不做任何「像代码」的模糊猜测(不按 { / [ 出现次数、不按行数猜);
// 只处理顶层独立段落 —— 列表项 / 引用里的段落一律不动,保证列表、引用渲染不受影响。
function isBareJson(text: string): boolean {
const trimmed = text.trim()
if (!trimmed) return false
try {
const parsed: unknown = JSON.parse(trimmed)
return typeof parsed === 'object' && parsed !== null
} catch {
return false
}
}
// 从原始 markdown 文本里剔除「整段都是裸 JSON」的顶层段落。
// 界面渲染(renderMarkdown)与「复制整条消息」共用这一个判定,保证两边口径一致。
export function stripBareJsonBlocks(content = ''): string {
if (!content) return ''
const tokens = markdown.parse(content, {})
const lines = content.split(/\r?\n/)
const dropLines = new Set<number>()
let depth = 0
for (let i = 0; i < tokens.length; i++) {
const token = tokens[i]
// 顶层段落结构固定为 paragraph_open → inline → paragraph_close;
// inline token 的 content 就是该段未解析的原始文本。
if (token.type === 'paragraph_open' && depth === 0 && token.map) {
const inline = tokens[i + 1]
if (inline?.type === 'inline' && isBareJson(inline.content)) {
for (let line = token.map[0]; line < token.map[1]; line++) {
dropLines.add(line)
}
}
}
// 段落本身不算容器层级;其余 *_open / *_close 记录是否处于列表、引用等容器内
if (token.type !== 'paragraph_open' && token.type !== 'paragraph_close') {
if (token.type.endsWith('_open')) depth++
else if (token.type.endsWith('_close')) depth--
}
}
if (dropLines.size === 0) return content
return lines.filter((_, index) => !dropLines.has(index)).join('\n').trim()
}
// 从原始 markdown 文本里剔除围栏代码块(含未闭合的尾部围栏),供「复制整条消息」用,
// 保证复制到的文本与界面所见一致(不含代码)。
export function stripFencedCode(content = ''): string {
if (!content) return ''
const lines = content.split(/\r?\n/)
const kept: string[] = []
let fenceChar = ''
for (const line of lines) {
const fenceMatch = /^\s*(`{3,}|~{3,})/.exec(line)
if (!fenceChar) {
if (fenceMatch) {
fenceChar = fenceMatch[1][0]
} else {
kept.push(line)
}
continue
}
// 围栏内:遇到同字符的闭合围栏则结束,其余行一律丢弃
if (fenceMatch && fenceMatch[1][0] === fenceChar) {
fenceChar = ''
}
}
return kept.join('\n').trim()
}
export function renderMarkdown(content = ''): string {
// 先剔除裸 JSON 段落再渲染,界面与复制共用同一判定
return markdown.render(stripBareJsonBlocks(content))
}