aboutsummaryrefslogtreecommitdiffstats
path: root/tiddlers/copy-codeblock.tid
diff options
context:
space:
mode:
authorshu <nvcsadjkojf@outlook.com>2026-07-26 18:33:43 +0800
committershu <nvcsadjkojf@outlook.com>2026-07-26 18:33:43 +0800
commitc1414f940c1fca93df0c266a3e90c9ff1d7e88c7 (patch)
tree4d613a365905d12699d71b3bfb2f68d2a7089c1c /tiddlers/copy-codeblock.tid
Initial TiddlyWiki setup
Diffstat (limited to 'tiddlers/copy-codeblock.tid')
-rw-r--r--tiddlers/copy-codeblock.tid72
1 files changed, 72 insertions, 0 deletions
diff --git a/tiddlers/copy-codeblock.tid b/tiddlers/copy-codeblock.tid
new file mode 100644
index 0000000..2251c62
--- /dev/null
+++ b/tiddlers/copy-codeblock.tid
@@ -0,0 +1,72 @@
+title: $:/plugins/local/copy-codeblock/copy-codeblock.js
+type: application/javascript
+module-type: widget
+
+/*\
+title: $:/plugins/local/copy-codeblock/copy-codeblock.js
+type: application/javascript
+module-type: widget
+
+Adds a copy button to code blocks.
+\*/
+(function() {
+"use strict";
+
+var CodeBlockWidget = require("$:/core/modules/widgets/codeblock.js").codeblock;
+
+var CopyCodeBlockWidget = function(parseTreeNode,options) {
+ this.initialise(parseTreeNode,options);
+};
+
+CopyCodeBlockWidget.prototype = new CodeBlockWidget();
+CopyCodeBlockWidget.prototype.constructor = CopyCodeBlockWidget;
+
+CopyCodeBlockWidget.prototype.postRender = function() {
+ var self = this,
+ preNode = this.domNodes[0],
+ previousNode,
+ button;
+
+ // Preserve syntax highlighting supplied by the highlight plugin.
+ if(CodeBlockWidget.prototype.postRender) {
+ CodeBlockWidget.prototype.postRender.call(this);
+ }
+
+ if(!$tw.browser || !preNode || preNode.isTiddlyWikiFakeDom) {
+ return;
+ }
+
+ // The system code view already renders its own copy button.
+ previousNode = preNode.previousElementSibling;
+ if(previousNode && previousNode.querySelector && previousNode.querySelector(".tc-image-copy-clipboard")) {
+ return;
+ }
+
+ preNode.style.position = "relative";
+ preNode.style.paddingRight = "5em";
+
+ button = this.document.createElement("button");
+ button.setAttribute("type","button");
+ button.setAttribute("aria-label","Copy code");
+ button.setAttribute("title","Copy code");
+ button.className = "tc-btn-invisible tc-copy-codeblock-button";
+ button.textContent = "Copy";
+ button.style.position = "absolute";
+ button.style.top = "0.5em";
+ button.style.right = "0.5em";
+ button.style.zIndex = "1";
+ button.style.padding = "0.2em 0.45em";
+ button.style.cursor = "pointer";
+
+ button.addEventListener("click",function(event) {
+ event.preventDefault();
+ event.stopPropagation();
+ $tw.utils.copyToClipboard(self.getAttribute("code",""));
+ });
+
+ preNode.appendChild(button);
+};
+
+exports.codeblock = CopyCodeBlockWidget;
+
+})();