Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

markdown.tsx 12KB

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