2
2
/* global Babel -- global scope directive */
3
3
import hljs from 'highlight.js/lib/core' ;
4
4
import javascript from 'highlight.js/lib/languages/javascript' ;
5
+ import { createPopper } from '@popperjs/core' ;
5
6
6
7
hljs . registerLanguage ( 'javascript' , javascript ) ;
7
8
@@ -28,6 +29,8 @@ function init() {
28
29
const resultBlock = document . querySelector ( '.result' ) ;
29
30
const backLinkBlock = document . querySelector ( '.back-link' ) ;
30
31
const backLink = document . querySelector ( '.back-link a' ) ;
32
+ const tooltip = document . querySelector ( '#tooltip' ) ;
33
+ const tooltipText = document . querySelector ( '#tooltip-text' ) ;
31
34
32
35
if ( ! codeInput ) return ;
33
36
@@ -199,6 +202,44 @@ function init() {
199
202
) ;
200
203
}
201
204
205
+ function copyToClipboard ( text ) {
206
+ if ( navigator . clipboard && window . isSecureContext ) {
207
+ return navigator . clipboard . writeText ( text ) ;
208
+ } else {
209
+ const textArea = document . createElement ( "textarea" ) ;
210
+ textArea . value = text ;
211
+ textArea . style . position = "fixed" ;
212
+ textArea . style . top = '0' ;
213
+ textArea . style . left = '0' ;
214
+ textArea . style . opacity = '0' ;
215
+ document . body . appendChild ( textArea ) ;
216
+ textArea . focus ( ) ;
217
+ textArea . select ( ) ;
218
+
219
+ try {
220
+ const successful = document . execCommand ( 'copy' ) ;
221
+ document . body . removeChild ( textArea ) ;
222
+ if ( successful ) {
223
+ return Promise . resolve ( ) ;
224
+ } else {
225
+ return Promise . reject ( new Error ( 'Copy command was unsuccessful' ) ) ;
226
+ }
227
+ } catch ( err ) {
228
+ document . body . removeChild ( textArea ) ;
229
+ return Promise . reject ( err ) ;
230
+ }
231
+ }
232
+ }
233
+
234
+ function showTooltip ( element , message , time = 3000 ) {
235
+ tooltipText . innerHTML = message ;
236
+ tooltip . setAttribute ( 'data-show' , '' ) ;
237
+ createPopper ( element , tooltip , { placement : 'bottom' } ) ;
238
+ setTimeout ( ( ) => {
239
+ tooltip . removeAttribute ( 'data-show' ) ;
240
+ } , time ) ;
241
+ }
242
+
202
243
codeInput . addEventListener ( 'input' , ( ) => {
203
244
codeOutput . removeAttribute ( 'data-highlighted' ) ;
204
245
let val = codeInput . value ;
@@ -231,6 +272,10 @@ function init() {
231
272
e . preventDefault ( ) ;
232
273
pageParams . set ( 'code' , codeInput . value ) ;
233
274
globalThis . location . hash = pageParams . toString ( ) ;
275
+ copyToClipboard ( globalThis . location . toString ( ) )
276
+ . then ( ( ) => {
277
+ showTooltip ( linkButton , 'Link copied' ) ;
278
+ } ) ;
234
279
} ) ;
235
280
} ) ;
236
281
0 commit comments