Elffuss BraidHub

kikocis/continue public

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