markdown.tsx 5.0 KB

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