markdown.tsx 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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. if (htmlDom) {
  76. setHtmlCode((htmlDom as HTMLElement).innerText);
  77. } else if (refText?.startsWith("<!DOCTYPE")) {
  78. setHtmlCode(refText);
  79. }
  80. }, 600);
  81. useEffect(() => {
  82. setTimeout(renderArtifacts, 1);
  83. // eslint-disable-next-line react-hooks/exhaustive-deps
  84. }, [refText]);
  85. const enableArtifacts = useMemo(
  86. () => plugins?.includes(Plugin.Artifacts),
  87. [plugins],
  88. );
  89. return (
  90. <>
  91. <pre ref={ref}>
  92. <span
  93. className="copy-code-button"
  94. onClick={() => {
  95. if (ref.current) {
  96. const code = ref.current.innerText;
  97. copyToClipboard(code);
  98. }
  99. }}
  100. ></span>
  101. {props.children}
  102. </pre>
  103. {mermaidCode.length > 0 && (
  104. <Mermaid code={mermaidCode} key={mermaidCode} />
  105. )}
  106. {htmlCode.length > 0 && enableArtifacts && (
  107. <FullScreen className="no-dark html" right={70}>
  108. <ArtifactsShareButton
  109. style={{ position: "absolute", right: 20, top: 10 }}
  110. getCode={() => htmlCode}
  111. />
  112. <HTMLPreview
  113. code={htmlCode}
  114. autoHeight={!document.fullscreenElement}
  115. height={!document.fullscreenElement ? 600 : height}
  116. />
  117. </FullScreen>
  118. )}
  119. </>
  120. );
  121. }
  122. function escapeDollarNumber(text: string) {
  123. let escapedText = "";
  124. for (let i = 0; i < text.length; i += 1) {
  125. let char = text[i];
  126. const nextChar = text[i + 1] || " ";
  127. if (char === "$" && nextChar >= "0" && nextChar <= "9") {
  128. char = "\\$";
  129. }
  130. escapedText += char;
  131. }
  132. return escapedText;
  133. }
  134. function escapeBrackets(text: string) {
  135. const pattern =
  136. /(```[\s\S]*?```|`.*?`)|\\\[([\s\S]*?[^\\])\\\]|\\\((.*?)\\\)/g;
  137. return text.replace(
  138. pattern,
  139. (match, codeBlock, squareBracket, roundBracket) => {
  140. if (codeBlock) {
  141. return codeBlock;
  142. } else if (squareBracket) {
  143. return `$$${squareBracket}$$`;
  144. } else if (roundBracket) {
  145. return `$${roundBracket}$`;
  146. }
  147. return match;
  148. },
  149. );
  150. }
  151. function _MarkDownContent(props: { content: string }) {
  152. const escapedContent = useMemo(() => {
  153. return escapeBrackets(escapeDollarNumber(props.content));
  154. }, [props.content]);
  155. return (
  156. <ReactMarkdown
  157. remarkPlugins={[RemarkMath, RemarkGfm, RemarkBreaks]}
  158. rehypePlugins={[
  159. RehypeKatex,
  160. [
  161. RehypeHighlight,
  162. {
  163. detect: false,
  164. ignoreMissing: true,
  165. },
  166. ],
  167. ]}
  168. components={{
  169. pre: PreCode,
  170. p: (pProps) => <p {...pProps} dir="auto" />,
  171. a: (aProps) => {
  172. const href = aProps.href || "";
  173. const isInternal = /^\/#/i.test(href);
  174. const target = isInternal ? "_self" : aProps.target ?? "_blank";
  175. return <a {...aProps} target={target} />;
  176. },
  177. }}
  178. >
  179. {escapedContent}
  180. </ReactMarkdown>
  181. );
  182. }
  183. export const MarkdownContent = React.memo(_MarkDownContent);
  184. export function Markdown(
  185. props: {
  186. content: string;
  187. loading?: boolean;
  188. fontSize?: number;
  189. parentRef?: RefObject<HTMLDivElement>;
  190. defaultShow?: boolean;
  191. } & React.DOMAttributes<HTMLDivElement>,
  192. ) {
  193. const mdRef = useRef<HTMLDivElement>(null);
  194. return (
  195. <div
  196. className="markdown-body"
  197. style={{
  198. fontSize: `${props.fontSize ?? 14}px`,
  199. }}
  200. ref={mdRef}
  201. onContextMenu={props.onContextMenu}
  202. onDoubleClickCapture={props.onDoubleClickCapture}
  203. dir="auto"
  204. >
  205. {props.loading ? (
  206. <LoadingIcon />
  207. ) : (
  208. <MarkdownContent content={props.content} />
  209. )}
  210. </div>
  211. );
  212. }