markdown.tsx 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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. import { SAAS_CHAT_URL } from "@/app/constant";
  25. import { trackConversationGuideToCPaymentClick } from "../utils/auth-settings-events";
  26. export function Mermaid(props: { code: string }) {
  27. const ref = useRef<HTMLDivElement>(null);
  28. const [hasError, setHasError] = useState(false);
  29. useEffect(() => {
  30. if (props.code && ref.current) {
  31. mermaid
  32. .run({
  33. nodes: [ref.current],
  34. suppressErrors: true,
  35. })
  36. .catch((e) => {
  37. setHasError(true);
  38. console.error("[Mermaid] ", e.message);
  39. });
  40. }
  41. // eslint-disable-next-line react-hooks/exhaustive-deps
  42. }, [props.code]);
  43. function viewSvgInNewWindow() {
  44. const svg = ref.current?.querySelector("svg");
  45. if (!svg) return;
  46. const text = new XMLSerializer().serializeToString(svg);
  47. const blob = new Blob([text], { type: "image/svg+xml" });
  48. showImageModal(URL.createObjectURL(blob));
  49. }
  50. if (hasError) {
  51. return null;
  52. }
  53. return (
  54. <div
  55. className="no-dark mermaid"
  56. style={{
  57. cursor: "pointer",
  58. overflow: "auto",
  59. }}
  60. ref={ref}
  61. onClick={() => viewSvgInNewWindow()}
  62. >
  63. {props.code}
  64. </div>
  65. );
  66. }
  67. export function PreCode(props: { children: any }) {
  68. const ref = useRef<HTMLPreElement>(null);
  69. const previewRef = useRef<HTMLPreviewHander>(null);
  70. const [mermaidCode, setMermaidCode] = useState("");
  71. const [htmlCode, setHtmlCode] = useState("");
  72. const { height } = useWindowSize();
  73. const chatStore = useChatStore();
  74. const session = chatStore.currentSession();
  75. const renderArtifacts = useDebouncedCallback(() => {
  76. if (!ref.current) return;
  77. const mermaidDom = ref.current.querySelector("code.language-mermaid");
  78. if (mermaidDom) {
  79. setMermaidCode((mermaidDom as HTMLElement).innerText);
  80. }
  81. const htmlDom = ref.current.querySelector("code.language-html");
  82. const refText = ref.current.querySelector("code")?.innerText;
  83. if (htmlDom) {
  84. setHtmlCode((htmlDom as HTMLElement).innerText);
  85. } else if (refText?.startsWith("<!DOCTYPE")) {
  86. setHtmlCode(refText);
  87. }
  88. }, 600);
  89. const enableArtifacts = session.mask?.enableArtifacts !== false;
  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. "md",
  99. "markdown",
  100. "text",
  101. "txt",
  102. "plaintext",
  103. "tex",
  104. "latex",
  105. ];
  106. codeElements.forEach((codeElement) => {
  107. let languageClass = codeElement.className.match(/language-(\w+)/);
  108. let name = languageClass ? languageClass[1] : "";
  109. if (wrapLanguages.includes(name)) {
  110. codeElement.style.whiteSpace = "pre-wrap";
  111. }
  112. });
  113. setTimeout(renderArtifacts, 1);
  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. <IconButton
  140. style={{ position: "absolute", right: 120, top: 10 }}
  141. bordered
  142. icon={<ReloadButtonIcon />}
  143. shadow
  144. onClick={() => previewRef.current?.reload()}
  145. />
  146. <HTMLPreview
  147. ref={previewRef}
  148. code={htmlCode}
  149. autoHeight={!document.fullscreenElement}
  150. height={!document.fullscreenElement ? 600 : height}
  151. />
  152. </FullScreen>
  153. )}
  154. </>
  155. );
  156. }
  157. function CustomCode(props: { children: any; className?: string }) {
  158. const ref = useRef<HTMLPreElement>(null);
  159. const [collapsed, setCollapsed] = useState(true);
  160. const [showToggle, setShowToggle] = useState(false);
  161. useEffect(() => {
  162. if (ref.current) {
  163. const codeHeight = ref.current.scrollHeight;
  164. setShowToggle(codeHeight > 400);
  165. ref.current.scrollTop = ref.current.scrollHeight;
  166. }
  167. }, [props.children]);
  168. const toggleCollapsed = () => {
  169. setCollapsed((collapsed) => !collapsed);
  170. };
  171. return (
  172. <>
  173. <code
  174. className={props?.className}
  175. ref={ref}
  176. style={{
  177. maxHeight: collapsed ? "400px" : "none",
  178. overflowY: "hidden",
  179. }}
  180. >
  181. {props.children}
  182. </code>
  183. {showToggle && collapsed && (
  184. <div
  185. className={`show-hide-button ${collapsed ? "collapsed" : "expanded"}`}
  186. >
  187. <button onClick={toggleCollapsed}>{Locale.NewChat.More}</button>
  188. </div>
  189. )}
  190. </>
  191. );
  192. }
  193. function escapeDollarNumber(text: string) {
  194. let escapedText = "";
  195. for (let i = 0; i < text.length; i += 1) {
  196. let char = text[i];
  197. const nextChar = text[i + 1] || " ";
  198. if (char === "$" && nextChar >= "0" && nextChar <= "9") {
  199. char = "\\$";
  200. }
  201. escapedText += char;
  202. }
  203. return escapedText;
  204. }
  205. function escapeBrackets(text: string) {
  206. const pattern =
  207. /(```[\s\S]*?```|`.*?`)|\\\[([\s\S]*?[^\\])\\\]|\\\((.*?)\\\)/g;
  208. return text.replace(
  209. pattern,
  210. (match, codeBlock, squareBracket, roundBracket) => {
  211. if (codeBlock) {
  212. return codeBlock;
  213. } else if (squareBracket) {
  214. return `$$${squareBracket}$$`;
  215. } else if (roundBracket) {
  216. return `$${roundBracket}$`;
  217. }
  218. return match;
  219. },
  220. );
  221. }
  222. function tryWrapHtmlCode(text: string) {
  223. // try add wrap html code (fixed: html codeblock include 2 newline)
  224. return text
  225. .replace(
  226. /([`]*?)(\w*?)([\n\r]*?)(<!DOCTYPE html>)/g,
  227. (match, quoteStart, lang, newLine, doctype) => {
  228. return !quoteStart ? "\n```html\n" + doctype : match;
  229. },
  230. )
  231. .replace(
  232. /(<\/body>)([\r\n\s]*?)(<\/html>)([\n\r]*?)([`]*?)([\n\r]*?)/g,
  233. (match, bodyEnd, space, htmlEnd, newLine, quoteEnd) => {
  234. return !quoteEnd ? bodyEnd + space + htmlEnd + "\n```\n" : match;
  235. },
  236. );
  237. }
  238. function _MarkDownContent(props: { content: string }) {
  239. const escapedContent = useMemo(() => {
  240. return tryWrapHtmlCode(escapeBrackets(escapeDollarNumber(props.content)));
  241. }, [props.content]);
  242. return (
  243. <ReactMarkdown
  244. remarkPlugins={[RemarkMath, RemarkGfm, RemarkBreaks]}
  245. rehypePlugins={[
  246. RehypeKatex,
  247. [
  248. RehypeHighlight,
  249. {
  250. detect: false,
  251. ignoreMissing: true,
  252. },
  253. ],
  254. ]}
  255. components={{
  256. pre: PreCode,
  257. code: CustomCode,
  258. p: (pProps) => <p {...pProps} dir="auto" />,
  259. a: (aProps) => {
  260. const href = aProps.href || "";
  261. const isInternal = /^\/#/i.test(href);
  262. const target = isInternal ? "_self" : aProps.target ?? "_blank";
  263. const handleClick = () => {
  264. if (href === SAAS_CHAT_URL) {
  265. trackConversationGuideToCPaymentClick();
  266. }
  267. };
  268. return <a {...aProps} target={target} onClick={handleClick} />;
  269. },
  270. }}
  271. >
  272. {escapedContent}
  273. </ReactMarkdown>
  274. );
  275. }
  276. export const MarkdownContent = React.memo(_MarkDownContent);
  277. export function Markdown(
  278. props: {
  279. content: string;
  280. loading?: boolean;
  281. fontSize?: number;
  282. fontFamily?: string;
  283. parentRef?: RefObject<HTMLDivElement>;
  284. defaultShow?: boolean;
  285. } & React.DOMAttributes<HTMLDivElement>,
  286. ) {
  287. const mdRef = useRef<HTMLDivElement>(null);
  288. return (
  289. <div
  290. className="markdown-body"
  291. style={{
  292. fontSize: `${props.fontSize ?? 14}px`,
  293. fontFamily: props.fontFamily || "inherit",
  294. }}
  295. ref={mdRef}
  296. onContextMenu={props.onContextMenu}
  297. onDoubleClickCapture={props.onDoubleClickCapture}
  298. dir="auto"
  299. >
  300. {props.loading ? (
  301. <LoadingIcon />
  302. ) : (
  303. <MarkdownContent content={props.content} />
  304. )}
  305. </div>
  306. );
  307. }