markdown.tsx 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. import ReactMarkdown from "react-markdown";
  2. import { Image } from "antd";
  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 RehypeHighlight from "rehype-highlight";
  8. import { useRef, useState, RefObject, useEffect, useMemo } from "react";
  9. import { copyToClipboard, useWindowSize } from "../utils";
  10. import mermaid from "mermaid";
  11. import LoadingIcon from "../icons/three-dots.svg";
  12. import React from "react";
  13. import { useDebouncedCallback } from "use-debounce";
  14. import { showImageModal, FullScreen } from "./ui-lib";
  15. import { ArtifactsShareButton, HTMLPreview } from "./artifacts";
  16. import { Plugin } from "../constant";
  17. import { useChatStore } from "../store";
  18. import "katex/dist/katex.min.css";
  19. export function Mermaid(props: { code: string }) {
  20. const ref = useRef<HTMLDivElement>(null);
  21. const [hasError, setHasError] = useState(false);
  22. useEffect(() => {
  23. if (props.code && ref.current) {
  24. mermaid
  25. .run({
  26. nodes: [ref.current],
  27. suppressErrors: true,
  28. })
  29. .catch((e) => {
  30. setHasError(true);
  31. console.error("[Mermaid] ", e.message);
  32. });
  33. }
  34. // eslint-disable-next-line react-hooks/exhaustive-deps
  35. }, [props.code]);
  36. function viewSvgInNewWindow() {
  37. const svg = ref.current?.querySelector("svg");
  38. if (!svg) return;
  39. const text = new XMLSerializer().serializeToString(svg);
  40. const blob = new Blob([text], { type: "image/svg+xml" });
  41. showImageModal(URL.createObjectURL(blob));
  42. }
  43. if (hasError) {
  44. return null;
  45. }
  46. return (
  47. <div
  48. className="no-dark mermaid"
  49. style={{
  50. cursor: "pointer",
  51. overflow: "auto",
  52. }}
  53. ref={ref}
  54. onClick={() => viewSvgInNewWindow()}
  55. >
  56. {props.code}
  57. </div>
  58. );
  59. }
  60. export function PreCode(props: { children: any }) {
  61. const ref = useRef<HTMLPreElement>(null);
  62. const refText = ref.current?.innerText;
  63. const [mermaidCode, setMermaidCode] = useState("");
  64. const [htmlCode, setHtmlCode] = useState("");
  65. const { height } = useWindowSize();
  66. const chatStore = useChatStore();
  67. const session = chatStore.currentSession();
  68. const plugins = session.mask?.plugin;
  69. const renderArtifacts = useDebouncedCallback(() => {
  70. if (!ref.current) return;
  71. const mermaidDom = ref.current.querySelector("code.language-mermaid");
  72. if (mermaidDom) {
  73. setMermaidCode((mermaidDom as HTMLElement).innerText);
  74. }
  75. const htmlDom = ref.current.querySelector("code.language-html");
  76. if (htmlDom) {
  77. setHtmlCode((htmlDom as HTMLElement).innerText);
  78. } else if (refText?.startsWith("<!DOCTYPE")) {
  79. setHtmlCode(refText);
  80. }
  81. }, 600);
  82. useEffect(() => {
  83. setTimeout(renderArtifacts, 1);
  84. // eslint-disable-next-line react-hooks/exhaustive-deps
  85. }, [refText]);
  86. const enableArtifacts = useMemo(
  87. () => plugins?.includes(Plugin.Artifacts),
  88. [plugins],
  89. );
  90. //Wrap the paragraph for plain-text
  91. useEffect(() => {
  92. if (ref.current) {
  93. const codeElements = ref.current.querySelectorAll(
  94. "code",
  95. ) as NodeListOf<HTMLElement>;
  96. const wrapLanguages = [
  97. "",
  98. "think",
  99. "md",
  100. "markdown",
  101. "text",
  102. "txt",
  103. "plaintext",
  104. "tex",
  105. "latex",
  106. ];
  107. codeElements.forEach((codeElement) => {
  108. let languageClass = codeElement.className.match(/language-(\w+)/);
  109. let name = languageClass ? languageClass[1] : "";
  110. if (wrapLanguages.includes(name)) {
  111. codeElement.style.whiteSpace = "pre-wrap";
  112. }
  113. });
  114. }
  115. }, []);
  116. return (
  117. <>
  118. <pre ref={ref}>
  119. <span
  120. className="copy-code-button"
  121. onClick={() => {
  122. if (ref.current) {
  123. const code = ref.current.innerText;
  124. copyToClipboard(code);
  125. }
  126. }}
  127. ></span>
  128. {props.children}
  129. </pre>
  130. {mermaidCode.length > 0 && (
  131. <Mermaid code={mermaidCode} key={mermaidCode} />
  132. )}
  133. {htmlCode.length > 0 && enableArtifacts && (
  134. <FullScreen className="no-dark html" right={70}>
  135. <ArtifactsShareButton
  136. style={{ position: "absolute", right: 20, top: 10 }}
  137. getCode={() => htmlCode}
  138. />
  139. <HTMLPreview
  140. code={htmlCode}
  141. autoHeight={!document.fullscreenElement}
  142. height={!document.fullscreenElement ? 600 : height}
  143. />
  144. </FullScreen>
  145. )}
  146. </>
  147. );
  148. }
  149. function escapeDollarNumber(text: string) {
  150. let escapedText = "";
  151. for (let i = 0; i < text.length; i += 1) {
  152. let char = text[i];
  153. const nextChar = text[i + 1] || " ";
  154. if (char === "$" && nextChar >= "0" && nextChar <= "9") {
  155. char = "\\$";
  156. }
  157. escapedText += char;
  158. }
  159. return escapedText;
  160. }
  161. function escapeBrackets(text: string) {
  162. const pattern =
  163. /(```[\s\S]*?```|`.*?`)|\\\[([\s\S]*?[^\\])\\\]|\\\((.*?)\\\)/g;
  164. return text.replace(
  165. pattern,
  166. (match, codeBlock, squareBracket, roundBracket) => {
  167. if (codeBlock) {
  168. return codeBlock;
  169. } else if (squareBracket) {
  170. return `$$${squareBracket}$$`;
  171. } else if (roundBracket) {
  172. return `$${roundBracket}$`;
  173. }
  174. return match;
  175. },
  176. );
  177. }
  178. function _MarkDownContent(props: { content: string }) {
  179. const escapedContent = useMemo(() => {
  180. return escapeBrackets(escapeDollarNumber(props.content));
  181. }, [props.content]);
  182. return (
  183. <ReactMarkdown
  184. remarkPlugins={[RemarkMath, RemarkGfm, RemarkBreaks]}
  185. rehypePlugins={[
  186. RehypeKatex,
  187. [
  188. RehypeHighlight,
  189. {
  190. detect: false,
  191. ignoreMissing: true,
  192. },
  193. ],
  194. ]}
  195. // 控制不同标签的显示样式
  196. components={{
  197. pre: PreCode,
  198. code: ({ className, children }) => {
  199. // console.log('className, children-----3',className, children)
  200. if (className && className.includes('language-think')) {
  201. return (
  202. <code style={{ whiteSpace: 'pre-wrap', background: '#f3f4f6', color: '#525252' }}>
  203. {children}
  204. </code>
  205. );
  206. } else {
  207. return children;
  208. }
  209. },
  210. p: (pProps) => {
  211. // console.log('pProps-----2',pProps)
  212. return <p {...pProps} dir="auto" />
  213. },
  214. a: (aProps) => {
  215. // console.log('aProps-----4',aProps)
  216. const href = aProps.href || "";
  217. const isInternal = /^\/#/i.test(href);
  218. const target = isInternal ? "_self" : aProps.target ?? "_blank";
  219. return <a {...aProps} target={target} />;
  220. },
  221. img: ({ src, alt }) => (
  222. // console.log('src, alt-----5',src, alt),
  223. <div style={{ width: '100%', height: 'auto', cursor: 'pointer' }}>
  224. <Image
  225. width='80%'
  226. src={src}
  227. alt={alt}
  228. preview={{
  229. mask: null
  230. }}
  231. />
  232. </div>
  233. ),
  234. }}
  235. >
  236. {escapedContent}
  237. </ReactMarkdown >
  238. );
  239. }
  240. export const MarkdownContent = React.memo(_MarkDownContent);
  241. export function Markdown(
  242. props: {
  243. content: string;
  244. loading?: boolean;
  245. fontSize?: number;
  246. fontFamily?: string;
  247. parentRef?: RefObject<HTMLDivElement>;
  248. defaultShow?: boolean;
  249. } & React.DOMAttributes<HTMLDivElement>,
  250. ) {
  251. const mdRef = useRef<HTMLDivElement>(null);
  252. return (
  253. <div
  254. className="markdown-body"
  255. style={{
  256. fontSize: `${props.fontSize ?? 14}px`,
  257. fontFamily: props.fontFamily || "inherit",
  258. }}
  259. ref={mdRef}
  260. onContextMenu={props.onContextMenu}
  261. onDoubleClickCapture={props.onDoubleClickCapture}
  262. dir="auto"
  263. >
  264. {props.loading ? (
  265. <LoadingIcon />
  266. ) : (
  267. <MarkdownContent content={props.content} />
  268. )}
  269. </div>
  270. );
  271. }