markdown.tsx 11 KB

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