Elffuss BraidHub

kikocis/continue public

9d8db5fc402e · 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 { 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 forceStreamId?: 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
197 const isLastItem = useMemo(() => {
198 return props.itemIndex === history.length - 1;
199 }, [history.length, props.itemIndex]);
200 const isLastItemRef = useUpdatingRef(isLastItem);
201
202 const codeblockStreamIds = useRef<string[]>([]);
203 useEffect(() => {
204 if (props.forceStreamId) {
205 codeblockStreamIds.current = [props.forceStreamId];
206 }
207 }, [props.forceStreamId, codeblockStreamIds]);
208
209 const [reactContent, setMarkdownSource] = useRemark({
210 remarkPlugins: [
211 remarkTables,
212 [
213 remarkMath,
214 {
215 singleDollarTextMath: false,
216 },
217 ],
218 () => (tree: any) => {
219 const lastNode = tree.children[tree.children.length - 1];
220 const lastCodeNode = lastNode.type === "code" ? lastNode : null;
221
222 visit(tree, "code", (node: any) => {
223 if (!node.lang) {
224 node.lang = "";
225 } else if (node.lang.includes(".")) {
226 node.lang = node.lang.split(".").slice(-1)[0];
227 }
228
229 node.data = node.data || {};
230 node.data.hProperties = node.data.hProperties || {};
231
232 node.data.hProperties["data-islastcodeblock"] = lastCodeNode === node;
233 node.data.hProperties["data-codeblockcontent"] = node.value;
234
235 if (node.meta) {
236 let meta = node.meta.split(" ");
237 node.data.hProperties["data-relativefilepath"] = meta[0];
238 node.data.hProperties.range = meta[1];
239 }
240 });
241 },
242 ],
243 rehypePlugins: [
244 rehypeKatex as any,
245 {},
246 rehypeHighlightPlugin(),
247 // Note: An empty obj is the default behavior, but leaving this here for scaffolding to
248 // add unsupported languages in the future. We will need to install the `lowlight` package
249 // to use the `common` language set in addition to unsupported languages.
250 // https://github.com/highlightjs/highlight.js/blob/main/SUPPORTED_LANGUAGES.md
251 () => {
252 let codeBlockIndex = 0;
253 return (tree) => {
254 visit(tree, { tagName: "pre" }, (node: any) => {
255 // Add an index (0, 1, 2, etc...) to each code block.
256 node.properties = { "data-codeblockindex": codeBlockIndex };
257 codeBlockIndex++;
258 });
259 };
260 },
261 {},
262 ],
263 rehypeReactOptions: {
264 components: {
265 a: ({ ...aProps }) => {
266 const tooltipId = uuidv4();
267
268 return (
269 <>
270 <a
271 href={aProps.href}
272 target="_blank"
273 className="hover:underline"
274 data-tooltip-id={tooltipId}
275 >
276 {aProps.children}
277 </a>
278 <ToolTip id={tooltipId} place="top" className="m-0 p-0">
279 {aProps.href}
280 </ToolTip>
281 </>
282 );
283 },
284 pre: ({ ...preProps }) => {
285 const codeBlockIndex = preProps["data-codeblockindex"];
286
287 const preChildProps = preProps?.children?.[0]?.props ?? {};
288 const { className, range } = preChildProps;
289
290 const relativeFilePath = preChildProps["data-relativefilepath"];
291 const codeBlockContent = preChildProps["data-codeblockcontent"];
292
293 if (!props.isRenderingInStepContainer) {
294 return <SyntaxHighlightedPre {...preProps} />;
295 }
296
297 const language = getLanguageFromClassName(className);
298
299 const isFinalCodeblock =
300 preChildProps["data-islastcodeblock"] && isLastItemRef.current;
301
302 if (codeblockStreamIds.current[codeBlockIndex] === undefined) {
303 codeblockStreamIds.current[codeBlockIndex] =
304 props.forceStreamId ?? uuidv4();
305 }
306
307 return (
308 <StepContainerPreToolbar
309 codeBlockContent={codeBlockContent}
310 codeBlockIndex={codeBlockIndex}
311 language={language}
312 relativeFilepath={relativeFilePath}
313 isFinalCodeblock={isFinalCodeblock}
314 range={range}
315 codeBlockStreamId={codeblockStreamIds.current[codeBlockIndex]}
316 expanded={props.expandCodeblocks}
317 disableManualApply={props.disableManualApply}
318 >
319 <SyntaxHighlightedPre {...preProps} />
320 </StepContainerPreToolbar>
321 );
322 },
323 code: ({ ...codeProps }) => {
324 const content = getCodeChildrenContent(codeProps.children);
325
326 if (content) {
327 const { symbols, rifs } = pastFileInfoRef.current;
328
329 const matchedSymbolOrFile = matchCodeToSymbolOrFile(
330 content,
331 symbols,
332 rifs,
333 );
334 if (matchedSymbolOrFile) {
335 if (isSymbolNotRif(matchedSymbolOrFile)) {
336 return (
337 <SymbolLink content={content} symbol={matchedSymbolOrFile} />
338 );
339 } else {
340 return <FilenameLink rif={matchedSymbolOrFile} />;
341 }
342 }
343 }
344 return <code {...codeProps}>{codeProps.children}</code>;
345 },
346 },
347 },
348 });
349
350 useEffect(() => {
351 setMarkdownSource(
352 // some patches to source markdown are applied here:
353 fixDoubleDollarNewLineLatex(patchNestedMarkdown(props.source ?? "")),
354 );
355 }, [props.source, allSymbols]);
356
357 const uiConfig = useAppSelector(selectUIConfig);
358 const codeWrapState = uiConfig?.codeWrap ? "pre-wrap" : "pre";
359 return (
360 <StyledMarkdown
361 contentEditable="false"
362 fontSize={getFontSize()}
363 whiteSpace={codeWrapState}
364 bgColor={props.useParentBackgroundColor ? "" : vscBackground}
365 >
366 {reactContent}
367 </StyledMarkdown>
368 );
369});
370
371export default StyledMarkdownPreview;