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
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 18 additions and 26 deletions

View File

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

View File

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