You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

markdown.tsx 10KB

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