fix: support \(...\) and \[...\] style math formula #78

This commit is contained in:
kangfenmao 2024-09-19 15:21:06 +08:00
parent cf9d4c5370
commit 03bdbdb412

View File

@ -17,7 +17,7 @@ interface Props {
} }
const rehypePlugins = [rehypeKatex] const rehypePlugins = [rehypeKatex]
const remarkPlugins = [remarkGfm, remarkMath] const remarkPlugins = [remarkMath, remarkGfm]
const components = { const components = {
code: CodeBlock, code: CodeBlock,
@ -31,7 +31,7 @@ const Markdown: FC<Props> = ({ message }) => {
const empty = isEmpty(message.content) const empty = isEmpty(message.content)
const paused = message.status === 'paused' const paused = message.status === 'paused'
const content = empty && paused ? t('message.chat.completion.paused') : message.content const content = empty && paused ? t('message.chat.completion.paused') : message.content
return content return escapeBrackets(escapeDollarNumber(content))
}, [message.content, message.status, t]) }, [message.content, message.status, t])
return ( return (
@ -50,4 +50,35 @@ const Markdown: FC<Props> = ({ message }) => {
) )
} }
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
})
}
export default Markdown export default Markdown