markdown.tsx 11 KB

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