Skip to content

Commit

Permalink
docs: add a copy code function (top/right copy icon) on doc examples (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
martinskou authored Aug 25, 2024
1 parent 62c69e8 commit caa0c46
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
11 changes: 11 additions & 0 deletions cmd/tools/vdoc/theme/doc.css
Original file line number Diff line number Diff line change
Expand Up @@ -623,6 +623,7 @@ code {
pre {
overflow: auto;
margin: 0;
position: relative;
}
.namespace {
opacity: 0.7;
Expand Down Expand Up @@ -684,6 +685,16 @@ tr:nth-child(even) {
background-color: var(--table-background-color);
}

button.copy {
border: none;
background-color: transparent;
position: absolute;
font-size: 12px;
top: 5px;
right: 5px;
color: var(--ref-symbol-hover-color);
}

/* Medium screen and up */
@media (min-width: 768px) {
*::-webkit-scrollbar {
Expand Down
25 changes: 25 additions & 0 deletions cmd/tools/vdoc/theme/doc.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
setupScrollSpy();
setupSearch();
setupCollapse();
setupCodeCopy();
})();

function setupScrollSpy() {
Expand Down Expand Up @@ -300,3 +301,27 @@ function debounce(func, timeout) {
timer = setTimeout(next, timeout > 0 ? timeout : 300);
};
}

function setupCodeCopy() {
const pres = document.querySelectorAll('pre:not(.signature)');
pres.forEach((pre) => {
const tempDiv = document.createElement('button');
tempDiv.className = 'copy';
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>';
tempDiv.addEventListener('click', (e) => {
const parent = e.target;
var code = tempDiv.parentElement.querySelector('code');
let i = Array.from(code.childNodes)
.map((r) => r.textContent)
.join('');
navigator.clipboard.writeText(i);
var tmp = tempDiv.innerHTML;
tempDiv.innerHTML = 'Copied';
window.setTimeout(function () {
tempDiv.innerHTML = tmp;
}, 1000);
});
pre.insertAdjacentElement('afterbegin', tempDiv);
});
}

0 comments on commit caa0c46

Please sign in to comment.