xref: /plugin/copy2clipboard/script.js (revision a0d5ec770e1c09bee95ae69f399737993bf2eff6)
1jQuery(function() {
2  // Copyright (C) 2020 Schplurtz le Déboulonné.
3  // Free to use for any purpose except dismantle the sky.
4  if(!navigator.clipboard)
5    return;
6  var messageBox=function( id, txt ) {
7    const body=document.getElementsByTagName('body')[0];
8    const msg=document.createElement('div');
9    msg.setAttribute('id', id );
10    msg.classList.add('cp2clipmsg');
11    const content = document.createTextNode(txt);
12    msg.appendChild(content);
13    body.appendChild(msg);
14    window.setTimeout(function() {
15        jQuery("#"+id).fadeTo(500, 0).slideUp(500, function(){
16            jQuery(this).remove();
17        });
18    }, 1500);
19  };
20  document.querySelectorAll('pre.code,pre.file').forEach(function(elem) {
21    elem.classList.add('cp2clip');
22    let cp = document.createElement('button');
23    cp.setAttribute( 'title', LANG.plugins.copy2clipboard.title);
24    //cp.appendChild(document.createTextNode('Copy to clipboard')) ;
25    cp.classList.add('cp2clip');
26    elem.appendChild(cp); // pre.appendChild
27    cp.addEventListener('click', async event => {
28      try {
29        // replace ??? geshi adds an NBSP on each empty line. This is an issue
30        // with python, perl... when you want to run copied code, you get a
31        // syntax error "unexpected \xC2 character" or similar... So remove this
32        // crap. And yes it could remove a legitimate NBSP ; chances are low though.
33        const text = event.target.parentElement.textContent.replace(/^\u00A0$/gm, "");
34        await navigator.clipboard.writeText(text);
35        // event.target.textContent = 'Copied to clipboard'
36        // console.log( "copié >>>" + text + "<<<" );
37        messageBox('cp2clipok', LANG.plugins.copy2clipboard.copied);
38      } catch (err) {
39        console.error('Failed to copy!', err);
40        messageBox('cp2clipnok', LANG.plugins.copy2clipboard.error);
41      }
42    })
43  })
44});
45
46