Skip to content

Commit d88da1f

Browse files
committed
feat: close ChatGPTNextWeb#951 support mermaid
1 parent fe8e3f2 commit d88da1f

File tree

3 files changed

+491
-5
lines changed

3 files changed

+491
-5
lines changed

app/components/markdown.tsx

+49
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,61 @@ import RemarkGfm from "remark-gfm";
77
import RehypeHighlight from "rehype-highlight";
88
import { useRef, useState, RefObject, useEffect } from "react";
99
import { copyToClipboard } from "../utils";
10+
import mermaid from "mermaid";
1011

1112
import LoadingIcon from "../icons/three-dots.svg";
1213
import React from "react";
1314

15+
export function Mermaid(props: { code: string }) {
16+
const ref = useRef<HTMLDivElement>(null);
17+
18+
useEffect(() => {
19+
if (props.code && ref.current) {
20+
mermaid.run({
21+
nodes: [ref.current],
22+
});
23+
}
24+
}, [props.code]);
25+
26+
function viewSvgInNewWindow() {
27+
const svg = ref.current?.querySelector("svg");
28+
if (!svg) return;
29+
const text = new XMLSerializer().serializeToString(svg);
30+
const blob = new Blob([text], { type: "image/svg+xml" });
31+
const url = URL.createObjectURL(blob);
32+
const win = window.open(url);
33+
if (win) {
34+
win.onload = () => URL.revokeObjectURL(url);
35+
}
36+
}
37+
38+
return (
39+
<div
40+
className="no-dark"
41+
style={{ cursor: "pointer" }}
42+
ref={ref}
43+
onClick={() => viewSvgInNewWindow()}
44+
>
45+
{props.code}
46+
</div>
47+
);
48+
}
49+
1450
export function PreCode(props: { children: any }) {
1551
const ref = useRef<HTMLPreElement>(null);
52+
const [mermaidCode, setMermaidCode] = useState("");
53+
54+
useEffect(() => {
55+
if (!ref.current) return;
56+
const mermaidDom = ref.current.querySelector("code.language-mermaid");
57+
if (mermaidDom) {
58+
setMermaidCode((mermaidDom as HTMLElement).innerText);
59+
}
60+
}, [props.children]);
61+
62+
if (mermaidCode) {
63+
return <Mermaid code={mermaidCode} />;
64+
}
1665

1766
return (
1867
<pre ref={ref}>

package.json

+1
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
"emoji-picker-react": "^4.4.7",
2020
"eventsource-parser": "^0.1.0",
2121
"fuse.js": "^6.6.2",
22+
"mermaid": "^10.1.0",
2223
"next": "^13.3.1-canary.8",
2324
"node-fetch": "^3.3.1",
2425
"openai": "^3.2.1",

0 commit comments

Comments
 (0)