version: 2
This commit is contained in:
+98
-120
@@ -1,131 +1,24 @@
|
||||
import MarkdownIt from 'markdown-it'
|
||||
import hljs from 'highlight.js/lib/core'
|
||||
import javascript from 'highlight.js/lib/languages/javascript'
|
||||
import json from 'highlight.js/lib/languages/json'
|
||||
import 'highlight.js/styles/github.css'
|
||||
|
||||
hljs.registerLanguage('javascript', javascript)
|
||||
hljs.registerLanguage('json', json)
|
||||
|
||||
const CODE_LANGUAGES = ['sql', 'javascript', 'typescript', 'java', 'python', 'json', 'html', 'css', 'bash', 'shell', 'vue', 'xml', 'yaml', 'markdown']
|
||||
const LANGUAGE_ALIASES: Record<string, string> = {
|
||||
js: 'javascript',
|
||||
jsx: 'javascript',
|
||||
ts: 'typescript',
|
||||
tsx: 'typescript',
|
||||
sh: 'bash',
|
||||
shell: 'bash',
|
||||
zsh: 'bash',
|
||||
yml: 'yaml',
|
||||
md: 'markdown',
|
||||
text: 'plaintext',
|
||||
}
|
||||
const CODE_FENCE_PATTERN = /```[\s\S]*?```/
|
||||
const CODE_FENCE_LINE_PATTERN = /^```/gm
|
||||
const SQL_KEYWORDS = /\b(select|insert|update|delete|create|alter|drop|from|where|join|group by|order by|limit)\b/i
|
||||
const CODE_STRUCTURE_PATTERN = /[{};<>]|\b(function|const|let|var|public|private|class|interface|return|import|export|try|catch|async|await)\b/
|
||||
|
||||
function escapeCodeHtml(code: string): string {
|
||||
return code
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''')
|
||||
}
|
||||
|
||||
function escapeAttribute(value: string): string {
|
||||
return value
|
||||
.replace(/&/g, '&')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
}
|
||||
|
||||
function normalizeLanguage(language = ''): string {
|
||||
const normalized = language.trim().toLowerCase()
|
||||
return LANGUAGE_ALIASES[normalized] || normalized || 'plaintext'
|
||||
}
|
||||
|
||||
function getDisplayLanguage(language: string): string {
|
||||
return language === 'plaintext' ? 'text' : language
|
||||
}
|
||||
|
||||
function detectCodeLanguage(content: string): string {
|
||||
const normalized = content.trim().toLowerCase()
|
||||
|
||||
if (SQL_KEYWORDS.test(normalized)) return 'sql'
|
||||
if (/^\s*[{[]/.test(content) && /[}\]]\s*$/.test(content)) return 'json'
|
||||
if (/<[a-z][\s\S]*?>/i.test(content)) return 'html'
|
||||
if (/\b(interface|type|implements|readonly|enum)\b/.test(normalized)) return 'typescript'
|
||||
if (/\b(system\.out\.println|public static void main|new \w+\()/i.test(content)) return 'java'
|
||||
if (/\b(def |import |from .+ import |print\()/i.test(content)) return 'python'
|
||||
if (/\b(const|let|var|function|=>|console\.log)\b/.test(normalized)) return 'javascript'
|
||||
if (/\b(selectors?|padding|margin|color|background|display|flex)\s*:/i.test(content)) return 'css'
|
||||
if (/^(npm|pnpm|yarn|git|curl|docker|cd|ls|dir)\b/im.test(content)) return 'bash'
|
||||
|
||||
return 'plaintext'
|
||||
}
|
||||
|
||||
function shouldRenderAsCode(content: string): boolean {
|
||||
const trimmed = content.trim()
|
||||
if (!trimmed || CODE_FENCE_PATTERN.test(trimmed)) return false
|
||||
|
||||
const lines = trimmed.split(/\r?\n/).filter((line) => line.trim())
|
||||
if (lines.length >= 2 && (SQL_KEYWORDS.test(trimmed) || CODE_STRUCTURE_PATTERN.test(trimmed))) {
|
||||
return true
|
||||
}
|
||||
|
||||
if (lines.length === 1) {
|
||||
return /^(select|insert|update|delete)\b/i.test(trimmed) || /^[{[]/.test(trimmed)
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
function normalizeMarkdownContent(content: string): string {
|
||||
if (!shouldRenderAsCode(content)) {
|
||||
return content
|
||||
}
|
||||
|
||||
const language = detectCodeLanguage(content)
|
||||
if (CODE_LANGUAGES.includes(language) || language === 'plaintext') {
|
||||
return `\n\n\`\`\`${language}\n${content.trim()}\n\`\`\`\n\n`
|
||||
}
|
||||
|
||||
return content
|
||||
}
|
||||
|
||||
function closeUnclosedCodeFence(content: string): string {
|
||||
const fenceCount = content.match(CODE_FENCE_LINE_PATTERN)?.length || 0
|
||||
return fenceCount % 2 === 1 ? `${content}\n\`\`\`` : content
|
||||
}
|
||||
// 界面侧兜底:禁止任何代码展示(模型侧行为准则已禁止输出代码,这里防漏网)。
|
||||
// - 围栏代码块(``` / ~~~)与缩进代码块:整块不渲染,用户看不到任何代码
|
||||
// - 行内 code:只保留文字、不输出 <code> 标签 —— 行内片段通常是字段名等,
|
||||
// 删掉文字会伤句子可读性,去掉「代码」外观即可
|
||||
|
||||
const markdown: MarkdownIt = new MarkdownIt({
|
||||
html: false,
|
||||
linkify: true,
|
||||
breaks: true,
|
||||
typographer: true,
|
||||
highlight(code: string, language: string): string {
|
||||
const normalizedLanguage = normalizeLanguage(language)
|
||||
const languageLabel = hljs.getLanguage(normalizedLanguage) ? normalizedLanguage : 'plaintext'
|
||||
const displayLanguage = getDisplayLanguage(languageLabel)
|
||||
const highlightedCode = hljs.getLanguage(languageLabel)
|
||||
? hljs.highlight(code, { language: languageLabel }).value
|
||||
: escapeCodeHtml(code)
|
||||
|
||||
return `
|
||||
<div class="md-code-block" data-language="${escapeAttribute(displayLanguage)}">
|
||||
<div class="md-code-block__toolbar">
|
||||
<span class="md-code-block__language">${escapeAttribute(displayLanguage)}</span>
|
||||
<button type="button" class="md-code-block__copy" aria-label="复制代码">复制代码</button>
|
||||
</div>
|
||||
<pre class="hljs"><code>${highlightedCode}</code></pre>
|
||||
</div>
|
||||
`
|
||||
},
|
||||
})
|
||||
|
||||
// 围栏代码块(``` / ~~~):整块不输出到 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]
|
||||
@@ -142,7 +35,92 @@ markdown.renderer.rules.link_open = (tokens, index, options, env, self) => {
|
||||
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 {
|
||||
const normalizedContent = normalizeMarkdownContent(content)
|
||||
return markdown.render(closeUnclosedCodeFence(normalizedContent))
|
||||
// 先剔除裸 JSON 段落再渲染,界面与复制共用同一判定
|
||||
return markdown.render(stripBareJsonBlocks(content))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user