From 65637ec3f0f95015e5f0c8691fcd05368dddc329 Mon Sep 17 00:00:00 2001 From: ZhenShuo Leo <98386542+ZhenShuo2021@users.noreply.github.com> Date: Sat, 16 Aug 2025 16:41:46 +0800 Subject: [PATCH] fix(code.js): filter line number on code copy --- assets/js/code.js | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/assets/js/code.js b/assets/js/code.js index 8639ad8d..f2efe534 100644 --- a/assets/js/code.js +++ b/assets/js/code.js @@ -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";