| 1 | import { ctxItemToRifWithContents } from "core/commands/util"; |
| 2 | import { memo, useEffect, useMemo, useRef } from "react"; |
| 3 | import { useRemark } from "react-remark"; |
| 4 | import rehypeKatex from "rehype-katex"; |
| 5 | import remarkMath from "remark-math"; |
| 6 | import styled from "styled-components"; |
| 7 | import { visit } from "unist-util-visit"; |
| 8 | import { v4 as uuidv4 } from "uuid"; |
| 9 | import { |
| 10 | defaultBorderRadius, |
| 11 | vscBackground, |
| 12 | vscEditorBackground, |
| 13 | vscForeground, |
| 14 | } from ".."; |
| 15 | import useUpdatingRef from "../../hooks/useUpdatingRef"; |
| 16 | import { useAppSelector } from "../../redux/hooks"; |
| 17 | import { selectUIConfig } from "../../redux/slices/configSlice"; |
| 18 | import { getContextItemsFromHistory } from "../../redux/thunks/updateFileSymbols"; |
| 19 | import { getFontSize } from "../../util"; |
| 20 | import { ToolTip } from "../gui/Tooltip"; |
| 21 | import FilenameLink from "./FilenameLink"; |
| 22 | import "./katex.css"; |
| 23 | import "./markdown.css"; |
| 24 | import MermaidBlock from "./MermaidBlock"; |
| 25 | import { rehypeHighlightPlugin } from "./rehypeHighlightPlugin"; |
| 26 | import { SecureImageComponent } from "./SecureImageComponent"; |
| 27 | import { StepContainerPreToolbar } from "./StepContainerPreToolbar"; |
| 28 | import SymbolLink from "./SymbolLink"; |
| 29 | import { SyntaxHighlightedPre } from "./SyntaxHighlightedPre"; |
| 30 | import { isSymbolNotRif, matchCodeToSymbolOrFile } from "./utils"; |
| 31 | import { fixDoubleDollarNewLineLatex } from "./utils/fixDoubleDollarLatex"; |
| 32 | import { patchNestedMarkdown } from "./utils/patchNestedMarkdown"; |
| 33 | import { remarkTables } from "./utils/remarkTables"; |
| 34 | |
| 35 | const StyledMarkdown = styled.div<{ |
| 36 | fontSize?: number; |
| 37 | whiteSpace: string; |
| 38 | bgColor: string; |
| 39 | }>` |
| 40 | h1 { |
| 41 | font-size: 1.25em; |
| 42 | } |
| 43 | |
| 44 | h2 { |
| 45 | font-size: 1.15em; |
| 46 | } |
| 47 | |
| 48 | h3 { |
| 49 | font-size: 1.05em; |
| 50 | } |
| 51 | |
| 52 | h4 { |
| 53 | font-size: 1em; |
| 54 | } |
| 55 | |
| 56 | h5 { |
| 57 | font-size: 0.95em; |
| 58 | } |
| 59 | |
| 60 | h6 { |
| 61 | font-size: 0.9em; |
| 62 | } |
| 63 | |
| 64 | pre { |
| 65 | white-space: ${(props) => props.whiteSpace}; |
| 66 | background-color: ${vscEditorBackground}; |
| 67 | border-radius: ${defaultBorderRadius}; |
| 68 | |
| 69 | max-width: calc(100vw - 24px); |
| 70 | overflow-x: scroll; |
| 71 | overflow-y: hidden; |
| 72 | |
| 73 | padding: 8px; |
| 74 | } |
| 75 | |
| 76 | code { |
| 77 | span.line:empty { |
| 78 | display: none; |
| 79 | } |
| 80 | word-wrap: break-word; |
| 81 | border-radius: 0.3125rem; |
| 82 | background-color: ${vscEditorBackground}; |
| 83 | font-size: ${getFontSize() - 2}px; |
| 84 | font-family: var(--vscode-editor-font-family); |
| 85 | } |
| 86 | |
| 87 | code:not(pre > code) { |
| 88 | font-family: var(--vscode-editor-font-family); |
| 89 | } |
| 90 | |
| 91 | background-color: ${(props) => props.bgColor}; |
| 92 | font-family: |
| 93 | var(--vscode-font-family), |
| 94 | system-ui, |
| 95 | -apple-system, |
| 96 | BlinkMacSystemFont, |
| 97 | "Segoe UI", |
| 98 | Roboto, |
| 99 | Oxygen, |
| 100 | Ubuntu, |
| 101 | Cantarell, |
| 102 | "Open Sans", |
| 103 | "Helvetica Neue", |
| 104 | sans-serif; |
| 105 | font-size: ${(props) => props.fontSize || getFontSize()}px; |
| 106 | padding-left: 8px; |
| 107 | padding-right: 8px; |
| 108 | color: ${vscForeground}; |
| 109 | |
| 110 | p, |
| 111 | li, |
| 112 | ol, |
| 113 | ul { |
| 114 | line-height: 1.5; |
| 115 | } |
| 116 | |
| 117 | * { |
| 118 | word-break: break-word; |
| 119 | } |
| 120 | |
| 121 | > *:last-child { |
| 122 | margin-bottom: 0; |
| 123 | } |
| 124 | `; |
| 125 | |
| 126 | interface StyledMarkdownPreviewProps { |
| 127 | showToolCallStatusIcon?: boolean; |
| 128 | source?: string; |
| 129 | className?: string; |
| 130 | isRenderingInStepContainer?: boolean; // Currently only used to control the rendering of codeblocks |
| 131 | scrollLocked?: boolean; |
| 132 | itemIndex?: number; |
| 133 | useParentBackgroundColor?: boolean; |
| 134 | disableManualApply?: boolean; |
| 135 | toolCallId?: string; |
| 136 | expandCodeblocks?: boolean; |
| 137 | collapsible?: boolean; |
| 138 | } |
| 139 | |
| 140 | const HLJS_LANGUAGE_CLASSNAME_PREFIX = "language-"; |
| 141 | |
| 142 | function getLanguageFromClassName(className: any): string | null { |
| 143 | if (!className || typeof className !== "string") { |
| 144 | return null; |
| 145 | } |
| 146 | |
| 147 | const language = className |
| 148 | .split(" ") |
| 149 | .find((word) => word.startsWith(HLJS_LANGUAGE_CLASSNAME_PREFIX)) |
| 150 | ?.split("-")[1]; |
| 151 | |
| 152 | return language ?? null; |
| 153 | } |
| 154 | |
| 155 | function getCodeChildrenContent(children: any) { |
| 156 | if (typeof children === "string") { |
| 157 | return children; |
| 158 | } else if ( |
| 159 | Array.isArray(children) && |
| 160 | children.length > 0 && |
| 161 | typeof children[0] === "string" |
| 162 | ) { |
| 163 | return children[0]; |
| 164 | } |
| 165 | return undefined; |
| 166 | } |
| 167 | |
| 168 | const StyledMarkdownPreview = memo(function StyledMarkdownPreview( |
| 169 | props: StyledMarkdownPreviewProps, |
| 170 | ) { |
| 171 | // The refs are a workaround because rehype options are stored on initiation |
| 172 | // So they won't use the most up-to-date state values |
| 173 | // So in this case we just put them in refs |
| 174 | |
| 175 | // The logic here is to get file names from |
| 176 | // 1. Context items found in past messages |
| 177 | // 2. Toolbar Codeblocks found in past messages |
| 178 | const history = useAppSelector((state) => state.session.history); |
| 179 | const allSymbols = useAppSelector((state) => state.session.symbols); |
| 180 | const pastFileInfo = useMemo(() => { |
| 181 | const index = props.itemIndex; |
| 182 | if (index === undefined) { |
| 183 | return { |
| 184 | symbols: [], |
| 185 | rifs: [], |
| 186 | }; |
| 187 | } |
| 188 | const pastContextItems = getContextItemsFromHistory(history, index); |
| 189 | const rifs = pastContextItems.map((item) => |
| 190 | ctxItemToRifWithContents(item, true), |
| 191 | ); |
| 192 | const symbols = Object.entries(allSymbols) |
| 193 | .filter((e) => pastContextItems.find((item) => item.uri!.value === e[0])) |
| 194 | .map((f) => f[1]) |
| 195 | .flat(); |
| 196 | |
| 197 | return { |
| 198 | symbols, |
| 199 | rifs, |
| 200 | }; |
| 201 | }, [props.itemIndex, history, allSymbols]); |
| 202 | const pastFileInfoRef = useUpdatingRef(pastFileInfo); |
| 203 | const itemIndexRef = useUpdatingRef(props.itemIndex); |
| 204 | |
| 205 | const codeblockStreamIds = useRef<string[]>([]); |
| 206 | |
| 207 | const [reactContent, setMarkdownSource] = useRemark({ |
| 208 | remarkPlugins: [ |
| 209 | remarkTables, |
| 210 | [ |
| 211 | remarkMath, |
| 212 | { |
| 213 | singleDollarTextMath: false, |
| 214 | }, |
| 215 | ], |
| 216 | () => (tree: any) => { |
| 217 | const lastNode = tree.children[tree.children.length - 1]; |
| 218 | const lastCodeNode = lastNode.type === "code" ? lastNode : null; |
| 219 | |
| 220 | visit(tree, "code", (node: any) => { |
| 221 | if (!node.lang) { |
| 222 | node.lang = ""; |
| 223 | } else if (node.lang.includes(".")) { |
| 224 | node.lang = node.lang.split(".").slice(-1)[0]; |
| 225 | } |
| 226 | |
| 227 | node.data = node.data || {}; |
| 228 | node.data.hProperties = node.data.hProperties || {}; |
| 229 | |
| 230 | node.data.hProperties["data-islastcodeblock"] = lastCodeNode === node; |
| 231 | node.data.hProperties["data-codeblockcontent"] = node.value; |
| 232 | |
| 233 | if (node.meta) { |
| 234 | let meta = node.meta.split(" "); |
| 235 | node.data.hProperties["data-relativefilepath"] = meta[0]; |
| 236 | node.data.hProperties.range = meta[1]; |
| 237 | } |
| 238 | }); |
| 239 | }, |
| 240 | ], |
| 241 | rehypePlugins: [ |
| 242 | rehypeKatex as any, |
| 243 | {}, |
| 244 | rehypeHighlightPlugin(), |
| 245 | // Note: An empty obj is the default behavior, but leaving this here for scaffolding to |
| 246 | // add unsupported languages in the future. We will need to install the `lowlight` package |
| 247 | // to use the `common` language set in addition to unsupported languages. |
| 248 | // https://github.com/highlightjs/highlight.js/blob/main/SUPPORTED_LANGUAGES.md |
| 249 | () => { |
| 250 | let codeBlockIndex = 0; |
| 251 | return (tree) => { |
| 252 | visit(tree, { tagName: "pre" }, (node: any) => { |
| 253 | // Add an index (0, 1, 2, etc...) to each code block. |
| 254 | node.properties = { "data-codeblockindex": codeBlockIndex }; |
| 255 | codeBlockIndex++; |
| 256 | }); |
| 257 | }; |
| 258 | }, |
| 259 | {}, |
| 260 | ], |
| 261 | rehypeReactOptions: { |
| 262 | components: { |
| 263 | a: ({ ...aProps }) => { |
| 264 | return ( |
| 265 | <ToolTip place="top" className="m-0 p-0" content={aProps.href}> |
| 266 | <a href={aProps.href} target="_blank" className="hover:underline"> |
| 267 | {aProps.children} |
| 268 | </a> |
| 269 | </ToolTip> |
| 270 | ); |
| 271 | }, |
| 272 | pre: ({ ...preProps }) => { |
| 273 | const codeBlockIndex = preProps["data-codeblockindex"]; |
| 274 | |
| 275 | const preChildProps = preProps?.children?.[0]?.props ?? {}; |
| 276 | const { className, range } = preChildProps; |
| 277 | |
| 278 | const relativeFilePath = preChildProps["data-relativefilepath"]; |
| 279 | const codeBlockContent = preChildProps["data-codeblockcontent"]; |
| 280 | |
| 281 | if (!props.isRenderingInStepContainer) { |
| 282 | return <SyntaxHighlightedPre {...preProps} />; |
| 283 | } |
| 284 | |
| 285 | const language = getLanguageFromClassName(className); |
| 286 | |
| 287 | const isLastCodeblock = preChildProps["data-islastcodeblock"]; |
| 288 | |
| 289 | if (codeblockStreamIds.current[codeBlockIndex] === undefined) { |
| 290 | codeblockStreamIds.current[codeBlockIndex] = uuidv4(); |
| 291 | } |
| 292 | |
| 293 | return ( |
| 294 | <StepContainerPreToolbar |
| 295 | showToolCallStatusIcon={props.showToolCallStatusIcon} |
| 296 | codeBlockContent={codeBlockContent} |
| 297 | itemIndex={itemIndexRef.current} |
| 298 | codeBlockIndex={codeBlockIndex} |
| 299 | language={language} |
| 300 | relativeFilepath={relativeFilePath} |
| 301 | isLastCodeblock={isLastCodeblock} |
| 302 | range={range} |
| 303 | codeBlockStreamId={codeblockStreamIds.current[codeBlockIndex]} // ignored if toolCallId stream state is found |
| 304 | forceToolCallId={props.toolCallId} |
| 305 | expanded={props.expandCodeblocks} |
| 306 | disableManualApply={props.disableManualApply} |
| 307 | collapsible={props.collapsible} |
| 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 | if (codeProps.className?.includes("language-mermaid")) { |
| 335 | const codeText = String(codeProps.children || ""); |
| 336 | return <MermaidBlock code={codeText} />; |
| 337 | } |
| 338 | return <code {...codeProps}>{codeProps.children}</code>; |
| 339 | }, |
| 340 | img: ({ ...imgProps }) => { |
| 341 | return ( |
| 342 | <SecureImageComponent |
| 343 | src={imgProps.src} |
| 344 | alt={imgProps.alt} |
| 345 | title={imgProps.title} |
| 346 | className={imgProps.className} |
| 347 | /> |
| 348 | ); |
| 349 | }, |
| 350 | }, |
| 351 | }, |
| 352 | }); |
| 353 | |
| 354 | useEffect(() => { |
| 355 | setMarkdownSource( |
| 356 | // some patches to source markdown are applied here: |
| 357 | fixDoubleDollarNewLineLatex(patchNestedMarkdown(props.source ?? "")), |
| 358 | ); |
| 359 | }, [props.source, allSymbols]); |
| 360 | |
| 361 | const uiConfig = useAppSelector(selectUIConfig); |
| 362 | const codeWrapState = uiConfig?.codeWrap ? "pre-wrap" : "pre"; |
| 363 | |
| 364 | return ( |
| 365 | <StyledMarkdown |
| 366 | fontSize={getFontSize()} |
| 367 | whiteSpace={codeWrapState} |
| 368 | bgColor={props.useParentBackgroundColor ? "" : vscBackground} |
| 369 | > |
| 370 | {reactContent} |
| 371 | </StyledMarkdown> |
| 372 | ); |
| 373 | }); |
| 374 | |
| 375 | export default StyledMarkdownPreview; |