Skip to content

Commit

Permalink
Merge pull request #154 from miurla/latex
Browse files Browse the repository at this point in the history
Support LaTeX format
  • Loading branch information
miurla committed May 15, 2024
2 parents abe1b03 + ac44345 commit 1d6bf0c
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 3 deletions.
Binary file modified bun.lockb
Binary file not shown.
26 changes: 23 additions & 3 deletions components/message.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,40 @@ import { StreamableValue, useStreamableValue } from 'ai/rsc'
import { MemoizedReactMarkdown } from './ui/markdown'
import rehypeExternalLinks from 'rehype-external-links'
import remarkGfm from 'remark-gfm'
import remarkMath from 'remark-math'
import rehypeKatex from 'rehype-katex'
import 'katex/dist/katex.min.css'

export function BotMessage({ content }: { content: StreamableValue<string> }) {
const [data, error, pending] = useStreamableValue(content)

// Currently, sometimes error occurs after finishing the stream.
if (error) return <div>Error</div>

//modify the content to render LaTeX equations
const processedData = preprocessLaTeX(data || '')

return (
<MemoizedReactMarkdown
rehypePlugins={[[rehypeExternalLinks, { target: '_blank' }]]}
remarkPlugins={[remarkGfm]}
rehypePlugins={[[rehypeExternalLinks, { target: '_blank' }], rehypeKatex]}
remarkPlugins={[remarkGfm, remarkMath]}
className="prose-sm prose-neutral prose-a:text-accent-foreground/50"
>
{data}
{processedData}
</MemoizedReactMarkdown>
)
}

// Preprocess LaTeX equations to be rendered by KaTeX
// ref: https://github.com/remarkjs/react-markdown/issues/785
const preprocessLaTeX = (content: string) => {
const blockProcessedContent = content.replace(
/\\\[([\s\S]*?)\\\]/g,
(_, equation) => `$$${equation}$$`
)
const inlineProcessedContent = blockProcessedContent.replace(
/\\\(([\s\S]*?)\\\)/g,
(_, equation) => `$${equation}$`
)
return inlineProcessedContent
}
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"clsx": "^2.1.0",
"embla-carousel-react": "^8.0.0",
"exa-js": "^1.0.12",
"katex": "^0.16.10",
"lucide-react": "^0.363.0",
"next": "^14.2.3",
"next-themes": "^0.3.0",
Expand All @@ -40,7 +41,9 @@
"react-markdown": "^9.0.1",
"react-textarea-autosize": "^8.5.3",
"rehype-external-links": "^3.0.0",
"rehype-katex": "^7.0.0",
"remark-gfm": "^4.0.0",
"remark-math": "^6.0.0",
"sonner": "^1.4.41",
"tailwind-merge": "^2.2.2",
"tailwindcss-animate": "^1.0.7"
Expand Down

0 comments on commit 1d6bf0c

Please sign in to comment.