markdown.tsx 8.1 KB

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