markdown.tsx 11 KB

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