From c148156409347258d6b13faf01c9cab82959096c Mon Sep 17 00:00:00 2001
From: Giteabot <teabot@gitea.io>
Date: Fri, 2 Feb 2024 05:06:21 +0800
Subject: [PATCH] Strip trailing newline in markdown code copy (#29019)
 (#29022)

Behaviour now matches GH. Safeguard added in the for loop because
`textContent` may be null in which case it does not make sense to render
the copy button.

Co-authored-by: silverwind <me@silverwind.io>
(cherry picked from commit 5d1abdce3ea16064fe22e9bdaa436033bdd6698a)
---
 web_src/js/markup/codecopy.js | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/web_src/js/markup/codecopy.js b/web_src/js/markup/codecopy.js
index a12802ef73..078d741253 100644
--- a/web_src/js/markup/codecopy.js
+++ b/web_src/js/markup/codecopy.js
@@ -12,8 +12,10 @@ export function renderCodeCopy() {
   if (!els.length) return;
 
   for (const el of els) {
+    if (!el.textContent) continue;
     const btn = makeCodeCopyButton();
-    btn.setAttribute('data-clipboard-text', el.textContent);
+    // remove final trailing newline introduced during HTML rendering
+    btn.setAttribute('data-clipboard-text', el.textContent.replace(/\r?\n$/, ''));
     el.after(btn);
   }
 }