markdown.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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 {
  11. atelierHeathDark,
  12. atelierHeathLight,
  13. } from 'react-syntax-highlighter/dist/esm/styles/hljs'
  14. import { Component, memo, useMemo, useRef, useState } from 'react'
  15. import { flow } from 'lodash-es'
  16. import ActionButton from '@/app/components/base/action-button'
  17. import CopyIcon from '@/app/components/base/copy-icon'
  18. import SVGBtn from '@/app/components/base/svg'
  19. import Flowchart from '@/app/components/base/mermaid'
  20. import ImageGallery from '@/app/components/base/image-gallery'
  21. import { useChatContext } from '@/app/components/base/chat/chat/context'
  22. import VideoGallery from '@/app/components/base/video-gallery'
  23. import AudioGallery from '@/app/components/base/audio-gallery'
  24. import MarkdownButton from '@/app/components/base/markdown-blocks/button'
  25. import MarkdownForm from '@/app/components/base/markdown-blocks/form'
  26. import ThinkBlock from '@/app/components/base/markdown-blocks/think-block'
  27. import { Theme } from '@/types/app'
  28. import useTheme from '@/hooks/use-theme'
  29. import cn from '@/utils/classnames'
  30. import SVGRenderer from './svg-gallery'
  31. // Available language https://github.com/react-syntax-highlighter/react-syntax-highlighter/blob/master/AVAILABLE_LANGUAGES_HLJS.MD
  32. const capitalizationLanguageNameMap: Record<string, string> = {
  33. sql: 'SQL',
  34. javascript: 'JavaScript',
  35. java: 'Java',
  36. typescript: 'TypeScript',
  37. vbscript: 'VBScript',
  38. css: 'CSS',
  39. html: 'HTML',
  40. xml: 'XML',
  41. php: 'PHP',
  42. python: 'Python',
  43. yaml: 'Yaml',
  44. mermaid: 'Mermaid',
  45. markdown: 'MarkDown',
  46. makefile: 'MakeFile',
  47. echarts: 'ECharts',
  48. shell: 'Shell',
  49. powershell: 'PowerShell',
  50. json: 'JSON',
  51. latex: 'Latex',
  52. svg: 'SVG',
  53. }
  54. const getCorrectCapitalizationLanguageName = (language: string) => {
  55. if (!language)
  56. return 'Plain'
  57. if (language in capitalizationLanguageNameMap)
  58. return capitalizationLanguageNameMap[language]
  59. return language.charAt(0).toUpperCase() + language.substring(1)
  60. }
  61. const preprocessLaTeX = (content: string) => {
  62. if (typeof content !== 'string')
  63. return content
  64. const codeBlockRegex = /```[\s\S]*?```/g
  65. const codeBlocks = content.match(codeBlockRegex) || []
  66. let processedContent = content.replace(codeBlockRegex, 'CODE_BLOCK_PLACEHOLDER')
  67. processedContent = flow([
  68. (str: string) => str.replace(/\\\[(.*?)\\\]/g, (_, equation) => `$$${equation}$$`),
  69. (str: string) => str.replace(/\\\[(.*?)\\\]/gs, (_, equation) => `$$${equation}$$`),
  70. (str: string) => str.replace(/\\\((.*?)\\\)/g, (_, equation) => `$$${equation}$$`),
  71. (str: string) => str.replace(/(^|[^\\])\$(.+?)\$/g, (_, prefix, equation) => `${prefix}$${equation}$`),
  72. ])(processedContent)
  73. codeBlocks.forEach((block) => {
  74. processedContent = processedContent.replace('CODE_BLOCK_PLACEHOLDER', block)
  75. })
  76. return processedContent
  77. }
  78. const preprocessThinkTag = (content: string) => {
  79. return flow([
  80. (str: string) => str.replace('<think>\n', '<details data-think=true>\n'),
  81. (str: string) => str.replace('\n</think>', '\n[ENDTHINKFLAG]</details>'),
  82. ])(content)
  83. }
  84. export function PreCode(props: { children: any }) {
  85. const ref = useRef<HTMLPreElement>(null)
  86. return (
  87. <pre ref={ref}>
  88. <span
  89. className="copy-code-button"
  90. ></span>
  91. {props.children}
  92. </pre>
  93. )
  94. }
  95. // **Add code block
  96. // Avoid error #185 (Maximum update depth exceeded.
  97. // This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate.
  98. // React limits the number of nested updates to prevent infinite loops.)
  99. // Reference A: https://reactjs.org/docs/error-decoder.html?invariant=185
  100. // Reference B1: https://react.dev/reference/react/memo
  101. // Reference B2: https://react.dev/reference/react/useMemo
  102. // ****
  103. // The original error that occurred in the streaming response during the conversation:
  104. // Error: Minified React error 185;
  105. // visit https://reactjs.org/docs/error-decoder.html?invariant=185 for the full message
  106. // or use the non-minified dev environment for full errors and additional helpful warnings.
  107. const CodeBlock: any = memo(({ inline, className, children, ...props }: any) => {
  108. const { theme } = useTheme()
  109. const [isSVG, setIsSVG] = useState(true)
  110. const match = /language-(\w+)/.exec(className || '')
  111. const language = match?.[1]
  112. const languageShowName = getCorrectCapitalizationLanguageName(language || '')
  113. const chartData = useMemo(() => {
  114. if (language === 'echarts') {
  115. try {
  116. return JSON.parse(String(children).replace(/\n$/, ''))
  117. }
  118. catch (error) { }
  119. }
  120. return JSON.parse('{"title":{"text":"ECharts error - Wrong JSON format."}}')
  121. }, [language, children])
  122. const renderCodeContent = useMemo(() => {
  123. const content = String(children).replace(/\n$/, '')
  124. if (language === 'mermaid' && isSVG) {
  125. return <Flowchart PrimitiveCode={content} />
  126. }
  127. else if (language === 'echarts') {
  128. return (
  129. <div style={{ minHeight: '350px', minWidth: '100%', overflowX: 'scroll' }}>
  130. <ErrorBoundary>
  131. <ReactEcharts option={chartData} style={{ minWidth: '700px' }} />
  132. </ErrorBoundary>
  133. </div>
  134. )
  135. }
  136. else if (language === 'svg' && isSVG) {
  137. return (
  138. <ErrorBoundary>
  139. <SVGRenderer content={content} />
  140. </ErrorBoundary>
  141. )
  142. }
  143. else {
  144. return (
  145. <SyntaxHighlighter
  146. {...props}
  147. style={theme === Theme.light ? atelierHeathLight : atelierHeathDark}
  148. customStyle={{
  149. paddingLeft: 12,
  150. borderBottomLeftRadius: '10px',
  151. borderBottomRightRadius: '10px',
  152. backgroundColor: 'var(--color-components-input-bg-normal)',
  153. }}
  154. language={match?.[1]}
  155. showLineNumbers
  156. PreTag="div"
  157. >
  158. {content}
  159. </SyntaxHighlighter>
  160. )
  161. }
  162. }, [language, match, props, children, chartData, isSVG])
  163. if (inline || !match)
  164. return <code {...props} className={className}>{children}</code>
  165. return (
  166. <div className='relative'>
  167. <div className='flex h-8 items-center justify-between rounded-t-[10px] border-b border-divider-subtle bg-components-input-bg-normal p-1 pl-3'>
  168. <div className='system-xs-semibold-uppercase text-text-secondary'>{languageShowName}</div>
  169. <div className='flex items-center gap-1'>
  170. {(['mermaid', 'svg']).includes(language!) && <SVGBtn isSVG={isSVG} setIsSVG={setIsSVG} />}
  171. <ActionButton>
  172. <CopyIcon content={String(children).replace(/\n$/, '')} />
  173. </ActionButton>
  174. </div>
  175. </div>
  176. {renderCodeContent}
  177. </div>
  178. )
  179. })
  180. CodeBlock.displayName = 'CodeBlock'
  181. const VideoBlock: any = memo(({ node }: any) => {
  182. const srcs = node.children.filter((child: any) => 'properties' in child).map((child: any) => (child as any).properties.src)
  183. if (srcs.length === 0)
  184. return null
  185. return <VideoGallery key={srcs.join()} srcs={srcs} />
  186. })
  187. VideoBlock.displayName = 'VideoBlock'
  188. const AudioBlock: any = memo(({ node }: any) => {
  189. const srcs = node.children.filter((child: any) => 'properties' in child).map((child: any) => (child as any).properties.src)
  190. if (srcs.length === 0)
  191. return null
  192. return <AudioGallery key={srcs.join()} srcs={srcs} />
  193. })
  194. AudioBlock.displayName = 'AudioBlock'
  195. const ScriptBlock = memo(({ node }: any) => {
  196. const scriptContent = node.children[0]?.value || ''
  197. return `<script>${scriptContent}</script>`
  198. })
  199. ScriptBlock.displayName = 'ScriptBlock'
  200. const Paragraph = (paragraph: any) => {
  201. const { node }: any = paragraph
  202. const children_node = node.children
  203. if (children_node && children_node[0] && 'tagName' in children_node[0] && children_node[0].tagName === 'img') {
  204. return (
  205. <>
  206. <ImageGallery srcs={[children_node[0].properties.src]} />
  207. {
  208. Array.isArray(paragraph.children) ? <p>{paragraph.children.slice(1)}</p> : null
  209. }
  210. </>
  211. )
  212. }
  213. return <p>{paragraph.children}</p>
  214. }
  215. const Img = ({ src }: any) => {
  216. return (<ImageGallery srcs={[src]} />)
  217. }
  218. const Link = ({ node, ...props }: any) => {
  219. if (node.properties?.href && node.properties.href?.toString().startsWith('abbr')) {
  220. // eslint-disable-next-line react-hooks/rules-of-hooks
  221. const { onSend } = useChatContext()
  222. const hidden_text = decodeURIComponent(node.properties.href.toString().split('abbr:')[1])
  223. return <abbr className="cursor-pointer underline !decoration-primary-700 decoration-dashed" onClick={() => onSend?.(hidden_text)} title={node.children[0]?.value}>{node.children[0]?.value}</abbr>
  224. }
  225. else {
  226. return <a {...props} target="_blank" className="cursor-pointer underline !decoration-primary-700 decoration-dashed">{node.children[0] ? node.children[0]?.value : 'Download'}</a>
  227. }
  228. }
  229. export function Markdown(props: { content: string; className?: string; customDisallowedElements?: string[] }) {
  230. const latexContent = flow([
  231. preprocessThinkTag,
  232. preprocessLaTeX,
  233. ])(props.content)
  234. return (
  235. <div className={cn('markdown-body', '!text-text-primary', props.className)}>
  236. <ReactMarkdown
  237. remarkPlugins={[
  238. RemarkGfm,
  239. [RemarkMath, { singleDollarTextMath: false }],
  240. RemarkBreaks,
  241. ]}
  242. rehypePlugins={[
  243. RehypeKatex,
  244. RehypeRaw as any,
  245. // The Rehype plug-in is used to remove the ref attribute of an element
  246. () => {
  247. return (tree) => {
  248. const iterate = (node: any) => {
  249. if (node.type === 'element' && node.properties?.ref)
  250. delete node.properties.ref
  251. if (node.type === 'element' && !/^[a-z][a-z0-9]*$/i.test(node.tagName)) {
  252. node.type = 'text'
  253. node.value = `<${node.tagName}`
  254. }
  255. if (node.children)
  256. node.children.forEach(iterate)
  257. }
  258. tree.children.forEach(iterate)
  259. }
  260. },
  261. ]}
  262. disallowedElements={['iframe', 'head', 'html', 'meta', 'link', 'style', 'body', ...(props.customDisallowedElements || [])]}
  263. components={{
  264. code: CodeBlock,
  265. img: Img,
  266. video: VideoBlock,
  267. audio: AudioBlock,
  268. a: Link,
  269. p: Paragraph,
  270. button: MarkdownButton,
  271. form: MarkdownForm,
  272. script: ScriptBlock as any,
  273. details: ThinkBlock,
  274. }}
  275. >
  276. {/* Markdown detect has problem. */}
  277. {latexContent}
  278. </ReactMarkdown>
  279. </div>
  280. )
  281. }
  282. // **Add an ECharts runtime error handler
  283. // Avoid error #7832 (Crash when ECharts accesses undefined objects)
  284. // This can happen when a component attempts to access an undefined object that references an unregistered map, causing the program to crash.
  285. export default class ErrorBoundary extends Component {
  286. constructor(props: any) {
  287. super(props)
  288. this.state = { hasError: false }
  289. }
  290. componentDidCatch(error: any, errorInfo: any) {
  291. this.setState({ hasError: true })
  292. console.error(error, errorInfo)
  293. }
  294. render() {
  295. // eslint-disable-next-line ts/ban-ts-comment
  296. // @ts-expect-error
  297. if (this.state.hasError)
  298. 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>
  299. // eslint-disable-next-line ts/ban-ts-comment
  300. // @ts-expect-error
  301. return this.props.children
  302. }
  303. }