Skip to content

Commit

Permalink
perf: 数学公式 $$ 处理
Browse files Browse the repository at this point in the history
  • Loading branch information
Chanzhaoyu committed Jun 7, 2024
1 parent a546d85 commit 574aac2
Showing 1 changed file with 34 additions and 2 deletions.
36 changes: 34 additions & 2 deletions src/views/chat/components/Message/Text.vue
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,11 @@ const wrapClass = computed(() => {
const text = computed(() => {
const value = props.text ?? ''
if (!props.asRawText)
return mdi.render(value)
if (!props.asRawText) {
// 对数学公式进行处理,自动添加 $$ 符号
const escapedText = escapeBrackets(escapeDollarNumber(value))
return mdi.render(escapedText)
}
return value
})
Expand Down Expand Up @@ -90,6 +93,35 @@ function removeCopyEvents() {
}
}
function escapeDollarNumber(text: string) {
let escapedText = ''
for (let i = 0; i < text.length; i += 1) {
let char = text[i]
const nextChar = text[i + 1] || ' '
if (char === '$' && nextChar >= '0' && nextChar <= '9')
char = '\\$'
escapedText += char
}
return escapedText
}
function escapeBrackets(text: string) {
const pattern = /(```[\s\S]*?```|`.*?`)|\\\[([\s\S]*?[^\\])\\\]|\\\((.*?)\\\)/g
return text.replace(pattern, (match, codeBlock, squareBracket, roundBracket) => {
if (codeBlock)
return codeBlock
else if (squareBracket)
return `$$${squareBracket}$$`
else if (roundBracket)
return `$${roundBracket}$`
return match
})
}
onMounted(() => {
addCopyEvents()
})
Expand Down

0 comments on commit 574aac2

Please sign in to comment.