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