From b96f4d88f837f7621eb803dfab0869e3a9ad2acb Mon Sep 17 00:00:00 2001 From: thisisommore Date: Mon, 2 Aug 2021 08:33:37 +0000 Subject: [PATCH] docs(code): Introduce copy code feature --- .../porter/assets/sass/docs-content.scss | 11 ++++++- docs/themes/porter/layouts/partials/js.html | 1 + .../porter/static/js/custom/copy_code.js | 29 +++++++++++++++++++ 3 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 docs/themes/porter/static/js/custom/copy_code.js diff --git a/docs/themes/porter/assets/sass/docs-content.scss b/docs/themes/porter/assets/sass/docs-content.scss index 5f14e85216..4371fa55b5 100755 --- a/docs/themes/porter/assets/sass/docs-content.scss +++ b/docs/themes/porter/assets/sass/docs-content.scss @@ -164,7 +164,7 @@ color: black; border: none; padding: 0.75em 1em; - margin: 0.25em 0 2.5em; + margin: 0 0 2.5em; font-size: 1rem; code { @@ -280,3 +280,12 @@ min-height: 320px; } } + +.copy-button-container { + display: flex; + justify-content: flex-end; + .copy-button { + margin-bottom: 0; + padding: 4px; + } +} \ No newline at end of file diff --git a/docs/themes/porter/layouts/partials/js.html b/docs/themes/porter/layouts/partials/js.html index ad72c347cc..f27db697e8 100755 --- a/docs/themes/porter/layouts/partials/js.html +++ b/docs/themes/porter/layouts/partials/js.html @@ -5,3 +5,4 @@ + diff --git a/docs/themes/porter/static/js/custom/copy_code.js b/docs/themes/porter/static/js/custom/copy_code.js new file mode 100644 index 0000000000..945d05ee5f --- /dev/null +++ b/docs/themes/porter/static/js/custom/copy_code.js @@ -0,0 +1,29 @@ +document.querySelectorAll("pre").forEach(ele => { + var codeElement = ele.querySelector("code") + + if (codeElement != null) { + with (document) { + var copyButtonContainer = createElement('div') + copyButtonContainer.classList.add("copy-button-container") + var copyButton = createElement('button'); + copyButtonContainer.append(copyButton) + } + + with (copyButton) { + className = "copy-button" + innerText = 'copy'; + + addEventListener('click', () => { + navigator.clipboard.writeText(codeElement.innerText).then(e => { + innerText = "copied" + }).catch(e => { + innerText = "error" + }) + setTimeout(() => innerText = "copy", 900) + }); + } + + ele.parentElement.insertBefore(copyButtonContainer, ele) + } +}) +