improved code block copying (#2802)

* improved code block copying

* k
This commit is contained in:
pablodanswer
2024-10-15 16:22:40 -07:00
committed by GitHub
parent bfe963988e
commit 02cc211e91
2 changed files with 18 additions and 26 deletions

View File

@ -256,7 +256,7 @@ export const AIMessage = ({
() => ({ () => ({
a: MemoizedLink, a: MemoizedLink,
p: MemoizedParagraph, p: MemoizedParagraph,
code: ({ node, inline, className, children, ...props }: any) => { code: ({ node, className, children, ...props }: any) => {
const codeText = extractCodeText( const codeText = extractCodeText(
node, node,
finalContent as string, finalContent as string,

View File

@ -4,40 +4,32 @@ export function extractCodeText(
children: React.ReactNode children: React.ReactNode
): string { ): string {
let codeText: string | null = null; let codeText: string | null = null;
if ( if (
node?.position?.start?.offset != null && node?.position?.start?.offset != null &&
node?.position?.end?.offset != null node?.position?.end?.offset != null
) { ) {
codeText = content.slice( codeText = content
node.position.start.offset, .slice(node.position.start.offset, node.position.end.offset)
node.position.end.offset .trim();
);
codeText = codeText.trim();
// Find the last occurrence of closing backticks // Match code block with optional language declaration
const lastBackticksIndex = codeText.lastIndexOf("```"); const codeBlockMatch = codeText.match(/^```[^\n]*\n([\s\S]*?)\n?```$/);
if (lastBackticksIndex !== -1) { if (codeBlockMatch) {
codeText = codeText.slice(0, lastBackticksIndex + 3); codeText = codeBlockMatch[1];
} }
// Remove the language declaration and trailing backticks // Normalize indentation
const codeLines = codeText.split("\n"); const codeLines = codeText.split("\n");
if (codeLines.length > 1 && codeLines[0].trim().startsWith("```")) { const minIndent = codeLines
codeLines.shift(); // Remove the first line with the language declaration .filter((line) => line.trim().length > 0)
if (codeLines[codeLines.length - 1]?.trim() === "```") { .reduce((min, line) => {
codeLines.pop(); // Remove the last line with the trailing backticks const match = line.match(/^\s*/);
} return Math.min(min, match ? match[0].length : min);
}, Infinity);
const minIndent = codeLines const formattedCodeLines = codeLines.map((line) => line.slice(minIndent));
.filter((line) => line.trim().length > 0) codeText = formattedCodeLines.join("\n").trim();
.reduce((min, line) => {
const match = line.match(/^\s*/);
return Math.min(min, match ? match[0].length : 0);
}, Infinity);
const formattedCodeLines = codeLines.map((line) => line.slice(minIndent));
codeText = formattedCodeLines.join("\n");
}
} else { } else {
// Fallback if position offsets are not available // Fallback if position offsets are not available
codeText = children?.toString() || null; codeText = children?.toString() || null;