Skip to content

Commit 868847c

Browse files
authored
Dynamically import React Syntax Highlighter; correct theme (#1909)
1 parent d8de625 commit 868847c

File tree

1 file changed

+33
-10
lines changed

1 file changed

+33
-10
lines changed

components/text.js

Lines changed: 33 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
import styles from './text.module.css'
22
import ReactMarkdown from 'react-markdown'
33
import gfm from 'remark-gfm'
4-
import { LightAsync as SyntaxHighlighter } from 'react-syntax-highlighter'
5-
import atomDark from 'react-syntax-highlighter/dist/cjs/styles/prism/atom-dark'
4+
import dynamic from 'next/dynamic'
65
import React, { useState, memo, useRef, useCallback, useMemo, useEffect } from 'react'
76
import MediaOrLink from './media-or-link'
87
import { IMGPROXY_URL_REGEXP, decodeProxyUrl } from '@/lib/url'
@@ -229,17 +228,41 @@ function Table ({ node, ...props }) {
229228
}
230229

231230
function Code ({ node, inline, className, children, style, ...props }) {
232-
return inline
233-
? (
231+
const [ReactSyntaxHighlighter, setReactSyntaxHighlighter] = useState(null)
232+
const [syntaxTheme, setSyntaxTheme] = useState(null)
233+
234+
const loadHighlighter = useCallback(() =>
235+
Promise.all([
236+
dynamic(() => import('react-syntax-highlighter').then(mod => mod.LightAsync), { ssr: false }),
237+
import('react-syntax-highlighter/dist/cjs/styles/hljs/atom-one-dark').then(mod => mod.default)
238+
]), []
239+
)
240+
241+
useEffect(() => {
242+
if (!inline) {
243+
// loading the syntax highlighter and theme only when needed
244+
loadHighlighter().then(([highlighter, theme]) => {
245+
setReactSyntaxHighlighter(() => highlighter)
246+
setSyntaxTheme(() => theme)
247+
})
248+
}
249+
}, [inline])
250+
251+
if (inline || !ReactSyntaxHighlighter || !syntaxTheme) {
252+
return (
234253
<code className={className} {...props}>
235254
{children}
236255
</code>
237-
)
238-
: (
239-
<SyntaxHighlighter style={atomDark} language='text' PreTag='div' {...props}>
240-
{children}
241-
</SyntaxHighlighter>
242-
)
256+
)
257+
}
258+
259+
const language = className?.match(/language-(\w+)/)?.[1] || 'text'
260+
261+
return (
262+
<ReactSyntaxHighlighter style={syntaxTheme} language={language} PreTag='div' customStyle={{ borderRadius: '0.3rem' }} {...props}>
263+
{children}
264+
</ReactSyntaxHighlighter>
265+
)
243266
}
244267

245268
function P ({ children, node, onlyImages, somethingBefore, somethingAfter, ...props }) {

0 commit comments

Comments
 (0)