markdown.tsx 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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 { useEffect, useRef, useState } from 'react'
  11. import cn from 'classnames'
  12. import CopyBtn from '@/app/components/app/chat/copy-btn'
  13. import SVGBtn from '@/app/components/app/chat/svg'
  14. import Flowchart from '@/app/components/app/chat/mermaid'
  15. // Available language https://github.com/react-syntax-highlighter/react-syntax-highlighter/blob/master/AVAILABLE_LANGUAGES_HLJS.MD
  16. const capitalizationLanguageNameMap: Record<string, string> = {
  17. sql: 'SQL',
  18. javascript: 'JavaScript',
  19. java: 'Java',
  20. typescript: 'TypeScript',
  21. vbscript: 'VBScript',
  22. css: 'CSS',
  23. html: 'HTML',
  24. xml: 'XML',
  25. php: 'PHP',
  26. python: 'Python',
  27. yaml: 'Yaml',
  28. mermaid: 'Mermaid',
  29. markdown: 'MarkDown',
  30. makefile: 'MakeFile',
  31. }
  32. const getCorrectCapitalizationLanguageName = (language: string) => {
  33. if (!language)
  34. return 'Plain'
  35. if (language in capitalizationLanguageNameMap)
  36. return capitalizationLanguageNameMap[language]
  37. return language.charAt(0).toUpperCase() + language.substring(1)
  38. }
  39. const preprocessLaTeX = (content: string) => {
  40. if (typeof content !== 'string')
  41. return content
  42. return content.replace(/\\\[(.*?)\\\]/gs, (_, equation) => `$$${equation}$$`)
  43. .replace(/\\\((.*?)\\\)/gs, (_, equation) => `$${equation}$`)
  44. }
  45. export function PreCode(props: { children: any }) {
  46. const ref = useRef<HTMLPreElement>(null)
  47. return (
  48. <pre ref={ref}>
  49. <span
  50. className="copy-code-button"
  51. onClick={() => {
  52. if (ref.current) {
  53. const code = ref.current.innerText
  54. // copyToClipboard(code);
  55. }
  56. }}
  57. ></span>
  58. {props.children}
  59. </pre>
  60. )
  61. }
  62. const useLazyLoad = (ref: RefObject<Element>): boolean => {
  63. const [isIntersecting, setIntersecting] = useState<boolean>(false)
  64. useEffect(() => {
  65. const observer = new IntersectionObserver(([entry]) => {
  66. if (entry.isIntersecting) {
  67. setIntersecting(true)
  68. observer.disconnect()
  69. }
  70. })
  71. if (ref.current)
  72. observer.observe(ref.current)
  73. return () => {
  74. observer.disconnect()
  75. }
  76. }, [ref])
  77. return isIntersecting
  78. }
  79. export function Markdown(props: { content: string; className?: string }) {
  80. const [isSVG, setIsSVG] = useState(false)
  81. const latexContent = preprocessLaTeX(props.content)
  82. return (
  83. <div className={cn(props.className, 'markdown-body')}>
  84. <ReactMarkdown
  85. remarkPlugins={[[RemarkMath, { singleDollarTextMath: false }], RemarkGfm, RemarkBreaks]}
  86. rehypePlugins={[
  87. RehypeKatex as any,
  88. ]}
  89. components={{
  90. code({ inline, className, children, ...props }) {
  91. const match = /language-(\w+)/.exec(className || '')
  92. const language = match?.[1]
  93. const languageShowName = getCorrectCapitalizationLanguageName(language || '')
  94. return (!inline && match)
  95. ? (
  96. <div>
  97. <div
  98. className='flex justify-between h-8 items-center p-1 pl-3 border-b'
  99. style={{
  100. borderColor: 'rgba(0, 0, 0, 0.05)',
  101. }}
  102. >
  103. <div className='text-[13px] text-gray-500 font-normal'>{languageShowName}</div>
  104. <div style={{ display: 'flex' }}>
  105. {language === 'mermaid'
  106. && <SVGBtn
  107. isSVG={isSVG}
  108. setIsSVG={setIsSVG}
  109. />
  110. }
  111. <CopyBtn
  112. className='mr-1'
  113. value={String(children).replace(/\n$/, '')}
  114. isPlain
  115. />
  116. </div>
  117. </div>
  118. {(language === 'mermaid' && isSVG)
  119. ? (<Flowchart PrimitiveCode={String(children).replace(/\n$/, '')} />)
  120. : (<SyntaxHighlighter
  121. {...props}
  122. style={atelierHeathLight}
  123. customStyle={{
  124. paddingLeft: 12,
  125. backgroundColor: '#fff',
  126. }}
  127. language={match[1]}
  128. showLineNumbers
  129. PreTag="div"
  130. >
  131. {String(children).replace(/\n$/, '')}
  132. </SyntaxHighlighter>)}
  133. </div>
  134. )
  135. : (
  136. <code {...props} className={className}>
  137. {children}
  138. </code>
  139. )
  140. },
  141. img({ src, alt, ...props }) {
  142. return (
  143. // eslint-disable-next-line @next/next/no-img-element
  144. <img
  145. src={src}
  146. alt={alt}
  147. width={250}
  148. height={250}
  149. 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"
  150. {...props}
  151. />
  152. )
  153. },
  154. p: (paragraph) => {
  155. const { node }: any = paragraph
  156. if (node.children[0].tagName === 'img') {
  157. const image = node.children[0]
  158. return (
  159. <>
  160. {/* eslint-disable-next-line @next/next/no-img-element */}
  161. <img
  162. src={image.properties.src}
  163. width={250}
  164. height={250}
  165. 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"
  166. alt={image.properties.alt}
  167. />
  168. <p>{paragraph.children.slice(1)}</p>
  169. </>
  170. )
  171. }
  172. return <p>{paragraph.children}</p>
  173. },
  174. }}
  175. linkTarget='_blank'
  176. >
  177. {/* Markdown detect has problem. */}
  178. {latexContent}
  179. </ReactMarkdown>
  180. </div>
  181. )
  182. }