markdown.tsx 7.1 KB

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