-
-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathChatMarkdown.tsx
More file actions
232 lines (214 loc) · 6.56 KB
/
ChatMarkdown.tsx
File metadata and controls
232 lines (214 loc) · 6.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
import {
Children,
useDeferredValue,
isValidElement,
memo,
useEffect,
useMemo,
useState,
type ReactNode,
} from "react";
import type { Components } from "react-markdown";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { ChatCodePreviewCard } from "./ChatCodePreviewCard";
import { useAppSettings } from "../appSettings";
import { openFileReference } from "../fileOpen";
import { useFileViewNavigation } from "~/hooks/useFileViewNavigation";
import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
import {
getCachedHighlightedHtml,
getHighlighterPromise,
renderHighlightedCodeHtml,
setCachedHighlightedHtml,
} from "../lib/syntaxHighlighting";
import { buildStreamingCodePreviewMeta } from "../lib/chatCodePreview";
import { useTheme } from "../hooks/useTheme";
import { resolveMarkdownFileLinkTarget } from "../markdown-links";
import { readNativeApi } from "../nativeApi";
import { toastManager } from "./ui/toast";
interface ChatMarkdownProps {
text: string;
cwd: string | undefined;
isStreaming?: boolean;
}
function nodeToPlainText(node: ReactNode): string {
if (typeof node === "string" || typeof node === "number") {
return String(node);
}
if (Array.isArray(node)) {
return node.map((child) => nodeToPlainText(child)).join("");
}
if (isValidElement<{ children?: ReactNode }>(node)) {
return nodeToPlainText(node.props.children);
}
return "";
}
function extractCodeBlock(
children: ReactNode,
): { className: string | undefined; code: string } | null {
const childNodes = Children.toArray(children);
if (childNodes.length !== 1) {
return null;
}
const onlyChild = childNodes[0];
if (
!isValidElement<{ className?: string; children?: ReactNode }>(onlyChild) ||
onlyChild.type !== "code"
) {
return null;
}
return {
className: onlyChild.props.className,
code: nodeToPlainText(onlyChild.props.children),
};
}
interface HighlightedCodeBlockProps {
className: string | undefined;
code: string;
themeName: DiffThemeName;
isStreaming: boolean;
fallback: ReactNode;
}
function HighlightedCodeBlock({
className,
code,
themeName,
isStreaming,
fallback,
}: HighlightedCodeBlockProps) {
const deferredCode = useDeferredValue(code);
const [highlightedHtml, setHighlightedHtml] = useState<string | null>(null);
const [highlightFailed, setHighlightFailed] = useState(false);
const meta = useMemo(
() =>
buildStreamingCodePreviewMeta({
className,
code,
isStreaming,
highlightFailed,
}),
[className, code, highlightFailed, isStreaming],
);
const effectiveCode = isStreaming ? deferredCode : code;
useEffect(() => {
let cancelled = false;
const cachedHighlightedHtml = !isStreaming
? getCachedHighlightedHtml(code, meta.language, themeName, "chat-markdown")
: null;
if (cachedHighlightedHtml != null) {
setHighlightFailed(false);
setHighlightedHtml(cachedHighlightedHtml);
return () => {
cancelled = true;
};
}
setHighlightedHtml((current) => (isStreaming ? current : null));
setHighlightFailed(false);
void getHighlighterPromise(meta.language)
.then((highlighter) => {
if (cancelled) return;
const nextHtml = renderHighlightedCodeHtml(
highlighter,
effectiveCode,
meta.language,
themeName,
);
if (cancelled) return;
setHighlightedHtml(nextHtml);
if (!isStreaming) {
setCachedHighlightedHtml(code, meta.language, themeName, "chat-markdown", nextHtml);
}
})
.catch(() => {
if (cancelled) return;
setHighlightFailed(true);
setHighlightedHtml(null);
});
return () => {
cancelled = true;
};
}, [code, effectiveCode, isStreaming, meta.language, themeName]);
return (
<ChatCodePreviewCard code={code} meta={meta} isStreaming={isStreaming}>
{highlightedHtml ? (
<div
className="chat-markdown-shiki"
dangerouslySetInnerHTML={{ __html: highlightedHtml }}
/>
) : (
fallback
)}
</ChatCodePreviewCard>
);
}
function ChatMarkdown({ text, cwd, isStreaming = false }: ChatMarkdownProps) {
const { settings } = useAppSettings();
const openFileInViewer = useFileViewNavigation();
const { resolvedTheme } = useTheme();
const diffThemeName = resolveDiffThemeName(resolvedTheme);
const openLinksExternally = settings.openLinksExternally;
const markdownComponents = useMemo<Components>(
() => ({
a({ node: _node, href, ...props }) {
const targetPath = resolveMarkdownFileLinkTarget(href, cwd);
if (!targetPath) {
return <a {...props} href={href} target="_blank" rel="noreferrer" />;
}
return (
<a
{...props}
href={href}
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
const api = readNativeApi();
if (api) {
void openFileReference({
api,
cwd,
targetPath,
preferExternal: openLinksExternally,
openInViewer: openFileInViewer,
}).catch((error) => {
toastManager.add({
type: "error",
title: "Unable to open file",
description: error instanceof Error ? error.message : "An error occurred.",
});
});
} else {
console.warn("Native API not found. Unable to open file.");
}
}}
/>
);
},
pre({ node: _node, children, ...props }) {
const codeBlock = extractCodeBlock(children);
if (!codeBlock) {
return <pre {...props}>{children}</pre>;
}
const fallback = <pre {...props}>{children}</pre>;
return (
<HighlightedCodeBlock
className={codeBlock.className}
code={codeBlock.code}
themeName={diffThemeName}
isStreaming={isStreaming}
fallback={fallback}
/>
);
},
}),
[cwd, diffThemeName, isStreaming, openFileInViewer, openLinksExternally],
);
return (
<div className="chat-markdown w-full min-w-0 text-sm leading-relaxed text-foreground/80">
<ReactMarkdown remarkPlugins={[remarkGfm]} components={markdownComponents}>
{text}
</ReactMarkdown>
</div>
);
}
export default memo(ChatMarkdown);