markdown.tsx 9.8 KB

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