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; })();