Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

markdown.tsx 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. import type { Components } from 'react-markdown'
  2. import ReactMarkdown from 'react-markdown'
  3. import ReactEcharts from 'echarts-for-react'
  4. import 'katex/dist/katex.min.css'
  5. import RemarkMath from 'remark-math'
  6. import RemarkBreaks from 'remark-breaks'
  7. import RehypeKatex from 'rehype-katex'
  8. import RemarkGfm from 'remark-gfm'
  9. import RehypeRaw from 'rehype-raw'
  10. import SyntaxHighlighter from 'react-syntax-highlighter'
  11. import { atelierHeathLight } from 'react-syntax-highlighter/dist/esm/styles/hljs'
  12. import { Component, createContext, memo, useContext, useMemo, useRef, useState } from '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. import type { ElementContentMap } from 'hast'
  26. // Available language https://github.com/react-syntax-highlighter/react-syntax-highlighter/blob/master/AVAILABLE_LANGUAGES_HLJS.MD
  27. const capitalizationLanguageNameMap: Record<string, string> = {
  28. sql: 'SQL',
  29. javascript: 'JavaScript',
  30. java: 'Java',
  31. typescript: 'TypeScript',
  32. vbscript: 'VBScript',
  33. css: 'CSS',
  34. html: 'HTML',
  35. xml: 'XML',
  36. php: 'PHP',
  37. python: 'Python',
  38. yaml: 'Yaml',
  39. mermaid: 'Mermaid',
  40. markdown: 'MarkDown',
  41. makefile: 'MakeFile',
  42. echarts: 'ECharts',
  43. shell: 'Shell',
  44. powershell: 'PowerShell',
  45. json: 'JSON',
  46. latex: 'Latex',
  47. svg: 'SVG',
  48. }
  49. const getCorrectCapitalizationLanguageName = (language: string) => {
  50. if (!language)
  51. return 'Plain'
  52. if (language in capitalizationLanguageNameMap)
  53. return capitalizationLanguageNameMap[language]
  54. return language.charAt(0).toUpperCase() + language.substring(1)
  55. }
  56. const preprocessLaTeX = (content?: string) => {
  57. if (typeof content !== 'string')
  58. return content
  59. return flow([
  60. (str: string) => str.replace(/\\\[(.*?)\\\]/g, (_, equation) => `$$${equation}$$`),
  61. (str: string) => str.replace(/\\\((.*?)\\\)/g, (_, equation) => `$$${equation}$$`),
  62. (str: string) => str.replace(/(^|[^\\])\$(.+?)\$/g, (_, prefix, equation) => `${prefix}$${equation}$`),
  63. ])(content)
  64. }
  65. const preprocessThinkTag = (content: string) => {
  66. if (!content.trim().startsWith('<think>\n'))
  67. return content
  68. return flow([
  69. (str: string) => str.replace('<think>\n', '<details>\n'),
  70. (str: string) => str.replace('\n</think>', '\n[ENDTHINKFLAG]</details>'),
  71. ])(content)
  72. }
  73. export function PreCode(props: { children: any }) {
  74. const ref = useRef<HTMLPreElement>(null)
  75. return (
  76. <pre ref={ref}>
  77. <span
  78. className="copy-code-button"
  79. ></span>
  80. {props.children}
  81. </pre>
  82. )
  83. }
  84. const PreContext = createContext({
  85. // if children not in PreContext, just leave inline true
  86. inline: true,
  87. })
  88. const PreBlock: Components['pre'] = (props) => {
  89. const { ...rest } = props
  90. return <PreContext.Provider value={{
  91. inline: false,
  92. }}>
  93. <pre {...rest} />
  94. </PreContext.Provider>
  95. }
  96. // **Add code block
  97. // Avoid error #185 (Maximum update depth exceeded.
  98. // This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate.
  99. // React limits the number of nested updates to prevent infinite loops.)
  100. // Reference A: https://reactjs.org/docs/error-decoder.html?invariant=185
  101. // Reference B1: https://react.dev/reference/react/memo
  102. // Reference B2: https://react.dev/reference/react/useMemo
  103. // ****
  104. // The original error that occurred in the streaming response during the conversation:
  105. // Error: Minified React error 185;
  106. // visit https://reactjs.org/docs/error-decoder.html?invariant=185 for the full message
  107. // or use the non-minified dev environment for full errors and additional helpful warnings.
  108. const CodeBlock: Components['code'] = memo(({ className, children, ...props }) => {
  109. const { inline } = useContext(PreContext)
  110. const [isSVG, setIsSVG] = useState(true)
  111. const match = /language-(\w+)/.exec(className || '')
  112. const language = match?.[1]
  113. const languageShowName = getCorrectCapitalizationLanguageName(language || '')
  114. const chartData = useMemo(() => {
  115. if (language === 'echarts') {
  116. try {
  117. return JSON.parse(String(children).replace(/\n$/, ''))
  118. }
  119. catch (error) { }
  120. }
  121. return JSON.parse('{"title":{"text":"ECharts error - Wrong JSON format."}}')
  122. }, [language, children])
  123. const renderCodeContent = useMemo(() => {
  124. const content = String(children).replace(/\n$/, '')
  125. if (language === 'mermaid' && isSVG) {
  126. return <Flowchart PrimitiveCode={content} />
  127. }
  128. else if (language === 'echarts') {
  129. return (
  130. <div style={{ minHeight: '350px', minWidth: '100%', overflowX: 'scroll' }}>
  131. <ErrorBoundary>
  132. <ReactEcharts option={chartData} style={{ minWidth: '700px' }} />
  133. </ErrorBoundary>
  134. </div>
  135. )
  136. }
  137. else if (language === 'svg' && isSVG) {
  138. return (
  139. <ErrorBoundary>
  140. <SVGRenderer content={content} />
  141. </ErrorBoundary>
  142. )
  143. }
  144. else {
  145. return (
  146. <SyntaxHighlighter
  147. {...props as any}
  148. style={atelierHeathLight}
  149. customStyle={{
  150. paddingLeft: 12,
  151. backgroundColor: '#fff',
  152. }}
  153. language={match?.[1]}
  154. showLineNumbers
  155. PreTag="div"
  156. >
  157. {content}
  158. </SyntaxHighlighter>
  159. )
  160. }
  161. }, [language, match, props, children, chartData, isSVG])
  162. if (inline || !match)
  163. return <code {...props} className={className}>{children}</code>
  164. return (
  165. <div>
  166. <div
  167. className='flex justify-between h-8 items-center p-1 pl-3 border-b'
  168. style={{
  169. borderColor: 'rgba(0, 0, 0, 0.05)',
  170. }}
  171. >
  172. <div className='text-[13px] text-gray-500 font-normal'>{languageShowName}</div>
  173. <div style={{ display: 'flex' }}>
  174. {(['mermaid', 'svg']).includes(language!) && <SVGBtn isSVG={isSVG} setIsSVG={setIsSVG} />}
  175. <CopyBtn
  176. className='mr-1'
  177. value={String(children).replace(/\n$/, '')}
  178. isPlain
  179. />
  180. </div>
  181. </div>
  182. {renderCodeContent}
  183. </div>
  184. )
  185. })
  186. // CodeBlock.displayName = 'CodeBlock'
  187. const VideoBlock: Components['video'] = memo(({ node }) => {
  188. const srcs = node!.children.filter(child => 'properties' in child).map(child => (child as any).properties.src)
  189. if (srcs.length === 0)
  190. return null
  191. return <VideoGallery key={srcs.join()} srcs={srcs} />
  192. })
  193. // VideoBlock.displayName = 'VideoBlock'
  194. const AudioBlock: Components['audio'] = memo(({ node }) => {
  195. const srcs = node!.children.filter(child => 'properties' in child).map(child => (child as any).properties.src)
  196. if (srcs.length === 0)
  197. return null
  198. return <AudioGallery key={srcs.join()} srcs={srcs} />
  199. })
  200. // AudioBlock.displayName = 'AudioBlock'
  201. const ScriptBlock = memo(({ node }: any) => {
  202. const scriptContent = node.children[0]?.value || ''
  203. return `<script>${scriptContent}</script>`
  204. })
  205. ScriptBlock.displayName = 'ScriptBlock'
  206. const Paragraph: Components['p'] = ({ node, children }) => {
  207. const children_node = node!.children
  208. if (children_node && children_node[0] && 'tagName' in children_node[0] && children_node[0].tagName === 'img')
  209. return <ImageGallery srcs={[children_node?.[0]?.properties?.src as string]} />
  210. return <p>{children}</p>
  211. }
  212. const Img: Components['img'] = ({ src }) => {
  213. return (<ImageGallery srcs={[src!]} />)
  214. }
  215. const Link: Components['a'] = ({ node, ...props }) => {
  216. if (node!.properties?.href && node!.properties.href?.toString().startsWith('abbr')) {
  217. // eslint-disable-next-line react-hooks/rules-of-hooks
  218. const { onSend } = useChatContext()
  219. const hidden_text = decodeURIComponent(node!.properties.href.toString().split('abbr:')[1])
  220. const title = (node!.children[0] as ElementContentMap['text'])?.value
  221. return <abbr className="underline decoration-dashed !decoration-primary-700 cursor-pointer" onClick={() => onSend?.(hidden_text)} title={title}>{title}</abbr>
  222. }
  223. else {
  224. const firstChild = node?.children?.[0] as ElementContentMap['text'] | undefined
  225. return <a {...props} target="_blank" className="underline decoration-dashed !decoration-primary-700 cursor-pointer">{
  226. firstChild
  227. ? firstChild.value
  228. : 'Download'
  229. }</a>
  230. }
  231. }
  232. export function Markdown(props: { content: string; className?: string }) {
  233. const latexContent = flow([
  234. preprocessThinkTag,
  235. preprocessLaTeX,
  236. ])(props.content)
  237. return (
  238. <div className={cn('markdown-body', props.className)}>
  239. <ReactMarkdown
  240. remarkPlugins={[
  241. RemarkGfm,
  242. [RemarkMath, { singleDollarTextMath: false }],
  243. RemarkBreaks,
  244. ]}
  245. rehypePlugins={[
  246. RehypeKatex,
  247. RehypeRaw as any,
  248. // The Rehype plug-in is used to remove the ref attribute of an element
  249. () => {
  250. return (tree) => {
  251. const iterate = (node: any) => {
  252. if (node.type === 'element' && node.properties?.ref)
  253. delete node.properties.ref
  254. if (node.children)
  255. node.children.forEach(iterate)
  256. }
  257. tree.children.forEach(iterate)
  258. }
  259. },
  260. ]}
  261. disallowedElements={['iframe', 'head', 'html', 'meta', 'link', 'style', 'body']}
  262. components={{
  263. pre: PreBlock,
  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,
  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. }