From 4ee78cbd3b449162b9ba6d1c35aac5696279c5a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cain=C3=A3=20Brazil?= Date: Mon, 23 Sep 2019 16:58:44 +0100 Subject: [PATCH] now using clipboard API, added feedback for error and content copied --- clientRootMixin.js | 30 +++++++++++------------------- style.css | 32 ++++++++++++++++++++++++++++++-- 2 files changed, 41 insertions(+), 21 deletions(-) diff --git a/clientRootMixin.js b/clientRootMixin.js index fcd051c..2b17abb 100755 --- a/clientRootMixin.js +++ b/clientRootMixin.js @@ -26,29 +26,21 @@ export default { copyElement.className = 'code-copy' copyElement.title = 'Click to Copy to Clipboard' copyElement.addEventListener( 'click', () => { - this.copyToClipboard( parent.innerText ) + this.copyToClipboard( parent.innerText, copyElement ) } ) parent.appendChild( copyElement ) parent.classList.add( 'codecopy-enabled' ) }, - copyToClipboard: function( str ) { - const el = document.createElement( 'textarea' ) - el.value = str - el.setAttribute( 'readonly', '' ) - el.style.position = 'absolute' - el.style.left = '-9999px' - document.body.appendChild( el ) - const selected = - document.getSelection().rangeCount > 0 - ? document.getSelection().getRangeAt( 0 ) - : false - el.select() - document.execCommand( 'copy' ) - document.body.removeChild( el ) - if ( selected ) { - document.getSelection().removeAllRanges() - document.getSelection().addRange( selected ) - } + copyToClipboard: function( str, copyElement ) { + navigator.clipboard.writeText(str) + .then(() => { + copyElement.classList.add( '_suc' ); + console.log('success'); + }) + .catch(() => { + copyElement.classList.add( '_err' ); + console.log('error'); + }); } } } diff --git a/style.css b/style.css index bf1acb4..2475ba2 100755 --- a/style.css +++ b/style.css @@ -3,14 +3,33 @@ display: inline-block; cursor: pointer; } + +.code-copy::after { + position: absolute; + right: calc(100% + 8px); + background: #424242e5; +} + +.code-copy._suc::after { + content: "Content Copied!"; + opacity: 0; /* for animation to work */ + animation: fadeout 3s; +} + +.code-copy._err::after { + content: "Oops, an error occurred!"; + opacity: 0; /* for animation to work */ + animation: fadeout 3s; +} + div[class*="language-"] pre .code-copy { position: absolute; z-index: 1000; top: 35px; right: 5px; - width: 20px; + width: 24px; height: 30px; - content: url('./copy.svg'); + background: no-repeat url('./copy.svg'); opacity: 0; } @@ -21,3 +40,12 @@ div[class*="language-"] pre:hover .code-copy { .content pre, .content pre[class*=language-] { overflow-y: hidden; } + +@keyframes fadeout { + 0% { + opacity: 1; + } + 100% { + opacity: 0; + } +}