markdown.tsx 11 KB

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