Skip to content

Node.js based forum software built for the modern web

feat: closes #11428, add a copy code button to code blocks

Barış Soner Uşaklı0a292fc1aed6
diff --git a/public/language/en-GB/topic.json b/public/language/en-GB/topic.json
index a3191cfdfd..d360fff733 100644
--- a/public/language/en-GB/topic.json
+++ b/public/language/en-GB/topic.json
@@ -39,6 +39,7 @@
"scheduled": "Scheduled",
"moved": "Moved",
"moved-from": "Moved from %1",
+ "copy-code": "Copy Code",
"copy-ip": "Copy IP",
"ban-ip": "Ban IP",
"view-history": "Edit History",
diff --git a/public/src/client/topic.js b/public/src/client/topic.js
index 012cc573ff..4e68fd004d 100644
--- a/public/src/client/topic.js
+++ b/public/src/client/topic.js
@@ -16,11 +16,12 @@ define('forum/topic', [
'api',
'alerts',
'bootbox',
+ 'clipboard',
], function (
infinitescroll, threadTools, postTools,
events, posts, navigator, sort, quickreply,
components, storage, hooks, api, alerts,
- bootbox
+ bootbox, clipboard,
) {
const Topic = {};
let tid = 0;
@@ -61,6 +62,7 @@ define('forum/topic', [
}
addBlockQuoteHandler();
+ addCodeBlockHandler();
addParentHandler();
addDropupHandler();
addRepliesHandler();
@@ -218,6 +220,29 @@ define('forum/topic', [
});
}
+ function addCodeBlockHandler() {
+ new clipboard('[component="copy/code/btn"]', {
+ text: function (trigger) {
+ const btn = $(trigger);
+ btn.find('i').removeClass('fa-copy').addClass('fa-check');
+ setTimeout(() => btn.find('i').removeClass('fa-check').addClass('fa-copy'), 2000);
+ return btn.parent().find('code').text();
+ },
+ });
+
+ function addCopyCodeButton() {
+ const codeBlocks = $('[component="topic"] [component="post/content"] code:not([data-button-added])');
+ const container = $('<div class="hover-parent position-relative"></div>');
+ const buttonDiv = $('<button component="copy/code/btn" class="hover-visible position-absolute end-0 top-0 btn btn-sm btn-outline-secondary"><i class="fa fa-fw fa-copy"></i></button>');
+ codeBlocks.parent().wrap(container).parent().append(buttonDiv);
+ codeBlocks.parent().parent().find('[component="copy/code/btn"]').translateAttr('title', '[[topic:copy-code]]');
+ codeBlocks.attr('data-button-added', 1);
+ }
+ hooks.registerPage('action:posts.loaded', addCopyCodeButton);
+ hooks.registerPage('action:topic.loaded', addCopyCodeButton);
+ hooks.registerPage('action:posts.edited', addCopyCodeButton);
+ }
+
function addParentHandler() {
components.get('topic').on('click', '[component="post/parent"]', function (e) {
const toPid = $(this).attr('data-topid');