markdown.tsx 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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 } 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 } from "./ui-lib";
  15. import { ArtifactShareButton, HTMLPreview } from "./artifact";
  16. export function Mermaid(props: { code: string }) {
  17. const ref = useRef<HTMLDivElement>(null);
  18. const [hasError, setHasError] = useState(false);
  19. useEffect(() => {
  20. if (props.code && ref.current) {
  21. mermaid
  22. .run({
  23. nodes: [ref.current],
  24. suppressErrors: true,
  25. })
  26. .catch((e) => {
  27. setHasError(true);
  28. console.error("[Mermaid] ", e.message);
  29. });
  30. }
  31. // eslint-disable-next-line react-hooks/exhaustive-deps
  32. }, [props.code]);
  33. function viewSvgInNewWindow() {
  34. const svg = ref.current?.querySelector("svg");
  35. if (!svg) return;
  36. const text = new XMLSerializer().serializeToString(svg);
  37. const blob = new Blob([text], { type: "image/svg+xml" });
  38. showImageModal(URL.createObjectURL(blob));
  39. }
  40. if (hasError) {
  41. return null;
  42. }
  43. return (
  44. <div
  45. className="no-dark mermaid"
  46. style={{
  47. cursor: "pointer",
  48. overflow: "auto",
  49. }}
  50. ref={ref}
  51. onClick={() => viewSvgInNewWindow()}
  52. >
  53. {props.code}
  54. </div>
  55. );
  56. }
  57. export function PreCode(props: { children: any }) {
  58. const ref = useRef<HTMLPreElement>(null);
  59. const refText = ref.current?.innerText;
  60. const [mermaidCode, setMermaidCode] = useState("");
  61. const [htmlCode, setHtmlCode] = useState("");
  62. const renderArtifacts = useDebouncedCallback(() => {
  63. if (!ref.current) return;
  64. const mermaidDom = ref.current.querySelector("code.language-mermaid");
  65. if (mermaidDom) {
  66. setMermaidCode((mermaidDom as HTMLElement).innerText);
  67. }
  68. const htmlDom = ref.current.querySelector("code.language-html");
  69. if (htmlDom) {
  70. setHtmlCode((htmlDom as HTMLElement).innerText);
  71. } else if (refText?.startsWith("<!DOCTYPE")) {
  72. setHtmlCode(refText);
  73. }
  74. }, 600);
  75. useEffect(() => {
  76. setTimeout(renderArtifacts, 1);
  77. // eslint-disable-next-line react-hooks/exhaustive-deps
  78. }, [refText]);
  79. return (
  80. <>
  81. <pre ref={ref}>
  82. <span
  83. className="copy-code-button"
  84. onClick={() => {
  85. if (ref.current) {
  86. const code = ref.current.innerText;
  87. copyToClipboard(code);
  88. }
  89. }}
  90. ></span>
  91. {props.children}
  92. </pre>
  93. {mermaidCode.length > 0 && (
  94. <Mermaid code={mermaidCode} key={mermaidCode} />
  95. )}
  96. {htmlCode.length > 0 && (
  97. <div
  98. className="no-dark html"
  99. style={{
  100. overflow: "auto",
  101. position: "relative",
  102. }}
  103. onClick={(e) => e.stopPropagation()}
  104. >
  105. <ArtifactShareButton
  106. style={{ position: "absolute", right: 10, top: 10 }}
  107. getCode={() => htmlCode}
  108. />
  109. <HTMLPreview code={htmlCode} />
  110. </div>
  111. )}
  112. </>
  113. );
  114. }
  115. function escapeDollarNumber(text: string) {
  116. let escapedText = "";
  117. for (let i = 0; i < text.length; i += 1) {
  118. let char = text[i];
  119. const nextChar = text[i + 1] || " ";
  120. if (char === "$" && nextChar >= "0" && nextChar <= "9") {
  121. char = "\\$";
  122. }
  123. escapedText += char;
  124. }
  125. return escapedText;
  126. }
  127. function escapeBrackets(text: string) {
  128. const pattern =
  129. /(```[\s\S]*?```|`.*?`)|\\\[([\s\S]*?[^\\])\\\]|\\\((.*?)\\\)/g;
  130. return text.replace(
  131. pattern,
  132. (match, codeBlock, squareBracket, roundBracket) => {
  133. if (codeBlock) {
  134. return codeBlock;
  135. } else if (squareBracket) {
  136. return `$$${squareBracket}$$`;
  137. } else if (roundBracket) {
  138. return `$${roundBracket}$`;
  139. }
  140. return match;
  141. },
  142. );
  143. }
  144. function _MarkDownContent(props: { content: string }) {
  145. const escapedContent = useMemo(() => {
  146. return escapeBrackets(escapeDollarNumber(props.content));
  147. }, [props.content]);
  148. return (
  149. <ReactMarkdown
  150. remarkPlugins={[RemarkMath, RemarkGfm, RemarkBreaks]}
  151. rehypePlugins={[
  152. RehypeKatex,
  153. [
  154. RehypeHighlight,
  155. {
  156. detect: false,
  157. ignoreMissing: true,
  158. },
  159. ],
  160. ]}
  161. components={{
  162. pre: PreCode,
  163. p: (pProps) => <p {...pProps} dir="auto" />,
  164. a: (aProps) => {
  165. const href = aProps.href || "";
  166. const isInternal = /^\/#/i.test(href);
  167. const target = isInternal ? "_self" : aProps.target ?? "_blank";
  168. return <a {...aProps} target={target} />;
  169. },
  170. }}
  171. >
  172. {escapedContent}
  173. </ReactMarkdown>
  174. );
  175. }
  176. export const MarkdownContent = React.memo(_MarkDownContent);
  177. export function Markdown(
  178. props: {
  179. content: string;
  180. loading?: boolean;
  181. fontSize?: number;
  182. parentRef?: RefObject<HTMLDivElement>;
  183. defaultShow?: boolean;
  184. } & React.DOMAttributes<HTMLDivElement>,
  185. ) {
  186. const mdRef = useRef<HTMLDivElement>(null);
  187. return (
  188. <div
  189. className="markdown-body"
  190. style={{
  191. fontSize: `${props.fontSize ?? 14}px`,
  192. }}
  193. ref={mdRef}
  194. onContextMenu={props.onContextMenu}
  195. onDoubleClickCapture={props.onDoubleClickCapture}
  196. dir="auto"
  197. >
  198. {props.loading ? (
  199. <LoadingIcon />
  200. ) : (
  201. <MarkdownContent content={props.content} />
  202. )}
  203. </div>
  204. );
  205. }