markdown.tsx 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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 { Component, memo, 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. import SVGRenderer from '@/app/components/base/svg-gallery'
  22. import MarkdownButton from '@/app/components/base/markdown-blocks/button'
  23. import MarkdownForm from '@/app/components/base/markdown-blocks/form'
  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. // **Add code block
  73. // Avoid error #185 (Maximum update depth exceeded.
  74. // This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate.
  75. // React limits the number of nested updates to prevent infinite loops.)
  76. // Reference A: https://reactjs.org/docs/error-decoder.html?invariant=185
  77. // Reference B1: https://react.dev/reference/react/memo
  78. // Reference B2: https://react.dev/reference/react/useMemo
  79. // ****
  80. // The original error that occurred in the streaming response during the conversation:
  81. // Error: Minified React error 185;
  82. // visit https://reactjs.org/docs/error-decoder.html?invariant=185 for the full message
  83. // or use the non-minified dev environment for full errors and additional helpful warnings.
  84. const CodeBlock: CodeComponent = memo(({ inline, className, children, ...props }) => {
  85. const [isSVG, setIsSVG] = useState(true)
  86. const match = /language-(\w+)/.exec(className || '')
  87. const language = match?.[1]
  88. const languageShowName = getCorrectCapitalizationLanguageName(language || '')
  89. const chartData = useMemo(() => {
  90. if (language === 'echarts') {
  91. try {
  92. return JSON.parse(String(children).replace(/\n$/, ''))
  93. }
  94. catch (error) { }
  95. }
  96. return JSON.parse('{"title":{"text":"ECharts error - Wrong JSON format."}}')
  97. }, [language, children])
  98. const renderCodeContent = useMemo(() => {
  99. const content = String(children).replace(/\n$/, '')
  100. if (language === 'mermaid' && isSVG) {
  101. return <Flowchart PrimitiveCode={content} />
  102. }
  103. else if (language === 'echarts') {
  104. return (
  105. <div style={{ minHeight: '350px', minWidth: '100%', overflowX: 'scroll' }}>
  106. <ErrorBoundary>
  107. <ReactEcharts option={chartData} style={{ minWidth: '700px' }} />
  108. </ErrorBoundary>
  109. </div>
  110. )
  111. }
  112. else if (language === 'svg' && isSVG) {
  113. return (
  114. <ErrorBoundary>
  115. <SVGRenderer content={content} />
  116. </ErrorBoundary>
  117. )
  118. }
  119. else {
  120. return (
  121. <SyntaxHighlighter
  122. {...props}
  123. style={atelierHeathLight}
  124. customStyle={{
  125. paddingLeft: 12,
  126. backgroundColor: '#fff',
  127. }}
  128. language={match?.[1]}
  129. showLineNumbers
  130. PreTag="div"
  131. >
  132. {content}
  133. </SyntaxHighlighter>
  134. )
  135. }
  136. }, [language, match, props, children, chartData, isSVG])
  137. if (inline || !match)
  138. return <code {...props} className={className}>{children}</code>
  139. return (
  140. <div>
  141. <div
  142. className='flex justify-between h-8 items-center p-1 pl-3 border-b'
  143. style={{
  144. borderColor: 'rgba(0, 0, 0, 0.05)',
  145. }}
  146. >
  147. <div className='text-[13px] text-gray-500 font-normal'>{languageShowName}</div>
  148. <div style={{ display: 'flex' }}>
  149. {(['mermaid', 'svg']).includes(language!) && <SVGBtn isSVG={isSVG} setIsSVG={setIsSVG} />}
  150. <CopyBtn
  151. className='mr-1'
  152. value={String(children).replace(/\n$/, '')}
  153. isPlain
  154. />
  155. </div>
  156. </div>
  157. {renderCodeContent}
  158. </div>
  159. )
  160. })
  161. CodeBlock.displayName = 'CodeBlock'
  162. const VideoBlock: CodeComponent = memo(({ node }) => {
  163. const srcs = node.children.filter(child => 'properties' in child).map(child => (child as any).properties.src)
  164. if (srcs.length === 0)
  165. return null
  166. return <VideoGallery key={srcs.join()} srcs={srcs} />
  167. })
  168. VideoBlock.displayName = 'VideoBlock'
  169. const AudioBlock: CodeComponent = memo(({ node }) => {
  170. const srcs = node.children.filter(child => 'properties' in child).map(child => (child as any).properties.src)
  171. if (srcs.length === 0)
  172. return null
  173. return <AudioGallery key={srcs.join()} srcs={srcs} />
  174. })
  175. AudioBlock.displayName = 'AudioBlock'
  176. const ScriptBlock = memo(({ node }: any) => {
  177. const scriptContent = node.children[0]?.value || ''
  178. return `<script>${scriptContent}</script>`
  179. })
  180. ScriptBlock.displayName = 'ScriptBlock'
  181. const Paragraph = (paragraph: any) => {
  182. const { node }: any = paragraph
  183. const children_node = node.children
  184. if (children_node && children_node[0] && 'tagName' in children_node[0] && children_node[0].tagName === 'img') {
  185. return (
  186. <>
  187. <ImageGallery srcs={[children_node[0].properties.src]} />
  188. <p>{paragraph.children.slice(1)}</p>
  189. </>
  190. )
  191. }
  192. return <p>{paragraph.children}</p>
  193. }
  194. const Img = ({ src }: any) => {
  195. return (<ImageGallery srcs={[src]} />)
  196. }
  197. const Link = ({ node, ...props }: any) => {
  198. if (node.properties?.href && node.properties.href?.toString().startsWith('abbr')) {
  199. // eslint-disable-next-line react-hooks/rules-of-hooks
  200. const { onSend } = useChatContext()
  201. const hidden_text = decodeURIComponent(node.properties.href.toString().split('abbr:')[1])
  202. 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>
  203. }
  204. else {
  205. return <a {...props} target="_blank" className="underline decoration-dashed !decoration-primary-700 cursor-pointer">{node.children[0] ? node.children[0]?.value : 'Download'}</a>
  206. }
  207. }
  208. export function Markdown(props: { content: string; className?: string }) {
  209. const latexContent = preprocessLaTeX(props.content)
  210. return (
  211. <div className={cn(props.className, 'markdown-body')}>
  212. <ReactMarkdown
  213. remarkPlugins={[RemarkGfm, RemarkMath, RemarkBreaks]}
  214. rehypePlugins={[
  215. RehypeKatex,
  216. RehypeRaw as any,
  217. // The Rehype plug-in is used to remove the ref attribute of an element
  218. () => {
  219. return (tree) => {
  220. const iterate = (node: any) => {
  221. if (node.type === 'element' && node.properties?.ref)
  222. delete node.properties.ref
  223. if (node.children)
  224. node.children.forEach(iterate)
  225. }
  226. tree.children.forEach(iterate)
  227. }
  228. },
  229. ]}
  230. disallowedElements={['iframe', 'head', 'html', 'meta', 'link', 'style', 'body']}
  231. components={{
  232. code: CodeBlock,
  233. img: Img,
  234. video: VideoBlock,
  235. audio: AudioBlock,
  236. a: Link,
  237. p: Paragraph,
  238. button: MarkdownButton,
  239. form: MarkdownForm,
  240. script: ScriptBlock,
  241. }}
  242. linkTarget='_blank'
  243. >
  244. {/* Markdown detect has problem. */}
  245. {latexContent}
  246. </ReactMarkdown>
  247. </div>
  248. )
  249. }
  250. // **Add an ECharts runtime error handler
  251. // Avoid error #7832 (Crash when ECharts accesses undefined objects)
  252. // This can happen when a component attempts to access an undefined object that references an unregistered map, causing the program to crash.
  253. export default class ErrorBoundary extends Component {
  254. constructor(props: any) {
  255. super(props)
  256. this.state = { hasError: false }
  257. }
  258. componentDidCatch(error: any, errorInfo: any) {
  259. this.setState({ hasError: true })
  260. console.error(error, errorInfo)
  261. }
  262. render() {
  263. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  264. // @ts-expect-error
  265. if (this.state.hasError)
  266. 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>
  267. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  268. // @ts-expect-error
  269. return this.props.children
  270. }
  271. }