markdown.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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 { flow } from 'lodash/fp'
  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. import ThinkBlock from '@/app/components/base/markdown-blocks/think-block'
  26. // Available language https://github.com/react-syntax-highlighter/react-syntax-highlighter/blob/master/AVAILABLE_LANGUAGES_HLJS.MD
  27. const capitalizationLanguageNameMap: Record<string, string> = {
  28. sql: 'SQL',
  29. javascript: 'JavaScript',
  30. java: 'Java',
  31. typescript: 'TypeScript',
  32. vbscript: 'VBScript',
  33. css: 'CSS',
  34. html: 'HTML',
  35. xml: 'XML',
  36. php: 'PHP',
  37. python: 'Python',
  38. yaml: 'Yaml',
  39. mermaid: 'Mermaid',
  40. markdown: 'MarkDown',
  41. makefile: 'MakeFile',
  42. echarts: 'ECharts',
  43. shell: 'Shell',
  44. powershell: 'PowerShell',
  45. json: 'JSON',
  46. latex: 'Latex',
  47. svg: 'SVG',
  48. }
  49. const getCorrectCapitalizationLanguageName = (language: string) => {
  50. if (!language)
  51. return 'Plain'
  52. if (language in capitalizationLanguageNameMap)
  53. return capitalizationLanguageNameMap[language]
  54. return language.charAt(0).toUpperCase() + language.substring(1)
  55. }
  56. const preprocessLaTeX = (content: string) => {
  57. if (typeof content !== 'string')
  58. return content
  59. return flow([
  60. (str: string) => str.replace(/\\\[(.*?)\\\]/g, (_, equation) => `$$${equation}$$`),
  61. (str: string) => str.replace(/\\\((.*?)\\\)/g, (_, equation) => `$$${equation}$$`),
  62. (str: string) => str.replace(/(^|[^\\])\$(.+?)\$/g, (_, prefix, equation) => `${prefix}$${equation}$`),
  63. ])(content)
  64. }
  65. const preprocessThinkTag = (content: string) => {
  66. if (!content.trim().startsWith('<think>\n'))
  67. return content
  68. return flow([
  69. (str: string) => str.replace('<think>\n', '<details>\n'),
  70. (str: string) => str.replace('\n</think>', '\n[ENDTHINKFLAG]</details>'),
  71. ])(content)
  72. }
  73. export function PreCode(props: { children: any }) {
  74. const ref = useRef<HTMLPreElement>(null)
  75. return (
  76. <pre ref={ref}>
  77. <span
  78. className="copy-code-button"
  79. ></span>
  80. {props.children}
  81. </pre>
  82. )
  83. }
  84. // **Add code block
  85. // Avoid error #185 (Maximum update depth exceeded.
  86. // This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate.
  87. // React limits the number of nested updates to prevent infinite loops.)
  88. // Reference A: https://reactjs.org/docs/error-decoder.html?invariant=185
  89. // Reference B1: https://react.dev/reference/react/memo
  90. // Reference B2: https://react.dev/reference/react/useMemo
  91. // ****
  92. // The original error that occurred in the streaming response during the conversation:
  93. // Error: Minified React error 185;
  94. // visit https://reactjs.org/docs/error-decoder.html?invariant=185 for the full message
  95. // or use the non-minified dev environment for full errors and additional helpful warnings.
  96. const CodeBlock: CodeComponent = memo(({ inline, className, children, ...props }) => {
  97. const [isSVG, setIsSVG] = useState(true)
  98. const match = /language-(\w+)/.exec(className || '')
  99. const language = match?.[1]
  100. const languageShowName = getCorrectCapitalizationLanguageName(language || '')
  101. const chartData = useMemo(() => {
  102. if (language === 'echarts') {
  103. try {
  104. return JSON.parse(String(children).replace(/\n$/, ''))
  105. }
  106. catch (error) { }
  107. }
  108. return JSON.parse('{"title":{"text":"ECharts error - Wrong JSON format."}}')
  109. }, [language, children])
  110. const renderCodeContent = useMemo(() => {
  111. const content = String(children).replace(/\n$/, '')
  112. if (language === 'mermaid' && isSVG) {
  113. return <Flowchart PrimitiveCode={content} />
  114. }
  115. else if (language === 'echarts') {
  116. return (
  117. <div style={{ minHeight: '350px', minWidth: '100%', overflowX: 'scroll' }}>
  118. <ErrorBoundary>
  119. <ReactEcharts option={chartData} style={{ minWidth: '700px' }} />
  120. </ErrorBoundary>
  121. </div>
  122. )
  123. }
  124. else if (language === 'svg' && isSVG) {
  125. return (
  126. <ErrorBoundary>
  127. <SVGRenderer content={content} />
  128. </ErrorBoundary>
  129. )
  130. }
  131. else {
  132. return (
  133. <SyntaxHighlighter
  134. {...props}
  135. style={atelierHeathLight}
  136. customStyle={{
  137. paddingLeft: 12,
  138. backgroundColor: '#fff',
  139. }}
  140. language={match?.[1]}
  141. showLineNumbers
  142. PreTag="div"
  143. >
  144. {content}
  145. </SyntaxHighlighter>
  146. )
  147. }
  148. }, [language, match, props, children, chartData, isSVG])
  149. if (inline || !match)
  150. return <code {...props} className={className}>{children}</code>
  151. return (
  152. <div>
  153. <div
  154. className='flex justify-between h-8 items-center p-1 pl-3 border-b'
  155. style={{
  156. borderColor: 'rgba(0, 0, 0, 0.05)',
  157. }}
  158. >
  159. <div className='text-[13px] text-gray-500 font-normal'>{languageShowName}</div>
  160. <div style={{ display: 'flex' }}>
  161. {(['mermaid', 'svg']).includes(language!) && <SVGBtn isSVG={isSVG} setIsSVG={setIsSVG} />}
  162. <CopyBtn
  163. className='mr-1'
  164. value={String(children).replace(/\n$/, '')}
  165. isPlain
  166. />
  167. </div>
  168. </div>
  169. {renderCodeContent}
  170. </div>
  171. )
  172. })
  173. CodeBlock.displayName = 'CodeBlock'
  174. const VideoBlock: CodeComponent = memo(({ node }) => {
  175. const srcs = node.children.filter(child => 'properties' in child).map(child => (child as any).properties.src)
  176. if (srcs.length === 0)
  177. return null
  178. return <VideoGallery key={srcs.join()} srcs={srcs} />
  179. })
  180. VideoBlock.displayName = 'VideoBlock'
  181. const AudioBlock: 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 <AudioGallery key={srcs.join()} srcs={srcs} />
  186. })
  187. AudioBlock.displayName = 'AudioBlock'
  188. const ScriptBlock = memo(({ node }: any) => {
  189. const scriptContent = node.children[0]?.value || ''
  190. return `<script>${scriptContent}</script>`
  191. })
  192. ScriptBlock.displayName = 'ScriptBlock'
  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 = flow([
  222. preprocessThinkTag,
  223. preprocessLaTeX,
  224. ])(props.content)
  225. return (
  226. <div className={cn(props.className, 'markdown-body')}>
  227. <ReactMarkdown
  228. remarkPlugins={[
  229. RemarkGfm,
  230. [RemarkMath, { singleDollarTextMath: false }],
  231. RemarkBreaks,
  232. ]}
  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?.ref)
  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. details: ThinkBlock,
  261. }}
  262. linkTarget='_blank'
  263. >
  264. {/* Markdown detect has problem. */}
  265. {latexContent}
  266. </ReactMarkdown>
  267. </div>
  268. )
  269. }
  270. // **Add an ECharts runtime error handler
  271. // Avoid error #7832 (Crash when ECharts accesses undefined objects)
  272. // This can happen when a component attempts to access an undefined object that references an unregistered map, causing the program to crash.
  273. export default class ErrorBoundary extends Component {
  274. constructor(props: any) {
  275. super(props)
  276. this.state = { hasError: false }
  277. }
  278. componentDidCatch(error: any, errorInfo: any) {
  279. this.setState({ hasError: true })
  280. console.error(error, errorInfo)
  281. }
  282. render() {
  283. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  284. // @ts-expect-error
  285. if (this.state.hasError)
  286. 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>
  287. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  288. // @ts-expect-error
  289. return this.props.children
  290. }
  291. }