markdown.tsx 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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 SyntaxHighlighter from 'react-syntax-highlighter'
  9. import { atelierHeathLight } from 'react-syntax-highlighter/dist/esm/styles/hljs'
  10. import type { RefObject } from 'react'
  11. import { memo, useEffect, useMemo, useRef, useState } from 'react'
  12. import type { CodeComponent } from 'react-markdown/lib/ast-to-react'
  13. import cn from '@/utils/classnames'
  14. import CopyBtn from '@/app/components/base/copy-btn'
  15. import SVGBtn from '@/app/components/base/svg'
  16. import Flowchart from '@/app/components/base/mermaid'
  17. // Available language https://github.com/react-syntax-highlighter/react-syntax-highlighter/blob/master/AVAILABLE_LANGUAGES_HLJS.MD
  18. const capitalizationLanguageNameMap: Record<string, string> = {
  19. sql: 'SQL',
  20. javascript: 'JavaScript',
  21. java: 'Java',
  22. typescript: 'TypeScript',
  23. vbscript: 'VBScript',
  24. css: 'CSS',
  25. html: 'HTML',
  26. xml: 'XML',
  27. php: 'PHP',
  28. python: 'Python',
  29. yaml: 'Yaml',
  30. mermaid: 'Mermaid',
  31. markdown: 'MarkDown',
  32. makefile: 'MakeFile',
  33. echarts: 'ECharts',
  34. }
  35. const getCorrectCapitalizationLanguageName = (language: string) => {
  36. if (!language)
  37. return 'Plain'
  38. if (language in capitalizationLanguageNameMap)
  39. return capitalizationLanguageNameMap[language]
  40. return language.charAt(0).toUpperCase() + language.substring(1)
  41. }
  42. const preprocessLaTeX = (content: string) => {
  43. if (typeof content !== 'string')
  44. return content
  45. return content.replace(/\\\[(.*?)\\\]/gs, (_, equation) => `$$${equation}$$`)
  46. .replace(/\\\((.*?)\\\)/gs, (_, equation) => `$$${equation}$$`)
  47. .replace(/(^|[^\\])\$(.+?)\$/gs, (_, prefix, equation) => `${prefix}$${equation}$`)
  48. }
  49. export function PreCode(props: { children: any }) {
  50. const ref = useRef<HTMLPreElement>(null)
  51. return (
  52. <pre ref={ref}>
  53. <span
  54. className="copy-code-button"
  55. onClick={() => {
  56. if (ref.current) {
  57. const code = ref.current.innerText
  58. // copyToClipboard(code);
  59. }
  60. }}
  61. ></span>
  62. {props.children}
  63. </pre>
  64. )
  65. }
  66. const useLazyLoad = (ref: RefObject<Element>): boolean => {
  67. const [isIntersecting, setIntersecting] = useState<boolean>(false)
  68. useEffect(() => {
  69. const observer = new IntersectionObserver(([entry]) => {
  70. if (entry.isIntersecting) {
  71. setIntersecting(true)
  72. observer.disconnect()
  73. }
  74. })
  75. if (ref.current)
  76. observer.observe(ref.current)
  77. return () => {
  78. observer.disconnect()
  79. }
  80. }, [ref])
  81. return isIntersecting
  82. }
  83. // **Add code block
  84. // Avoid error #185 (Maximum update depth exceeded.
  85. // This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate.
  86. // React limits the number of nested updates to prevent infinite loops.)
  87. // Reference A: https://reactjs.org/docs/error-decoder.html?invariant=185
  88. // Reference B1: https://react.dev/reference/react/memo
  89. // Reference B2: https://react.dev/reference/react/useMemo
  90. // ****
  91. // The original error that occurred in the streaming response during the conversation:
  92. // Error: Minified React error 185;
  93. // visit https://reactjs.org/docs/error-decoder.html?invariant=185 for the full message
  94. // or use the non-minified dev environment for full errors and additional helpful warnings.
  95. const CodeBlock: CodeComponent = memo(({ inline, className, children, ...props }) => {
  96. const [isSVG, setIsSVG] = useState(true)
  97. const match = /language-(\w+)/.exec(className || '')
  98. const language = match?.[1]
  99. const languageShowName = getCorrectCapitalizationLanguageName(language || '')
  100. let chartData = JSON.parse(String('{"title":{"text":"Something went wrong."}}').replace(/\n$/, ''))
  101. if (language === 'echarts') {
  102. try {
  103. chartData = JSON.parse(String(children).replace(/\n$/, ''))
  104. }
  105. catch (error) {
  106. }
  107. }
  108. // Use `useMemo` to ensure that `SyntaxHighlighter` only re-renders when necessary
  109. return useMemo(() => {
  110. return (!inline && match)
  111. ? (
  112. <div>
  113. <div
  114. className='flex justify-between h-8 items-center p-1 pl-3 border-b'
  115. style={{
  116. borderColor: 'rgba(0, 0, 0, 0.05)',
  117. }}
  118. >
  119. <div className='text-[13px] text-gray-500 font-normal'>{languageShowName}</div>
  120. <div style={{ display: 'flex' }}>
  121. {language === 'mermaid'
  122. && <SVGBtn
  123. isSVG={isSVG}
  124. setIsSVG={setIsSVG}
  125. />
  126. }
  127. <CopyBtn
  128. className='mr-1'
  129. value={String(children).replace(/\n$/, '')}
  130. isPlain
  131. />
  132. </div>
  133. </div>
  134. {(language === 'mermaid' && isSVG)
  135. ? (<Flowchart PrimitiveCode={String(children).replace(/\n$/, '')} />)
  136. : (
  137. (language === 'echarts')
  138. ? (<div style={{ minHeight: '250px', minWidth: '250px' }}><ReactEcharts
  139. option={chartData}
  140. >
  141. </ReactEcharts></div>)
  142. : (<SyntaxHighlighter
  143. {...props}
  144. style={atelierHeathLight}
  145. customStyle={{
  146. paddingLeft: 12,
  147. backgroundColor: '#fff',
  148. }}
  149. language={match[1]}
  150. showLineNumbers
  151. PreTag="div"
  152. >
  153. {String(children).replace(/\n$/, '')}
  154. </SyntaxHighlighter>))}
  155. </div>
  156. )
  157. : (
  158. <code {...props} className={className}>
  159. {children}
  160. </code>
  161. )
  162. }, [children, className, inline, isSVG, language, languageShowName, match, props])
  163. })
  164. CodeBlock.displayName = 'CodeBlock'
  165. export function Markdown(props: { content: string; className?: string }) {
  166. const latexContent = preprocessLaTeX(props.content)
  167. return (
  168. <div className={cn(props.className, 'markdown-body')}>
  169. <ReactMarkdown
  170. remarkPlugins={[[RemarkMath, { singleDollarTextMath: false }], RemarkGfm, RemarkBreaks]}
  171. rehypePlugins={[
  172. RehypeKatex as any,
  173. ]}
  174. components={{
  175. code: CodeBlock,
  176. img({ src, alt, ...props }) {
  177. return (
  178. // eslint-disable-next-line @next/next/no-img-element
  179. <img
  180. src={src}
  181. alt={alt}
  182. width={250}
  183. height={250}
  184. className="max-w-full h-auto align-middle border-none rounded-lg shadow-md hover:shadow-lg transition-shadow duration-300 ease-in-out mt-2 mb-2"
  185. {...props}
  186. />
  187. )
  188. },
  189. p: (paragraph) => {
  190. const { node }: any = paragraph
  191. if (node.children[0].tagName === 'img') {
  192. const image = node.children[0]
  193. return (
  194. <>
  195. {/* eslint-disable-next-line @next/next/no-img-element */}
  196. <img
  197. src={image.properties.src}
  198. width={250}
  199. height={250}
  200. className="max-w-full h-auto align-middle border-none rounded-lg shadow-md hover:shadow-lg transition-shadow duration-300 ease-in-out mt-2 mb-2"
  201. alt={image.properties.alt}
  202. />
  203. <p>{paragraph.children.slice(1)}</p>
  204. </>
  205. )
  206. }
  207. return <p>{paragraph.children}</p>
  208. },
  209. }}
  210. linkTarget='_blank'
  211. >
  212. {/* Markdown detect has problem. */}
  213. {latexContent}
  214. </ReactMarkdown>
  215. </div>
  216. )
  217. }