markdown.tsx 8.2 KB

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