Elffuss BraidHub

kikocis/continue public

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