markdown.tsx 11 KB

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