From caa0c46484cb3e59f5ca5d8fbb229b7ebbae023c Mon Sep 17 00:00:00 2001 From: Martin Skou Date: Sun, 25 Aug 2024 16:35:07 +0200 Subject: [PATCH] docs: add a copy code function (top/right copy icon) on doc examples (#22114) --- cmd/tools/vdoc/theme/doc.css | 11 +++++++++++ cmd/tools/vdoc/theme/doc.js | 25 +++++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/cmd/tools/vdoc/theme/doc.css b/cmd/tools/vdoc/theme/doc.css index cf99c739f89e05..82c272eaacedf3 100644 --- a/cmd/tools/vdoc/theme/doc.css +++ b/cmd/tools/vdoc/theme/doc.css @@ -623,6 +623,7 @@ code { pre { overflow: auto; margin: 0; + position: relative; } .namespace { opacity: 0.7; @@ -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 { diff --git a/cmd/tools/vdoc/theme/doc.js b/cmd/tools/vdoc/theme/doc.js index 04319f256bc49b..30be98228f95b1 100644 --- a/cmd/tools/vdoc/theme/doc.js +++ b/cmd/tools/vdoc/theme/doc.js @@ -7,6 +7,7 @@ setupScrollSpy(); setupSearch(); setupCollapse(); + setupCodeCopy(); })(); function setupScrollSpy() { @@ -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 = + ''; + 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); + }); +}