markdown.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. import ReactMarkdown from 'react-markdown'
  2. import ReactEcharts from 'echarts-for-react'
  3. import 'katex/dist/katex.min.css'
  4. import RemarkMath from 'remark-math'
  5. import RemarkBreaks from 'remark-breaks'
  6. import RehypeKatex from 'rehype-katex'
  7. import RemarkGfm from 'remark-gfm'
  8. import RehypeRaw from 'rehype-raw'
  9. import SyntaxHighlighter from 'react-syntax-highlighter'
  10. import { atelierHeathLight } from 'react-syntax-highlighter/dist/esm/styles/hljs'
  11. import type { RefObject } from 'react'
  12. import { Component, memo, useEffect, useMemo, useRef, useState } from 'react'
  13. import type { CodeComponent } from 'react-markdown/lib/ast-to-react'
  14. import cn from '@/utils/classnames'
  15. import CopyBtn from '@/app/components/base/copy-btn'
  16. import SVGBtn from '@/app/components/base/svg'
  17. import Flowchart from '@/app/components/base/mermaid'
  18. import ImageGallery from '@/app/components/base/image-gallery'
  19. import { useChatContext } from '@/app/components/base/chat/chat/context'
  20. import VideoGallery from '@/app/components/base/video-gallery'
  21. import AudioGallery from '@/app/components/base/audio-gallery'
  22. import SVGRenderer from '@/app/components/base/svg-gallery'
  23. // Available language https://github.com/react-syntax-highlighter/react-syntax-highlighter/blob/master/AVAILABLE_LANGUAGES_HLJS.MD
  24. const capitalizationLanguageNameMap: Record<string, string> = {
  25. sql: 'SQL',
  26. javascript: 'JavaScript',
  27. java: 'Java',
  28. typescript: 'TypeScript',
  29. vbscript: 'VBScript',
  30. css: 'CSS',
  31. html: 'HTML',
  32. xml: 'XML',
  33. php: 'PHP',
  34. python: 'Python',
  35. yaml: 'Yaml',
  36. mermaid: 'Mermaid',
  37. markdown: 'MarkDown',
  38. makefile: 'MakeFile',
  39. echarts: 'ECharts',
  40. shell: 'Shell',
  41. powershell: 'PowerShell',
  42. json: 'JSON',
  43. latex: 'Latex',
  44. svg: 'SVG',
  45. }
  46. const getCorrectCapitalizationLanguageName = (language: string) => {
  47. if (!language)
  48. return 'Plain'
  49. if (language in capitalizationLanguageNameMap)
  50. return capitalizationLanguageNameMap[language]
  51. return language.charAt(0).toUpperCase() + language.substring(1)
  52. }
  53. const preprocessLaTeX = (content: string) => {
  54. if (typeof content !== 'string')
  55. return content
  56. return content.replace(/\\\[(.*?)\\\]/g, (_, equation) => `$$${equation}$$`)
  57. .replace(/\\\((.*?)\\\)/g, (_, equation) => `$$${equation}$$`)
  58. .replace(/(^|[^\\])\$(.+?)\$/g, (_, prefix, equation) => `${prefix}$${equation}$`)
  59. }
  60. export function PreCode(props: { children: any }) {
  61. const ref = useRef<HTMLPreElement>(null)
  62. return (
  63. <pre ref={ref}>
  64. <span
  65. className="copy-code-button"
  66. ></span>
  67. {props.children}
  68. </pre>
  69. )
  70. }
  71. // eslint-disable-next-line unused-imports/no-unused-vars
  72. const useLazyLoad = (ref: RefObject<Element>): boolean => {
  73. const [isIntersecting, setIntersecting] = useState<boolean>(false)
  74. useEffect(() => {
  75. const observer = new IntersectionObserver(([entry]) => {
  76. if (entry.isIntersecting) {
  77. setIntersecting(true)
  78. observer.disconnect()
  79. }
  80. })
  81. if (ref.current)
  82. observer.observe(ref.current)
  83. return () => {
  84. observer.disconnect()
  85. }
  86. }, [ref])
  87. return isIntersecting
  88. }
  89. // **Add code block
  90. // Avoid error #185 (Maximum update depth exceeded.
  91. // This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate.
  92. // React limits the number of nested updates to prevent infinite loops.)
  93. // Reference A: https://reactjs.org/docs/error-decoder.html?invariant=185
  94. // Reference B1: https://react.dev/reference/react/memo
  95. // Reference B2: https://react.dev/reference/react/useMemo
  96. // ****
  97. // The original error that occurred in the streaming response during the conversation:
  98. // Error: Minified React error 185;
  99. // visit https://reactjs.org/docs/error-decoder.html?invariant=185 for the full message
  100. // or use the non-minified dev environment for full errors and additional helpful warnings.
  101. const CodeBlock: CodeComponent = memo(({ inline, className, children, ...props }) => {
  102. const [isSVG, setIsSVG] = useState(true)
  103. const match = /language-(\w+)/.exec(className || '')
  104. const language = match?.[1]
  105. const languageShowName = getCorrectCapitalizationLanguageName(language || '')
  106. let chartData = JSON.parse(String('{"title":{"text":"ECharts error - Wrong JSON format."}}').replace(/\n$/, ''))
  107. if (language === 'echarts') {
  108. try {
  109. chartData = JSON.parse(String(children).replace(/\n$/, ''))
  110. }
  111. catch (error) {
  112. }
  113. }
  114. // Use `useMemo` to ensure that `SyntaxHighlighter` only re-renders when necessary
  115. return useMemo(() => {
  116. return (!inline && match)
  117. ? (
  118. <div>
  119. <div
  120. className='flex justify-between h-8 items-center p-1 pl-3 border-b'
  121. style={{
  122. borderColor: 'rgba(0, 0, 0, 0.05)',
  123. }}
  124. >
  125. <div className='text-[13px] text-gray-500 font-normal'>{languageShowName}</div>
  126. <div style={{ display: 'flex' }}>
  127. {language === 'mermaid' && <SVGBtn isSVG={isSVG} setIsSVG={setIsSVG}/>}
  128. <CopyBtn
  129. className='mr-1'
  130. value={String(children).replace(/\n$/, '')}
  131. isPlain
  132. />
  133. </div>
  134. </div>
  135. {(language === 'mermaid' && isSVG)
  136. ? (<Flowchart PrimitiveCode={String(children).replace(/\n$/, '')} />)
  137. : (language === 'echarts'
  138. ? (<div style={{ minHeight: '350px', minWidth: '700px' }}><ErrorBoundary><ReactEcharts option={chartData} /></ErrorBoundary></div>)
  139. : (language === 'svg'
  140. ? (<ErrorBoundary><SVGRenderer content={String(children).replace(/\n$/, '')} /></ErrorBoundary>)
  141. : (<SyntaxHighlighter
  142. {...props}
  143. style={atelierHeathLight}
  144. customStyle={{
  145. paddingLeft: 12,
  146. backgroundColor: '#fff',
  147. }}
  148. language={match[1]}
  149. showLineNumbers
  150. PreTag="div"
  151. >
  152. {String(children).replace(/\n$/, '')}
  153. </SyntaxHighlighter>)))}
  154. </div>
  155. )
  156. : (<code {...props} className={className}>{children}</code>)
  157. }, [chartData, children, className, inline, isSVG, language, languageShowName, match, props])
  158. })
  159. CodeBlock.displayName = 'CodeBlock'
  160. const VideoBlock: CodeComponent = memo(({ node }) => {
  161. const srcs = node.children.filter(child => 'properties' in child).map(child => (child as any).properties.src)
  162. if (srcs.length === 0)
  163. return null
  164. return <VideoGallery key={srcs.join()} srcs={srcs} />
  165. })
  166. VideoBlock.displayName = 'VideoBlock'
  167. const AudioBlock: CodeComponent = memo(({ node }) => {
  168. const srcs = node.children.filter(child => 'properties' in child).map(child => (child as any).properties.src)
  169. if (srcs.length === 0)
  170. return null
  171. return <AudioGallery key={srcs.join()} srcs={srcs} />
  172. })
  173. AudioBlock.displayName = 'AudioBlock'
  174. const Paragraph = (paragraph: any) => {
  175. const { node }: any = paragraph
  176. const children_node = node.children
  177. if (children_node && children_node[0] && 'tagName' in children_node[0] && children_node[0].tagName === 'img') {
  178. return (
  179. <>
  180. <ImageGallery srcs={[children_node[0].properties.src]} />
  181. <p>{paragraph.children.slice(1)}</p>
  182. </>
  183. )
  184. }
  185. return <p>{paragraph.children}</p>
  186. }
  187. const Img = ({ src }: any) => {
  188. return (<ImageGallery srcs={[src]} />)
  189. }
  190. const Link = ({ node, ...props }: any) => {
  191. if (node.properties?.href && node.properties.href?.toString().startsWith('abbr')) {
  192. // eslint-disable-next-line react-hooks/rules-of-hooks
  193. const { onSend } = useChatContext()
  194. const hidden_text = decodeURIComponent(node.properties.href.toString().split('abbr:')[1])
  195. 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>
  196. }
  197. else {
  198. return <a {...props} target="_blank" className="underline decoration-dashed !decoration-primary-700 cursor-pointer">{node.children[0] ? node.children[0]?.value : 'Download'}</a>
  199. }
  200. }
  201. export function Markdown(props: { content: string; className?: string }) {
  202. const latexContent = preprocessLaTeX(props.content)
  203. return (
  204. <div className={cn(props.className, 'markdown-body')}>
  205. <ReactMarkdown
  206. remarkPlugins={[[RemarkGfm, RemarkMath, { singleDollarTextMath: false }], RemarkBreaks]}
  207. rehypePlugins={[
  208. RehypeKatex,
  209. RehypeRaw as any,
  210. // The Rehype plug-in is used to remove the ref attribute of an element
  211. () => {
  212. return (tree) => {
  213. const iterate = (node: any) => {
  214. if (node.type === 'element' && !node.properties?.src && node.properties?.ref && node.properties.ref.startsWith('{') && node.properties.ref.endsWith('}'))
  215. delete node.properties.ref
  216. if (node.children)
  217. node.children.forEach(iterate)
  218. }
  219. tree.children.forEach(iterate)
  220. }
  221. },
  222. ]}
  223. disallowedElements={['script', 'iframe', 'head', 'html', 'meta', 'link', 'style', 'body']}
  224. components={{
  225. code: CodeBlock,
  226. img: Img,
  227. video: VideoBlock,
  228. audio: AudioBlock,
  229. a: Link,
  230. p: Paragraph,
  231. }}
  232. linkTarget='_blank'
  233. >
  234. {/* Markdown detect has problem. */}
  235. {latexContent}
  236. </ReactMarkdown>
  237. </div>
  238. )
  239. }
  240. // **Add an ECharts runtime error handler
  241. // Avoid error #7832 (Crash when ECharts accesses undefined objects)
  242. // This can happen when a component attempts to access an undefined object that references an unregistered map, causing the program to crash.
  243. export default class ErrorBoundary extends Component {
  244. constructor(props: any) {
  245. super(props)
  246. this.state = { hasError: false }
  247. }
  248. componentDidCatch(error: any, errorInfo: any) {
  249. this.setState({ hasError: true })
  250. console.error(error, errorInfo)
  251. }
  252. render() {
  253. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  254. // @ts-expect-error
  255. if (this.state.hasError)
  256. return <div>Oops! An error occurred. This could be due to an ECharts runtime error or invalid SVG content. <br />(see the browser console for more information)</div>
  257. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  258. // @ts-expect-error
  259. return this.props.children
  260. }
  261. }