Elffuss BraidHub

kikocis/continue public

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