markdown.tsx 10 KB

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