chore: Fixing Markdown renderer (#3038)

This commit is contained in:
Francisco Arceo 2025-08-04 17:16:09 -04:00 committed by GitHub
parent 68b0071861
commit eac1e0c7d4
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -1,4 +1,4 @@
import React, { Suspense } from "react" import React, { Suspense, useEffect, useState } from "react"
import Markdown from "react-markdown" import Markdown from "react-markdown"
import remarkGfm from "remark-gfm" import remarkGfm from "remark-gfm"
@ -25,28 +25,66 @@ interface HighlightedPre extends React.HTMLAttributes<HTMLPreElement> {
} }
const HighlightedPre = React.memo( const HighlightedPre = React.memo(
async ({ children, language, ...props }: HighlightedPre) => { ({ children, language, ...props }: HighlightedPre) => {
const { codeToTokens, bundledLanguages } = await import("shiki") const [tokens, setTokens] = useState<any[] | null>(null)
const [isSupported, setIsSupported] = useState(false)
if (!(language in bundledLanguages)) { useEffect(() => {
let mounted = true
const loadAndHighlight = async () => {
try {
const { codeToTokens, bundledLanguages } = await import("shiki")
if (!mounted) return
if (!(language in bundledLanguages)) {
setIsSupported(false)
return
}
setIsSupported(true)
const { tokens: highlightedTokens } = await codeToTokens(children, {
lang: language as keyof typeof bundledLanguages,
defaultColor: false,
themes: {
light: "github-light",
dark: "github-dark",
},
})
if (mounted) {
setTokens(highlightedTokens)
}
} catch (error) {
if (mounted) {
setIsSupported(false)
}
}
}
loadAndHighlight()
return () => {
mounted = false
}
}, [children, language])
if (!isSupported) {
return <pre {...props}>{children}</pre> return <pre {...props}>{children}</pre>
} }
const { tokens } = await codeToTokens(children, { if (!tokens) {
lang: language as keyof typeof bundledLanguages, return <pre {...props}>{children}</pre>
defaultColor: false, }
themes: {
light: "github-light",
dark: "github-dark",
},
})
return ( return (
<pre {...props}> <pre {...props}>
<code> <code>
{tokens.map((line, lineIndex) => ( {tokens.map((line, lineIndex) => (
<> <React.Fragment key={lineIndex}>
<span key={lineIndex}> <span>
{line.map((token, tokenIndex) => { {line.map((token, tokenIndex) => {
const style = const style =
typeof token.htmlStyle === "string" typeof token.htmlStyle === "string"
@ -65,7 +103,7 @@ const HighlightedPre = React.memo(
})} })}
</span> </span>
{lineIndex !== tokens.length - 1 && "\n"} {lineIndex !== tokens.length - 1 && "\n"}
</> </React.Fragment>
))} ))}
</code> </code>
</pre> </pre>