Elffuss BraidHub

kikocis/continue public

972ea8cfaef0 · 10.5 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 const itemIndexRef = useUpdatingRef(props.itemIndex);
197
198 const codeblockStreamIds = useRef<string[]>([]);
199 useEffect(() => {
200 if (props.forceStreamId) {
201 codeblockStreamIds.current = [props.forceStreamId];
202 }
203 }, [props.forceStreamId, codeblockStreamIds]);
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] =
299 props.forceStreamId ?? uuidv4();
300 }
301
302 return (
303 <StepContainerPreToolbar
304 codeBlockContent={codeBlockContent}
305 itemIndex={itemIndexRef.current}
306 codeBlockIndex={codeBlockIndex}
307 language={language}
308 relativeFilepath={relativeFilePath}
309 isLastCodeblock={isLastCodeblock}
310 range={range}
311 codeBlockStreamId={codeblockStreamIds.current[codeBlockIndex]}
312 expanded={props.expandCodeblocks}
313 disableManualApply={props.disableManualApply}
314 >
315 <SyntaxHighlightedPre {...preProps} />
316 </StepContainerPreToolbar>
317 );
318 },
319 code: ({ ...codeProps }) => {
320 const content = getCodeChildrenContent(codeProps.children);
321
322 if (content) {
323 const { symbols, rifs } = pastFileInfoRef.current;
324
325 const matchedSymbolOrFile = matchCodeToSymbolOrFile(
326 content,
327 symbols,
328 rifs,
329 );
330 if (matchedSymbolOrFile) {
331 if (isSymbolNotRif(matchedSymbolOrFile)) {
332 return (
333 <SymbolLink content={content} symbol={matchedSymbolOrFile} />
334 );
335 } else {
336 return <FilenameLink rif={matchedSymbolOrFile} />;
337 }
338 }
339 }
340 return <code {...codeProps}>{codeProps.children}</code>;
341 },
342 },
343 },
344 });
345
346 useEffect(() => {
347 setMarkdownSource(
348 // some patches to source markdown are applied here:
349 fixDoubleDollarNewLineLatex(patchNestedMarkdown(props.source ?? "")),
350 );
351 }, [props.source, allSymbols]);
352
353 const uiConfig = useAppSelector(selectUIConfig);
354 const codeWrapState = uiConfig?.codeWrap ? "pre-wrap" : "pre";
355 return (
356 <StyledMarkdown
357 contentEditable="false"
358 fontSize={getFontSize()}
359 whiteSpace={codeWrapState}
360 bgColor={props.useParentBackgroundColor ? "" : vscBackground}
361 >
362 {reactContent}
363 </StyledMarkdown>
364 );
365});
366
367export default StyledMarkdownPreview;