Elffuss BraidHub

kikocis/continue public

f34c6dd29412 · 10.8 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 code:not(pre > code) {
88 font-family: var(--vscode-editor-font-family);
89 }
90
91 background-color: ${(props) => props.bgColor};
92 font-family:
93 var(--vscode-font-family),
94 system-ui,
95 -apple-system,
96 BlinkMacSystemFont,
97 "Segoe UI",
98 Roboto,
99 Oxygen,
100 Ubuntu,
101 Cantarell,
102 "Open Sans",
103 "Helvetica Neue",
104 sans-serif;
105 font-size: ${(props) => props.fontSize || getFontSize()}px;
106 padding-left: 8px;
107 padding-right: 8px;
108 color: ${vscForeground};
109
110 p,
111 li,
112 ol,
113 ul {
114 line-height: 1.5;
115 }
116
117 * {
118 word-break: break-word;
119 }
120
121 > *:last-child {
122 margin-bottom: 0;
123 }
124`;
125
126interface StyledMarkdownPreviewProps {
127 showToolCallStatusIcon?: boolean;
128 source?: string;
129 className?: string;
130 isRenderingInStepContainer?: boolean; // Currently only used to control the rendering of codeblocks
131 scrollLocked?: boolean;
132 itemIndex?: number;
133 useParentBackgroundColor?: boolean;
134 disableManualApply?: boolean;
135 toolCallId?: string;
136 expandCodeblocks?: boolean;
137 collapsible?: boolean;
138}
139
140const HLJS_LANGUAGE_CLASSNAME_PREFIX = "language-";
141
142function getLanguageFromClassName(className: any): string | null {
143 if (!className || typeof className !== "string") {
144 return null;
145 }
146
147 const language = className
148 .split(" ")
149 .find((word) => word.startsWith(HLJS_LANGUAGE_CLASSNAME_PREFIX))
150 ?.split("-")[1];
151
152 return language ?? null;
153}
154
155function getCodeChildrenContent(children: any) {
156 if (typeof children === "string") {
157 return children;
158 } else if (
159 Array.isArray(children) &&
160 children.length > 0 &&
161 typeof children[0] === "string"
162 ) {
163 return children[0];
164 }
165 return undefined;
166}
167
168const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
169 props: StyledMarkdownPreviewProps,
170) {
171 // The refs are a workaround because rehype options are stored on initiation
172 // So they won't use the most up-to-date state values
173 // So in this case we just put them in refs
174
175 // The logic here is to get file names from
176 // 1. Context items found in past messages
177 // 2. Toolbar Codeblocks found in past messages
178 const history = useAppSelector((state) => state.session.history);
179 const allSymbols = useAppSelector((state) => state.session.symbols);
180 const pastFileInfo = useMemo(() => {
181 const index = props.itemIndex;
182 if (index === undefined) {
183 return {
184 symbols: [],
185 rifs: [],
186 };
187 }
188 const pastContextItems = getContextItemsFromHistory(history, index);
189 const rifs = pastContextItems.map((item) =>
190 ctxItemToRifWithContents(item, true),
191 );
192 const symbols = Object.entries(allSymbols)
193 .filter((e) => pastContextItems.find((item) => item.uri!.value === e[0]))
194 .map((f) => f[1])
195 .flat();
196
197 return {
198 symbols,
199 rifs,
200 };
201 }, [props.itemIndex, history, allSymbols]);
202 const pastFileInfoRef = useUpdatingRef(pastFileInfo);
203 const itemIndexRef = useUpdatingRef(props.itemIndex);
204
205 const codeblockStreamIds = useRef<string[]>([]);
206
207 const [reactContent, setMarkdownSource] = useRemark({
208 remarkPlugins: [
209 remarkTables,
210 [
211 remarkMath,
212 {
213 singleDollarTextMath: false,
214 },
215 ],
216 () => (tree: any) => {
217 const lastNode = tree.children[tree.children.length - 1];
218 const lastCodeNode = lastNode.type === "code" ? lastNode : null;
219
220 visit(tree, "code", (node: any) => {
221 if (!node.lang) {
222 node.lang = "";
223 } else if (node.lang.includes(".")) {
224 node.lang = node.lang.split(".").slice(-1)[0];
225 }
226
227 node.data = node.data || {};
228 node.data.hProperties = node.data.hProperties || {};
229
230 node.data.hProperties["data-islastcodeblock"] = lastCodeNode === node;
231 node.data.hProperties["data-codeblockcontent"] = node.value;
232
233 if (node.meta) {
234 let meta = node.meta.split(" ");
235 node.data.hProperties["data-relativefilepath"] = meta[0];
236 node.data.hProperties.range = meta[1];
237 }
238 });
239 },
240 ],
241 rehypePlugins: [
242 rehypeKatex as any,
243 {},
244 rehypeHighlightPlugin(),
245 // Note: An empty obj is the default behavior, but leaving this here for scaffolding to
246 // add unsupported languages in the future. We will need to install the `lowlight` package
247 // to use the `common` language set in addition to unsupported languages.
248 // https://github.com/highlightjs/highlight.js/blob/main/SUPPORTED_LANGUAGES.md
249 () => {
250 let codeBlockIndex = 0;
251 return (tree) => {
252 visit(tree, { tagName: "pre" }, (node: any) => {
253 // Add an index (0, 1, 2, etc...) to each code block.
254 node.properties = { "data-codeblockindex": codeBlockIndex };
255 codeBlockIndex++;
256 });
257 };
258 },
259 {},
260 ],
261 rehypeReactOptions: {
262 components: {
263 a: ({ ...aProps }) => {
264 return (
265 <ToolTip place="top" className="m-0 p-0" content={aProps.href}>
266 <a href={aProps.href} target="_blank" className="hover:underline">
267 {aProps.children}
268 </a>
269 </ToolTip>
270 );
271 },
272 pre: ({ ...preProps }) => {
273 const codeBlockIndex = preProps["data-codeblockindex"];
274
275 const preChildProps = preProps?.children?.[0]?.props ?? {};
276 const { className, range } = preChildProps;
277
278 const relativeFilePath = preChildProps["data-relativefilepath"];
279 const codeBlockContent = preChildProps["data-codeblockcontent"];
280
281 if (!props.isRenderingInStepContainer) {
282 return <SyntaxHighlightedPre {...preProps} />;
283 }
284
285 const language = getLanguageFromClassName(className);
286
287 const isLastCodeblock = preChildProps["data-islastcodeblock"];
288
289 if (codeblockStreamIds.current[codeBlockIndex] === undefined) {
290 codeblockStreamIds.current[codeBlockIndex] = uuidv4();
291 }
292
293 return (
294 <StepContainerPreToolbar
295 showToolCallStatusIcon={props.showToolCallStatusIcon}
296 codeBlockContent={codeBlockContent}
297 itemIndex={itemIndexRef.current}
298 codeBlockIndex={codeBlockIndex}
299 language={language}
300 relativeFilepath={relativeFilePath}
301 isLastCodeblock={isLastCodeblock}
302 range={range}
303 codeBlockStreamId={codeblockStreamIds.current[codeBlockIndex]} // ignored if toolCallId stream state is found
304 forceToolCallId={props.toolCallId}
305 expanded={props.expandCodeblocks}
306 disableManualApply={props.disableManualApply}
307 collapsible={props.collapsible}
308 >
309 <SyntaxHighlightedPre {...preProps} />
310 </StepContainerPreToolbar>
311 );
312 },
313 code: ({ ...codeProps }) => {
314 const content = getCodeChildrenContent(codeProps.children);
315
316 if (content) {
317 const { symbols, rifs } = pastFileInfoRef.current;
318
319 const matchedSymbolOrFile = matchCodeToSymbolOrFile(
320 content,
321 symbols,
322 rifs,
323 );
324 if (matchedSymbolOrFile) {
325 if (isSymbolNotRif(matchedSymbolOrFile)) {
326 return (
327 <SymbolLink content={content} symbol={matchedSymbolOrFile} />
328 );
329 } else {
330 return <FilenameLink rif={matchedSymbolOrFile} />;
331 }
332 }
333 }
334 if (codeProps.className?.includes("language-mermaid")) {
335 const codeText = String(codeProps.children || "");
336 return <MermaidBlock code={codeText} />;
337 }
338 return <code {...codeProps}>{codeProps.children}</code>;
339 },
340 img: ({ ...imgProps }) => {
341 return (
342 <SecureImageComponent
343 src={imgProps.src}
344 alt={imgProps.alt}
345 title={imgProps.title}
346 className={imgProps.className}
347 />
348 );
349 },
350 },
351 },
352 });
353
354 useEffect(() => {
355 setMarkdownSource(
356 // some patches to source markdown are applied here:
357 fixDoubleDollarNewLineLatex(patchNestedMarkdown(props.source ?? "")),
358 );
359 }, [props.source, allSymbols]);
360
361 const uiConfig = useAppSelector(selectUIConfig);
362 const codeWrapState = uiConfig?.codeWrap ? "pre-wrap" : "pre";
363
364 return (
365 <StyledMarkdown
366 fontSize={getFontSize()}
367 whiteSpace={codeWrapState}
368 bgColor={props.useParentBackgroundColor ? "" : vscBackground}
369 >
370 {reactContent}
371 </StyledMarkdown>
372 );
373});
374
375export default StyledMarkdownPreview;