Elffuss BraidHub

kikocis/continue public

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