markdown.tsx 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  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. content.replace(/\\\[(.*?)\\\]/gs, (_, equation) => `$$${equation}$$`)
  41. .replace(/\\\((.*?)\\\)/gs, (_, equation) => `$${equation}$`)
  42. export function PreCode(props: { children: any }) {
  43. const ref = useRef<HTMLPreElement>(null)
  44. return (
  45. <pre ref={ref}>
  46. <span
  47. className="copy-code-button"
  48. onClick={() => {
  49. if (ref.current) {
  50. const code = ref.current.innerText
  51. // copyToClipboard(code);
  52. }
  53. }}
  54. ></span>
  55. {props.children}
  56. </pre>
  57. )
  58. }
  59. const useLazyLoad = (ref: RefObject<Element>): boolean => {
  60. const [isIntersecting, setIntersecting] = useState<boolean>(false)
  61. useEffect(() => {
  62. const observer = new IntersectionObserver(([entry]) => {
  63. if (entry.isIntersecting) {
  64. setIntersecting(true)
  65. observer.disconnect()
  66. }
  67. })
  68. if (ref.current)
  69. observer.observe(ref.current)
  70. return () => {
  71. observer.disconnect()
  72. }
  73. }, [ref])
  74. return isIntersecting
  75. }
  76. export function Markdown(props: { content: string; className?: string }) {
  77. const [isSVG, setIsSVG] = useState(false)
  78. const latexContent = preprocessLaTeX(props.content)
  79. return (
  80. <div className={cn(props.className, 'markdown-body')}>
  81. <ReactMarkdown
  82. remarkPlugins={[[RemarkMath, { singleDollarTextMath: false }], RemarkGfm, RemarkBreaks]}
  83. rehypePlugins={[
  84. RehypeKatex as any,
  85. ]}
  86. components={{
  87. code({ inline, className, children, ...props }) {
  88. const match = /language-(\w+)/.exec(className || '')
  89. const language = match?.[1]
  90. const languageShowName = getCorrectCapitalizationLanguageName(language || '')
  91. return (!inline && match)
  92. ? (
  93. <div>
  94. <div
  95. className='flex justify-between h-8 items-center p-1 pl-3 border-b'
  96. style={{
  97. borderColor: 'rgba(0, 0, 0, 0.05)',
  98. }}
  99. >
  100. <div className='text-[13px] text-gray-500 font-normal'>{languageShowName}</div>
  101. <div style={{ display: 'flex' }}>
  102. {language === 'mermaid'
  103. && <SVGBtn
  104. isSVG={isSVG}
  105. setIsSVG={setIsSVG}
  106. />
  107. }
  108. <CopyBtn
  109. className='mr-1'
  110. value={String(children).replace(/\n$/, '')}
  111. isPlain
  112. />
  113. </div>
  114. </div>
  115. {(language === 'mermaid' && isSVG)
  116. ? (<Flowchart PrimitiveCode={String(children).replace(/\n$/, '')} />)
  117. : (<SyntaxHighlighter
  118. {...props}
  119. style={atelierHeathLight}
  120. customStyle={{
  121. paddingLeft: 12,
  122. backgroundColor: '#fff',
  123. }}
  124. language={match[1]}
  125. showLineNumbers
  126. PreTag="div"
  127. >
  128. {String(children).replace(/\n$/, '')}
  129. </SyntaxHighlighter>)}
  130. </div>
  131. )
  132. : (
  133. <code {...props} className={className}>
  134. {children}
  135. </code>
  136. )
  137. },
  138. img({ src, alt, ...props }) {
  139. return (
  140. // eslint-disable-next-line @next/next/no-img-element
  141. <img
  142. src={src}
  143. alt={alt}
  144. width={250}
  145. height={250}
  146. 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"
  147. {...props}
  148. />
  149. )
  150. },
  151. p: (paragraph) => {
  152. const { node }: any = paragraph
  153. if (node.children[0].tagName === 'img') {
  154. const image = node.children[0]
  155. return (
  156. <>
  157. {/* eslint-disable-next-line @next/next/no-img-element */}
  158. <img
  159. src={image.properties.src}
  160. width={250}
  161. height={250}
  162. 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"
  163. alt={image.properties.alt}
  164. />
  165. <p>{paragraph.children.slice(1)}</p>
  166. </>
  167. )
  168. }
  169. return <p>{paragraph.children}</p>
  170. },
  171. }}
  172. linkTarget='_blank'
  173. >
  174. {/* Markdown detect has problem. */}
  175. {latexContent}
  176. </ReactMarkdown>
  177. </div>
  178. )
  179. }