markdown.tsx 7.8 KB

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