markdown.tsx 7.7 KB

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