Elffuss BraidHub

kikocis/continue public

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