build: update react markdown

This commit is contained in:
AkaraChen 2024-10-29 11:04:40 +08:00
parent ca9e23d6ea
commit 29690f2483
3 changed files with 540 additions and 677 deletions

View File

@ -1,3 +1,4 @@
import type { Components } from 'react-markdown'
import ReactMarkdown from 'react-markdown'
import ReactEcharts from 'echarts-for-react'
import 'katex/dist/katex.min.css'
@ -6,11 +7,11 @@ import RemarkBreaks from 'remark-breaks'
import RehypeKatex from 'rehype-katex'
import RemarkGfm from 'remark-gfm'
import RehypeRaw from 'rehype-raw'
import rehypeExternalLinks from 'rehype-external-links'
import SyntaxHighlighter from 'react-syntax-highlighter'
import { atelierHeathLight } from 'react-syntax-highlighter/dist/esm/styles/hljs'
import type { RefObject } from 'react'
import { Component, memo, useEffect, useMemo, useRef, useState } from 'react'
import type { CodeComponent } from 'react-markdown/lib/ast-to-react'
import { Component, createContext, memo, useContext, useEffect, useMemo, useRef, useState } from 'react'
import cn from '@/utils/classnames'
import CopyBtn from '@/app/components/base/copy-btn'
import SVGBtn from '@/app/components/base/svg'
@ -21,6 +22,7 @@ import VideoGallery from '@/app/components/base/video-gallery'
import AudioGallery from '@/app/components/base/audio-gallery'
import SVGRenderer from '@/app/components/base/svg-gallery'
import Button from '@/app/components/base/button'
import type { ElementContentMap } from 'hast'
// Available language https://github.com/react-syntax-highlighter/react-syntax-highlighter/blob/master/AVAILABLE_LANGUAGES_HLJS.MD
const capitalizationLanguageNameMap: Record<string, string> = {
@ -55,7 +57,7 @@ const getCorrectCapitalizationLanguageName = (language: string) => {
return language.charAt(0).toUpperCase() + language.substring(1)
}
const preprocessLaTeX = (content: string) => {
const preprocessLaTeX = (content?: string) => {
if (typeof content !== 'string')
return content
return content.replace(/\\\[(.*?)\\\]/g, (_, equation) => `$$${equation}$$`)
@ -98,6 +100,20 @@ const useLazyLoad = (ref: RefObject<Element>): boolean => {
return isIntersecting
}
const PreContext = createContext({
// if children not in PreContext, just leave inline true
inline: true,
})
const PreBlock: Components['pre'] = (props) => {
const { ...rest } = props
return <PreContext.Provider value={{
inline: false,
}}>
<pre {...rest} />
</PreContext.Provider>
}
// **Add code block
// Avoid error #185 (Maximum update depth exceeded.
// This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate.
@ -111,7 +127,8 @@ const useLazyLoad = (ref: RefObject<Element>): boolean => {
// visit https://reactjs.org/docs/error-decoder.html?invariant=185 for the full message
// or use the non-minified dev environment for full errors and additional helpful warnings.
const CodeBlock: CodeComponent = memo(({ inline, className, children, ...props }) => {
const CodeBlock: Components['code'] = memo(({ ref, className, children, ...props }) => {
const { inline } = useContext(PreContext)
const [isSVG, setIsSVG] = useState(true)
const match = /language-(\w+)/.exec(className || '')
const language = match?.[1]
@ -121,7 +138,7 @@ const CodeBlock: CodeComponent = memo(({ inline, className, children, ...props }
try {
return JSON.parse(String(children).replace(/\n$/, ''))
}
catch (error) {}
catch {}
}
return JSON.parse('{"title":{"text":"ECharts error - Wrong JSON format."}}')
}, [language, children])
@ -191,52 +208,56 @@ const CodeBlock: CodeComponent = memo(({ inline, className, children, ...props }
</div>
)
})
CodeBlock.displayName = 'CodeBlock'
// CodeBlock.displayName = 'CodeBlock'
const VideoBlock: CodeComponent = memo(({ node }) => {
const srcs = node.children.filter(child => 'properties' in child).map(child => (child as any).properties.src)
const VideoBlock: Components['video'] = memo(({ node }) => {
const srcs = node!.children.filter(child => 'properties' in child).map(child => (child as any).properties.src)
if (srcs.length === 0)
return null
return <VideoGallery key={srcs.join()} srcs={srcs} />
})
VideoBlock.displayName = 'VideoBlock'
// VideoBlock.displayName = 'VideoBlock'
const AudioBlock: CodeComponent = memo(({ node }) => {
const srcs = node.children.filter(child => 'properties' in child).map(child => (child as any).properties.src)
const AudioBlock: Components['audio'] = memo(({ node }) => {
const srcs = node!.children.filter(child => 'properties' in child).map(child => (child as any).properties.src)
if (srcs.length === 0)
return null
return <AudioGallery key={srcs.join()} srcs={srcs} />
})
AudioBlock.displayName = 'AudioBlock'
// AudioBlock.displayName = 'AudioBlock'
const Paragraph = (paragraph: any) => {
const { node }: any = paragraph
const children_node = node.children
const Paragraph: Components['p'] = ({ node, children }) => {
const children_node = node!.children
if (children_node && children_node[0] && 'tagName' in children_node[0] && children_node[0].tagName === 'img') {
return (
<>
<ImageGallery srcs={[children_node[0].properties.src]} />
<p>{paragraph.children.slice(1)}</p>
<ImageGallery srcs={[children_node[0].properties.src as string]} />
<p>{(children as string).slice(1)}</p>
</>
)
}
return <p>{paragraph.children}</p>
return <p>{children}</p>
}
const Img = ({ src }: any) => {
return (<ImageGallery srcs={[src]} />)
const Img: Components['img'] = ({ src }) => {
return (<ImageGallery srcs={[src!]} />)
}
const Link = ({ node, ...props }: any) => {
if (node.properties?.href && node.properties.href?.toString().startsWith('abbr')) {
const Link: Components['a'] = ({ node, ...props }) => {
if (node!.properties?.href && node!.properties.href?.toString().startsWith('abbr')) {
// eslint-disable-next-line react-hooks/rules-of-hooks
const { onSend } = useChatContext()
const hidden_text = decodeURIComponent(node.properties.href.toString().split('abbr:')[1])
return <abbr className="underline decoration-dashed !decoration-primary-700 cursor-pointer" onClick={() => onSend?.(hidden_text)} title={node.children[0]?.value}>{node.children[0]?.value}</abbr>
const hidden_text = decodeURIComponent(node!.properties.href.toString().split('abbr:')[1])
const title = (node!.children[0] as ElementContentMap['text'])?.value
return <abbr className="underline decoration-dashed !decoration-primary-700 cursor-pointer" onClick={() => onSend?.(hidden_text)} title={title}>{title}</abbr>
}
else {
return <a {...props} target="_blank" className="underline decoration-dashed !decoration-primary-700 cursor-pointer">{node.children[0] ? node.children[0]?.value : 'Download'}</a>
const firstChild = node?.children?.[0] as ElementContentMap['text'] | undefined
return <a {...props} target="_blank" className="underline decoration-dashed !decoration-primary-700 cursor-pointer">{
firstChild
? firstChild.value
: 'Download'
}</a>
}
}
@ -278,9 +299,13 @@ export function Markdown(props: { content: string; className?: string }) {
tree.children.forEach(iterate)
}
},
rehypeExternalLinks({
target: '_blank',
}),
]}
disallowedElements={['script', 'iframe', 'head', 'html', 'meta', 'link', 'style', 'body']}
components={{
pre: PreBlock,
code: CodeBlock,
img: Img,
video: VideoBlock,
@ -289,7 +314,6 @@ export function Markdown(props: { content: string; className?: string }) {
p: Paragraph,
button: MarkdownButton,
}}
linkTarget='_blank'
>
{/* Markdown detect has problem. */}
{latexContent}

View File

@ -33,8 +33,8 @@
"@heroicons/react": "^2.0.16",
"@hookform/resolvers": "^3.3.4",
"@lexical/react": "^0.18.0",
"@mdx-js/loader": "^2.3.0",
"@mdx-js/react": "^2.3.0",
"@mdx-js/loader": "^3.1.0",
"@mdx-js/react": "^3.1.0",
"@monaco-editor/react": "^4.6.0",
"@next/mdx": "^14.0.4",
"@remixicon/react": "^4.3.0",
@ -43,6 +43,7 @@
"@svgdotjs/svg.js": "^3.2.4",
"@tailwindcss/line-clamp": "^0.4.4",
"@tailwindcss/typography": "^0.5.9",
"@types/hast": "^3.0.4",
"ahooks": "^3.8.1",
"class-variance-authority": "^0.7.0",
"classnames": "^2.5.1",
@ -60,7 +61,7 @@
"js-audio-recorder": "^1.0.7",
"js-cookie": "^3.0.5",
"jwt-decode": "^4.0.0",
"katex": "^0.16.10",
"katex": "^0.16.11",
"lamejs": "^1.2.1",
"lexical": "^0.18.0",
"lodash-es": "^4.17.21",
@ -81,7 +82,7 @@
"react-hook-form": "^7.51.4",
"react-i18next": "^15.1.0",
"react-infinite-scroll-component": "^6.1.0",
"react-markdown": "^8.0.6",
"react-markdown": "^9.0.1",
"react-multi-email": "^1.0.14",
"react-papaparse": "^4.1.0",
"react-slider": "^2.0.6",
@ -92,11 +93,12 @@
"react-window-infinite-loader": "^1.0.9",
"reactflow": "^11.11.3",
"recordrtc": "^5.6.2",
"rehype-katex": "^6.0.2",
"rehype-external-links": "^3.0.0",
"rehype-katex": "^7.0.1",
"rehype-raw": "^7.0.0",
"remark-breaks": "^3.0.2",
"remark-gfm": "^3.0.1",
"remark-math": "^5.1.1",
"remark-breaks": "^4.0.0",
"remark-gfm": "^4.0.0",
"remark-math": "^6.0.0",
"scheduler": "^0.23.0",
"server-only": "^0.0.1",
"sharp": "^0.33.5",
@ -153,9 +155,9 @@
"eslint": "^9.13.0",
"eslint-config-next": "^15.0.0",
"eslint-plugin-react-hooks": "^5.0.0",
"husky": "^9.1.6",
"eslint-plugin-react-refresh": "^0.4.13",
"eslint-plugin-storybook": "^0.10.1",
"husky": "^9.1.6",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"lint-staged": "^15.2.10",

File diff suppressed because it is too large Load Diff