markdown.tsx 9.8 KB

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