markdown.tsx 6.4 KB

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