Elffuss BraidHub

kikocis/continue public

main · 11.1 KiBRawPermalink
1import { ctxItemToRifWithContents } from "core/commands/util";
2import { memo, useEffect, useMemo, useRef } from "react";
3import { useRemark } from "react-remark";
4import rehypeKatex from "rehype-katex";
5import remarkMath from "remark-math";
6import styled from "styled-components";
7import { visit } from "unist-util-visit";
8import { v4 as uuidv4 } from "uuid";
9import {
10 defaultBorderRadius,
11 vscBackground,
12 vscEditorBackground,
13 vscForeground,
14} from "..";
15import useUpdatingRef from "../../hooks/useUpdatingRef";
16import { useAppSelector } from "../../redux/hooks";
17import { selectUIConfig } from "../../redux/slices/configSlice";
18import { getContextItemsFromHistory } from "../../redux/thunks/updateFileSymbols";
19import { getFontSize } from "../../util";
20import { ToolTip } from "../gui/Tooltip";
21import FilenameLink from "./FilenameLink";
22import "./katex.css";
23import "./markdown.css";
24import MermaidBlock from "./MermaidBlock";
25import { rehypeHighlightPlugin } from "./rehypeHighlightPlugin";
26import { SecureImageComponent } from "./SecureImageComponent";
27import { StepContainerPreToolbar } from "./StepContainerPreToolbar";
28import SymbolLink from "./SymbolLink";
29import { SyntaxHighlightedPre } from "./SyntaxHighlightedPre";
30import { isSymbolNotRif, matchCodeToSymbolOrFile } from "./utils";
31import { fixDoubleDollarNewLineLatex } from "./utils/fixDoubleDollarLatex";
32import { patchNestedMarkdown } from "./utils/patchNestedMarkdown";
33import { remarkTables } from "./utils/remarkTables";
34
35const StyledMarkdown = styled.div<{
36 fontSize?: number;
37 whiteSpace: string;
38 bgColor: string;
39}>`
40 h1 {
41 font-size: 1.25em;
42 }
43
44 h2 {
45 font-size: 1.15em;
46 }
47
48 h3 {
49 font-size: 1.05em;
50 }
51
52 h4 {
53 font-size: 1em;
54 }
55
56 h5 {
57 font-size: 0.95em;
58 }
59
60 h6 {
61 font-size: 0.9em;
62 }
63
64 pre {
65 white-space: ${(props) => props.whiteSpace};
66 background-color: ${vscEditorBackground};
67 border-radius: ${defaultBorderRadius};
68
69 max-width: calc(100vw - 24px);
70 overflow-x: scroll;
71 overflow-y: hidden;
72
73 padding: 8px;
74 }
75
76 code {
77 span.line:empty {
78 display: none;
79 }
80 word-wrap: break-word;
81 border-radius: 0.3125rem;
82 background-color: ${vscEditorBackground};
83 font-size: ${getFontSize() - 2}px;
84 font-family: var(--vscode-editor-font-family);
85 }
86
87 ul ul,
88 ul ol,
89 ol ul,
90 ol ol {
91 padding-left: 1.5em;
92 margin-top: 1em;
93 }
94
95 li {
96 margin-bottom: 0.8em;
97 }
98 li:last-child {
99 margin-bottom: 0;
100 }
101
102 ul,
103 ol {
104 padding-left: 2em;
105 }
106
107 code:not(pre > code) {
108 font-family: var(--vscode-editor-font-family);
109 }
110
111 background-color: ${(props) => props.bgColor};
112 font-family:
113 var(--vscode-font-family),
114 system-ui,
115 -apple-system,
116 BlinkMacSystemFont,
117 "Segoe UI",
118 Roboto,
119 Oxygen,
120 Ubuntu,
121 Cantarell,
122 "Open Sans",
123 "Helvetica Neue",
124 sans-serif;
125 font-size: ${(props) => props.fontSize || getFontSize()}px;
126 padding-left: 8px;
127 padding-right: 8px;
128 color: ${vscForeground};
129
130 p,
131 li,
132 ol,
133 ul {
134 line-height: 1.5;
135 }
136
137 * {
138 word-break: break-word;
139 }
140
141 > *:last-child {
142 margin-bottom: 0;
143 }
144`;
145
146interface StyledMarkdownPreviewProps {
147 showToolCallStatusIcon?: boolean;
148 source?: string;
149 className?: string;
150 isRenderingInStepContainer?: boolean; // Currently only used to control the rendering of codeblocks
151 scrollLocked?: boolean;
152 itemIndex?: number;
153 useParentBackgroundColor?: boolean;
154 disableManualApply?: boolean;
155 toolCallId?: string;
156 expandCodeblocks?: boolean;
157 collapsible?: boolean;
158}
159
160const HLJS_LANGUAGE_CLASSNAME_PREFIX = "language-";
161
162function getLanguageFromClassName(className: any): string | null {
163 if (!className || typeof className !== "string") {
164 return null;
165 }
166
167 const language = className
168 .split(" ")
169 .find((word) => word.startsWith(HLJS_LANGUAGE_CLASSNAME_PREFIX))
170 ?.split("-")[1];
171
172 return language ?? null;
173}
174
175function getCodeChildrenContent(children: any) {
176 if (typeof children === "string") {
177 return children;
178 } else if (
179 Array.isArray(children) &&
180 children.length > 0 &&
181 typeof children[0] === "string"
182 ) {
183 return children[0];
184 }
185 return undefined;
186}
187
188const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
189 props: StyledMarkdownPreviewProps,
190) {
191 // The refs are a workaround because rehype options are stored on initiation
192 // So they won't use the most up-to-date state values
193 // So in this case we just put them in refs
194
195 // The logic here is to get file names from
196 // 1. Context items found in past messages
197 // 2. Toolbar Codeblocks found in past messages
198 const history = useAppSelector((state) => state.session.history);
199 const allSymbols = useAppSelector((state) => state.session.symbols);
200 const pastFileInfo = useMemo(() => {
201 const index = props.itemIndex;
202 if (index === undefined) {
203 return {
204 symbols: [],
205 rifs: [],
206 };
207 }
208 const pastContextItems = getContextItemsFromHistory(history, index);
209 const rifs = pastContextItems.map((item) =>
210 ctxItemToRifWithContents(item, true),
211 );
212 const symbols = Object.entries(allSymbols)
213 .filter((e) => pastContextItems.find((item) => item.uri!.value === e[0]))
214 .map((f) => f[1])
215 .flat();
216
217 return {
218 symbols,
219 rifs,
220 };
221 }, [props.itemIndex, history, allSymbols]);
222 const pastFileInfoRef = useUpdatingRef(pastFileInfo);
223 const itemIndexRef = useUpdatingRef(props.itemIndex);
224
225 const codeblockStreamIds = useRef<string[]>([]);
226
227 const [reactContent, setMarkdownSource] = useRemark({
228 remarkPlugins: [
229 remarkTables,
230 [
231 remarkMath,
232 {
233 singleDollarTextMath: false,
234 },
235 ],
236 () => (tree: any) => {
237 const lastNode = tree.children[tree.children.length - 1];
238 const lastCodeNode = lastNode.type === "code" ? lastNode : null;
239
240 visit(tree, "code", (node: any) => {
241 if (!node.lang) {
242 node.lang = "";
243 } else if (node.lang.includes(".")) {
244 node.lang = node.lang.split(".").slice(-1)[0];
245 }
246
247 node.data = node.data || {};
248 node.data.hProperties = node.data.hProperties || {};
249
250 node.data.hProperties["data-islastcodeblock"] = lastCodeNode === node;
251 node.data.hProperties["data-codeblockcontent"] = node.value;
252
253 if (node.meta) {
254 let meta = node.meta.split(" ");
255 node.data.hProperties["data-relativefilepath"] = meta[0];
256 node.data.hProperties.range = meta[1];
257 }
258 });
259 },
260 ],
261 rehypePlugins: [
262 rehypeKatex as any,
263 {},
264 rehypeHighlightPlugin(),
265 // Note: An empty obj is the default behavior, but leaving this here for scaffolding to
266 // add unsupported languages in the future. We will need to install the `lowlight` package
267 // to use the `common` language set in addition to unsupported languages.
268 // https://github.com/highlightjs/highlight.js/blob/main/SUPPORTED_LANGUAGES.md
269 () => {
270 let codeBlockIndex = 0;
271 return (tree) => {
272 visit(tree, { tagName: "pre" }, (node: any) => {
273 // Add an index (0, 1, 2, etc...) to each code block.
274 node.properties = { "data-codeblockindex": codeBlockIndex };
275 codeBlockIndex++;
276 });
277 };
278 },
279 {},
280 ],
281 rehypeReactOptions: {
282 components: {
283 a: ({ ...aProps }) => {
284 return (
285 <ToolTip place="top" className="m-0 p-0" content={aProps.href}>
286 <a href={aProps.href} target="_blank" className="hover:underline">
287 {aProps.children}
288 </a>
289 </ToolTip>
290 );
291 },
292 pre: ({ ...preProps }) => {
293 const codeBlockIndex = preProps["data-codeblockindex"];
294
295 const preChildProps = preProps?.children?.[0]?.props ?? {};
296 const { className, range } = preChildProps;
297
298 const relativeFilePath = preChildProps["data-relativefilepath"];
299 const codeBlockContent = preChildProps["data-codeblockcontent"];
300
301 if (!props.isRenderingInStepContainer) {
302 return <SyntaxHighlightedPre {...preProps} />;
303 }
304
305 const language = getLanguageFromClassName(className);
306
307 const isLastCodeblock = preChildProps["data-islastcodeblock"];
308
309 if (codeblockStreamIds.current[codeBlockIndex] === undefined) {
310 codeblockStreamIds.current[codeBlockIndex] = uuidv4();
311 }
312
313 return (
314 <StepContainerPreToolbar
315 showToolCallStatusIcon={props.showToolCallStatusIcon}
316 codeBlockContent={codeBlockContent}
317 itemIndex={itemIndexRef.current}
318 codeBlockIndex={codeBlockIndex}
319 language={language}
320 relativeFilepath={relativeFilePath}
321 isLastCodeblock={isLastCodeblock}
322 range={range}
323 codeBlockStreamId={codeblockStreamIds.current[codeBlockIndex]} // ignored if toolCallId stream state is found
324 forceToolCallId={props.toolCallId}
325 expanded={props.expandCodeblocks}
326 disableManualApply={props.disableManualApply}
327 collapsible={props.collapsible}
328 >
329 <SyntaxHighlightedPre {...preProps} />
330 </StepContainerPreToolbar>
331 );
332 },
333 code: ({ ...codeProps }) => {
334 const content = getCodeChildrenContent(codeProps.children);
335
336 if (content) {
337 const { symbols, rifs } = pastFileInfoRef.current;
338
339 const matchedSymbolOrFile = matchCodeToSymbolOrFile(
340 content,
341 symbols,
342 rifs,
343 );
344 if (matchedSymbolOrFile) {
345 if (isSymbolNotRif(matchedSymbolOrFile)) {
346 return (
347 <SymbolLink content={content} symbol={matchedSymbolOrFile} />
348 );
349 } else {
350 return <FilenameLink rif={matchedSymbolOrFile} />;
351 }
352 }
353 }
354 if (codeProps.className?.includes("language-mermaid")) {
355 const codeText = String(codeProps.children || "");
356 return <MermaidBlock code={codeText} />;
357 }
358 return <code {...codeProps}>{codeProps.children}</code>;
359 },
360 img: ({ ...imgProps }) => {
361 return (
362 <SecureImageComponent
363 src={imgProps.src}
364 alt={imgProps.alt}
365 title={imgProps.title}
366 className={imgProps.className}
367 />
368 );
369 },
370 },
371 },
372 });
373
374 useEffect(() => {
375 setMarkdownSource(
376 // some patches to source markdown are applied here:
377 fixDoubleDollarNewLineLatex(patchNestedMarkdown(props.source ?? "")),
378 );
379 }, [props.source, allSymbols]);
380
381 const uiConfig = useAppSelector(selectUIConfig);
382 const codeWrapState = uiConfig?.codeWrap ? "pre-wrap" : "pre";
383
384 return (
385 <StyledMarkdown
386 fontSize={getFontSize()}
387 whiteSpace={codeWrapState}
388 bgColor={props.useParentBackgroundColor ? "" : vscBackground}
389 >
390 {reactContent}
391 </StyledMarkdown>
392 );
393});
394
395export default StyledMarkdownPreview;