fix(code.js): filter line number on code copy

This commit is contained in:
ZhenShuo Leo
2025-08-16 16:41:46 +08:00
parent f8d272d9ad
commit 65637ec3f0

View File

@@ -17,7 +17,7 @@ function createCopyButton(highlightDiv) {
}
async function copyCodeToClipboard(button, highlightDiv) {
const codeToCopy = highlightDiv.querySelector(":last-child").innerText;
const codeToCopy = getCleanCodeText(highlightDiv);
try {
result = await navigator.permissions.query({ name: "clipboard-write" });
if (result.state == "granted" || result.state == "prompt") {
@@ -32,6 +32,25 @@ async function copyCodeToClipboard(button, highlightDiv) {
}
}
function getCleanCodeText(highlightDiv) {
const codeElement = highlightDiv.querySelector("code");
if (!codeElement) return "";
const contentElements = codeElement.querySelectorAll(".cl");
if (contentElements.length > 0) {
const lines = Array.from(contentElements).map((el) => el.textContent.replace(/\n$/, ""));
return lines.join("\n");
}
const tableCell = highlightDiv.querySelector(".lntable .lntd:last-child code");
if (tableCell) {
return tableCell.textContent.trim();
}
return codeElement.textContent.trim();
}
function copyCodeBlockExecCommand(codeToCopy, highlightDiv) {
const textArea = document.createElement("textArea");
textArea.contentEditable = "true";