markdown.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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. const chartData = useMemo(() => {
  107. if (language === 'echarts') {
  108. try {
  109. return JSON.parse(String(children).replace(/\n$/, ''))
  110. }
  111. catch (error) {}
  112. }
  113. return JSON.parse('{"title":{"text":"ECharts error - Wrong JSON format."}}')
  114. }, [language, children])
  115. const renderCodeContent = useMemo(() => {
  116. const content = String(children).replace(/\n$/, '')
  117. if (language === 'mermaid' && isSVG) {
  118. return <Flowchart PrimitiveCode={content} />
  119. }
  120. else if (language === 'echarts') {
  121. return (
  122. <div style={{ minHeight: '350px', minWidth: '700px' }}>
  123. <ErrorBoundary>
  124. <ReactEcharts option={chartData} />
  125. </ErrorBoundary>
  126. </div>
  127. )
  128. }
  129. else if (language === 'svg' && isSVG) {
  130. return (
  131. <ErrorBoundary>
  132. <SVGRenderer content={content} />
  133. </ErrorBoundary>
  134. )
  135. }
  136. else {
  137. return (
  138. <SyntaxHighlighter
  139. {...props}
  140. style={atelierHeathLight}
  141. customStyle={{
  142. paddingLeft: 12,
  143. backgroundColor: '#fff',
  144. }}
  145. language={match?.[1]}
  146. showLineNumbers
  147. PreTag="div"
  148. >
  149. {content}
  150. </SyntaxHighlighter>
  151. )
  152. }
  153. }, [language, match, props, children, chartData, isSVG])
  154. if (inline || !match)
  155. return <code {...props} className={className}>{children}</code>
  156. return (
  157. <div>
  158. <div
  159. className='flex justify-between h-8 items-center p-1 pl-3 border-b'
  160. style={{
  161. borderColor: 'rgba(0, 0, 0, 0.05)',
  162. }}
  163. >
  164. <div className='text-[13px] text-gray-500 font-normal'>{languageShowName}</div>
  165. <div style={{ display: 'flex' }}>
  166. {(['mermaid', 'svg']).includes(language!) && <SVGBtn isSVG={isSVG} setIsSVG={setIsSVG}/>}
  167. <CopyBtn
  168. className='mr-1'
  169. value={String(children).replace(/\n$/, '')}
  170. isPlain
  171. />
  172. </div>
  173. </div>
  174. {renderCodeContent}
  175. </div>
  176. )
  177. })
  178. CodeBlock.displayName = 'CodeBlock'
  179. const VideoBlock: CodeComponent = memo(({ node }) => {
  180. const srcs = node.children.filter(child => 'properties' in child).map(child => (child as any).properties.src)
  181. if (srcs.length === 0)
  182. return null
  183. return <VideoGallery key={srcs.join()} srcs={srcs} />
  184. })
  185. VideoBlock.displayName = 'VideoBlock'
  186. const AudioBlock: CodeComponent = memo(({ node }) => {
  187. const srcs = node.children.filter(child => 'properties' in child).map(child => (child as any).properties.src)
  188. if (srcs.length === 0)
  189. return null
  190. return <AudioGallery key={srcs.join()} srcs={srcs} />
  191. })
  192. AudioBlock.displayName = 'AudioBlock'
  193. const Paragraph = (paragraph: any) => {
  194. const { node }: any = paragraph
  195. const children_node = node.children
  196. if (children_node && children_node[0] && 'tagName' in children_node[0] && children_node[0].tagName === 'img') {
  197. return (
  198. <>
  199. <ImageGallery srcs={[children_node[0].properties.src]} />
  200. <p>{paragraph.children.slice(1)}</p>
  201. </>
  202. )
  203. }
  204. return <p>{paragraph.children}</p>
  205. }
  206. const Img = ({ src }: any) => {
  207. return (<ImageGallery srcs={[src]} />)
  208. }
  209. const Link = ({ node, ...props }: any) => {
  210. if (node.properties?.href && node.properties.href?.toString().startsWith('abbr')) {
  211. // eslint-disable-next-line react-hooks/rules-of-hooks
  212. const { onSend } = useChatContext()
  213. const hidden_text = decodeURIComponent(node.properties.href.toString().split('abbr:')[1])
  214. 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>
  215. }
  216. else {
  217. return <a {...props} target="_blank" className="underline decoration-dashed !decoration-primary-700 cursor-pointer">{node.children[0] ? node.children[0]?.value : 'Download'}</a>
  218. }
  219. }
  220. export function Markdown(props: { content: string; className?: string }) {
  221. const latexContent = preprocessLaTeX(props.content)
  222. return (
  223. <div className={cn(props.className, 'markdown-body')}>
  224. <ReactMarkdown
  225. remarkPlugins={[[RemarkGfm, RemarkMath, { singleDollarTextMath: false }], RemarkBreaks]}
  226. rehypePlugins={[
  227. RehypeKatex,
  228. RehypeRaw as any,
  229. // The Rehype plug-in is used to remove the ref attribute of an element
  230. () => {
  231. return (tree) => {
  232. const iterate = (node: any) => {
  233. if (node.type === 'element' && !node.properties?.src && node.properties?.ref && node.properties.ref.startsWith('{') && node.properties.ref.endsWith('}'))
  234. delete node.properties.ref
  235. if (node.children)
  236. node.children.forEach(iterate)
  237. }
  238. tree.children.forEach(iterate)
  239. }
  240. },
  241. ]}
  242. disallowedElements={['script', 'iframe', 'head', 'html', 'meta', 'link', 'style', 'body']}
  243. components={{
  244. code: CodeBlock,
  245. img: Img,
  246. video: VideoBlock,
  247. audio: AudioBlock,
  248. a: Link,
  249. p: Paragraph,
  250. }}
  251. linkTarget='_blank'
  252. >
  253. {/* Markdown detect has problem. */}
  254. {latexContent}
  255. </ReactMarkdown>
  256. </div>
  257. )
  258. }
  259. // **Add an ECharts runtime error handler
  260. // Avoid error #7832 (Crash when ECharts accesses undefined objects)
  261. // This can happen when a component attempts to access an undefined object that references an unregistered map, causing the program to crash.
  262. export default class ErrorBoundary extends Component {
  263. constructor(props: any) {
  264. super(props)
  265. this.state = { hasError: false }
  266. }
  267. componentDidCatch(error: any, errorInfo: any) {
  268. this.setState({ hasError: true })
  269. console.error(error, errorInfo)
  270. }
  271. render() {
  272. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  273. // @ts-expect-error
  274. if (this.state.hasError)
  275. 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>
  276. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  277. // @ts-expect-error
  278. return this.props.children
  279. }
  280. }