Skip to content

Commit

Permalink
Dynamically import MathJax
Browse files Browse the repository at this point in the history
  • Loading branch information
Soxasora committed Feb 16, 2025
1 parent c571ba0 commit 298f247
Showing 1 changed file with 15 additions and 4 deletions.
19 changes: 15 additions & 4 deletions components/text.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import rehypeSN from '@/lib/rehype-sn'
import remarkUnicode from '@/lib/remark-unicode'
import Embed from './embed'
import remarkMath from 'remark-math'
import rehypeMathjax from 'rehype-mathjax'

const rehypeSNStyled = () => rehypeSN({
stylers: [{
Expand All @@ -35,7 +34,6 @@ const rehypeSNStyled = () => rehypeSN({
})

const remarkPlugins = [gfm, remarkUnicode, [remarkMath, { singleDollarTextMath: false }]]
const rehypePlugins = [rehypeSNStyled, rehypeMathjax]

export function SearchText ({ text }) {
return (
Expand All @@ -55,6 +53,19 @@ export default memo(function Text ({ rel = UNKNOWN_LINK_REL, imgproxyUrls, child
const router = useRouter()
const [show, setShow] = useState(false)
const containerRef = useRef(null)
const [mathJaxPlugin, setMathJaxPlugin] = useState(null)

// we only need mathjax if there's math content
useEffect(() => {
if (children?.includes('$$')) {
import('rehype-mathjax').then(mod => {
setMathJaxPlugin(() => mod.default)
}).catch(err => {
console.error('error loading mathjax', err)
setMathJaxPlugin(null)
})
}
}, [children])

// if we are navigating to a hash, show the full text
useEffect(() => {
Expand Down Expand Up @@ -133,12 +144,12 @@ export default memo(function Text ({ rel = UNKNOWN_LINK_REL, imgproxyUrls, child
<ReactMarkdown
components={components}
remarkPlugins={remarkPlugins}
rehypePlugins={rehypePlugins}
rehypePlugins={[rehypeSNStyled, ...(mathJaxPlugin ? [mathJaxPlugin] : [])]}
remarkRehypeOptions={{ clobberPrefix: `itemfn-${itemId}-` }}
>
{children}
</ReactMarkdown>
), [components, remarkPlugins, rehypePlugins, children, itemId])
), [components, remarkPlugins, mathJaxPlugin, children, itemId])

const showOverflow = useCallback(() => setShow(true), [setShow])

Expand Down

0 comments on commit 298f247

Please sign in to comment.