Skip to content

Commit ae68ea0

Browse files
committed
docs: copy code function (top/right copy icon) on examples
implemented with js and css.
1 parent 62c69e8 commit ae68ea0

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

cmd/tools/vdoc/theme/doc.css

+13
Original file line numberDiff line numberDiff line change
@@ -623,6 +623,7 @@ code {
623623
pre {
624624
overflow: auto;
625625
margin: 0;
626+
position: relative;
626627
}
627628
.namespace {
628629
opacity: 0.7;
@@ -684,6 +685,18 @@ tr:nth-child(even) {
684685
background-color: var(--table-background-color);
685686
}
686687

688+
689+
button.copy {
690+
border: none;
691+
background-color: transparent;
692+
position: absolute;
693+
font-size: 12px;
694+
top: 5px;
695+
right: 5px;
696+
color: var(--ref-symbol-hover-color);
697+
}
698+
699+
687700
/* Medium screen and up */
688701
@media (min-width: 768px) {
689702
*::-webkit-scrollbar {

cmd/tools/vdoc/theme/doc.js

+20
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
setupScrollSpy();
88
setupSearch();
99
setupCollapse();
10+
setupCodeCopy();
1011
})();
1112

1213
function setupScrollSpy() {
@@ -300,3 +301,22 @@ function debounce(func, timeout) {
300301
timer = setTimeout(next, timeout > 0 ? timeout : 300);
301302
};
302303
}
304+
305+
function setupCodeCopy() {
306+
const pres = document.querySelectorAll('pre:not(.signature)');
307+
pres.forEach((pre) => {
308+
const tempDiv = document.createElement("button");
309+
tempDiv.className = "copy";
310+
tempDiv.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16" height="16" fill="rgba(173,184,194,1)"><path d="M6.9998 6V3C6.9998 2.44772 7.44752 2 7.9998 2H19.9998C20.5521 2 20.9998 2.44772 20.9998 3V17C20.9998 17.5523 20.5521 18 19.9998 18H16.9998V20.9991C16.9998 21.5519 16.5499 22 15.993 22H4.00666C3.45059 22 3 21.5554 3 20.9991L3.0026 7.00087C3.0027 6.44811 3.45264 6 4.00942 6H6.9998ZM5.00242 8L5.00019 20H14.9998V8H5.00242ZM8.9998 6H16.9998V16H18.9998V4H8.9998V6Z"></path></svg>';
311+
tempDiv.addEventListener('click', (e) => {
312+
const parent = e.target;
313+
var code = tempDiv.parentElement.querySelector("code");
314+
let i = Array.from(code.childNodes).map(r => r.textContent).join("");
315+
navigator.clipboard.writeText(i)
316+
var tmp = tempDiv.innerHTML;
317+
tempDiv.innerHTML="Copied";
318+
window.setTimeout(function() { tempDiv.innerHTML = tmp; },1000);
319+
});
320+
pre.insertAdjacentElement("afterbegin", tempDiv);
321+
});
322+
}

0 commit comments

Comments
 (0)