|
| 1 | +import React, { useMemo, useState } from 'react'; |
| 2 | +import Markdown, { ExtraProps } from 'react-markdown'; |
| 3 | +import remarkGfm from 'remark-gfm'; |
| 4 | +import rehypeHightlight from 'rehype-highlight'; |
| 5 | +import rehypeKatex from 'rehype-katex'; |
| 6 | +import remarkMath from 'remark-math'; |
| 7 | +import remarkBreaks from 'remark-breaks'; |
| 8 | +import 'katex/dist/katex.min.css'; |
| 9 | +import { copyStr } from '../utils/misc'; |
| 10 | + |
| 11 | +export default function MarkdownDisplay({ content }: { content: string }) { |
| 12 | + const preprocessedContent = useMemo( |
| 13 | + () => preprocessLaTeX(content), |
| 14 | + [content] |
| 15 | + ); |
| 16 | + return ( |
| 17 | + <Markdown |
| 18 | + remarkPlugins={[remarkGfm, remarkMath, remarkBreaks]} |
| 19 | + rehypePlugins={[rehypeHightlight, rehypeKatex]} |
| 20 | + components={{ |
| 21 | + pre: (props) => <Pre {...props} origContent={preprocessedContent} />, |
| 22 | + }} |
| 23 | + > |
| 24 | + {preprocessedContent} |
| 25 | + </Markdown> |
| 26 | + ); |
| 27 | +} |
| 28 | + |
| 29 | +const Pre: React.ElementType< |
| 30 | + React.ClassAttributes<HTMLPreElement> & |
| 31 | + React.HTMLAttributes<HTMLPreElement> & |
| 32 | + ExtraProps & { origContent: string } |
| 33 | +> = ({ node, origContent, ...props }) => { |
| 34 | + const startOffset = node?.position?.start.offset ?? 0; |
| 35 | + const endOffset = node?.position?.end.offset ?? 0; |
| 36 | + |
| 37 | + const [copied, setCopied] = useState(false); |
| 38 | + const copiedContent = useMemo( |
| 39 | + () => |
| 40 | + origContent |
| 41 | + .substring(startOffset, endOffset) |
| 42 | + .replace(/^```[^\n]+\n/g, '') |
| 43 | + .replace(/```$/g, ''), |
| 44 | + [origContent, startOffset, endOffset] |
| 45 | + ); |
| 46 | + |
| 47 | + if (!node?.position) { |
| 48 | + return <pre {...props} />; |
| 49 | + } |
| 50 | + |
| 51 | + return ( |
| 52 | + <div className="relative my-4"> |
| 53 | + <div |
| 54 | + className="text-right sticky top-4 mb-2 mr-2 h-0" |
| 55 | + onClick={() => { |
| 56 | + copyStr(copiedContent); |
| 57 | + setCopied(true); |
| 58 | + }} |
| 59 | + onMouseLeave={() => setCopied(false)} |
| 60 | + > |
| 61 | + <button className="badge btn-mini"> |
| 62 | + {copied ? 'Copied!' : '📋 Copy'} |
| 63 | + </button> |
| 64 | + </div> |
| 65 | + <pre {...props} /> |
| 66 | + </div> |
| 67 | + ); |
| 68 | +}; |
| 69 | + |
| 70 | +/** |
| 71 | + * The part below is copied and adapted from: |
| 72 | + * https://github.com/danny-avila/LibreChat/blob/main/client/src/utils/latex.ts |
| 73 | + * (MIT License) |
| 74 | + */ |
| 75 | + |
| 76 | +// Regex to check if the processed content contains any potential LaTeX patterns |
| 77 | +const containsLatexRegex = |
| 78 | + /\\\(.*?\\\)|\\\[.*?\\\]|\$.*?\$|\\begin\{equation\}.*?\\end\{equation\}/; |
| 79 | + |
| 80 | +// Regex for inline and block LaTeX expressions |
| 81 | +const inlineLatex = new RegExp(/\\\((.+?)\\\)/, 'g'); |
| 82 | +const blockLatex = new RegExp(/\\\[(.*?[^\\])\\\]/, 'gs'); |
| 83 | + |
| 84 | +// Function to restore code blocks |
| 85 | +const restoreCodeBlocks = (content: string, codeBlocks: string[]) => { |
| 86 | + return content.replace( |
| 87 | + /<<CODE_BLOCK_(\d+)>>/g, |
| 88 | + (_, index) => codeBlocks[index] |
| 89 | + ); |
| 90 | +}; |
| 91 | + |
| 92 | +// Regex to identify code blocks and inline code |
| 93 | +const codeBlockRegex = /(```[\s\S]*?```|`.*?`)/g; |
| 94 | + |
| 95 | +export const processLaTeX = (_content: string) => { |
| 96 | + let content = _content; |
| 97 | + // Temporarily replace code blocks and inline code with placeholders |
| 98 | + const codeBlocks: string[] = []; |
| 99 | + let index = 0; |
| 100 | + content = content.replace(codeBlockRegex, (match) => { |
| 101 | + codeBlocks[index] = match; |
| 102 | + return `<<CODE_BLOCK_${index++}>>`; |
| 103 | + }); |
| 104 | + |
| 105 | + // Escape dollar signs followed by a digit or space and digit |
| 106 | + let processedContent = content.replace(/(\$)(?=\s?\d)/g, '\\$'); |
| 107 | + |
| 108 | + // If no LaTeX patterns are found, restore code blocks and return the processed content |
| 109 | + if (!containsLatexRegex.test(processedContent)) { |
| 110 | + return restoreCodeBlocks(processedContent, codeBlocks); |
| 111 | + } |
| 112 | + |
| 113 | + // Convert LaTeX expressions to a markdown compatible format |
| 114 | + processedContent = processedContent |
| 115 | + .replace(inlineLatex, (_: string, equation: string) => `$${equation}$`) // Convert inline LaTeX |
| 116 | + .replace(blockLatex, (_: string, equation: string) => `$$${equation}$$`); // Convert block LaTeX |
| 117 | + |
| 118 | + // Restore code blocks |
| 119 | + return restoreCodeBlocks(processedContent, codeBlocks); |
| 120 | +}; |
| 121 | + |
| 122 | +/** |
| 123 | + * Preprocesses LaTeX content by replacing delimiters and escaping certain characters. |
| 124 | + * |
| 125 | + * @param content The input string containing LaTeX expressions. |
| 126 | + * @returns The processed string with replaced delimiters and escaped characters. |
| 127 | + */ |
| 128 | +export function preprocessLaTeX(content: string): string { |
| 129 | + // Step 1: Protect code blocks |
| 130 | + const codeBlocks: string[] = []; |
| 131 | + content = content.replace(/(```[\s\S]*?```|`[^`\n]+`)/g, (_, code) => { |
| 132 | + codeBlocks.push(code); |
| 133 | + return `<<CODE_BLOCK_${codeBlocks.length - 1}>>`; |
| 134 | + }); |
| 135 | + |
| 136 | + // Step 2: Protect existing LaTeX expressions |
| 137 | + const latexExpressions: string[] = []; |
| 138 | + content = content.replace( |
| 139 | + /(\$\$[\s\S]*?\$\$|\\\[[\s\S]*?\\\]|\\\(.*?\\\))/g, |
| 140 | + (match) => { |
| 141 | + latexExpressions.push(match); |
| 142 | + return `<<LATEX_${latexExpressions.length - 1}>>`; |
| 143 | + } |
| 144 | + ); |
| 145 | + |
| 146 | + // Step 3: Escape dollar signs that are likely currency indicators |
| 147 | + content = content.replace(/\$(?=\d)/g, '\\$'); |
| 148 | + |
| 149 | + // Step 4: Restore LaTeX expressions |
| 150 | + content = content.replace( |
| 151 | + /<<LATEX_(\d+)>>/g, |
| 152 | + (_, index) => latexExpressions[parseInt(index)] |
| 153 | + ); |
| 154 | + |
| 155 | + // Step 5: Restore code blocks |
| 156 | + content = content.replace( |
| 157 | + /<<CODE_BLOCK_(\d+)>>/g, |
| 158 | + (_, index) => codeBlocks[parseInt(index)] |
| 159 | + ); |
| 160 | + |
| 161 | + // Step 6: Apply additional escaping functions |
| 162 | + content = escapeBrackets(content); |
| 163 | + content = escapeMhchem(content); |
| 164 | + |
| 165 | + return content; |
| 166 | +} |
| 167 | + |
| 168 | +export function escapeBrackets(text: string): string { |
| 169 | + const pattern = |
| 170 | + /(```[\S\s]*?```|`.*?`)|\\\[([\S\s]*?[^\\])\\]|\\\((.*?)\\\)/g; |
| 171 | + return text.replace( |
| 172 | + pattern, |
| 173 | + ( |
| 174 | + match: string, |
| 175 | + codeBlock: string | undefined, |
| 176 | + squareBracket: string | undefined, |
| 177 | + roundBracket: string | undefined |
| 178 | + ): string => { |
| 179 | + if (codeBlock != null) { |
| 180 | + return codeBlock; |
| 181 | + } else if (squareBracket != null) { |
| 182 | + return `$$${squareBracket}$$`; |
| 183 | + } else if (roundBracket != null) { |
| 184 | + return `$${roundBracket}$`; |
| 185 | + } |
| 186 | + return match; |
| 187 | + } |
| 188 | + ); |
| 189 | +} |
| 190 | + |
| 191 | +export function escapeMhchem(text: string) { |
| 192 | + return text.replaceAll('$\\ce{', '$\\\\ce{').replaceAll('$\\pu{', '$\\\\pu{'); |
| 193 | +} |
0 commit comments