All files main.js

100% Statements 19/19
100% Branches 10/10
100% Functions 1/1
100% Lines 18/18

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52                                                    4x 3x 3x 3x 3x       3x 3x 3x 3x 3x 3x 2x   1x   3x 3x 1x 1x   3x    
/**
 * *** This styling is an extra step which is likely not required. ***
 * https://github.com/w3c/clipboard-apis/blob/master/explainer.adoc#writing-to-the-clipboard
 * 
 * Why is it here? To ensure:
 * 
 * 1. the element is able to have focus and selection.
 * 2. if element was to flash render it has minimal visual impact.
 * 3. less flakyness with selection and copying which **might** occur if
 *     the textarea element is not visible.
 *
 *   The likelihood is the element won't even render, not even a flash,
 *   so some of these are just precautions. However in IE the element
 *   is visible whilst the popup box asking the user for permission for
 *   the web page to copy to the clipboard.
 *  
 *   Place in top-left corner of screen regardless of scroll position.
 *
 * @typedef CopyTextToClipboard
 * @property {(text: string, method?: (isCopy: boolean) => void) => void} void
 * @returns {void}
 * 
 * @param {string} text 
 * @param {CopyTextToClipboard} cb 
 */
export default function copyTextToClipboard(text, cb) {
  if (typeof document === "undefined") return;
  const el = document.createElement('textarea');
  el.value = text;
  el.setAttribute('readonly', '');
  el.style = {
    position: 'absolute',
    left: '-9999px',
  }
  document.body.appendChild(el);
  const selected = document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false;
  el.select();
  let isCopy = false;
  try {
    const successful = document.execCommand('copy');
    isCopy = !!successful;
  } catch (err) {
    isCopy = false;
  }
  document.body.removeChild(el);
  if (selected && document.getSelection) {
    document.getSelection().removeAllRanges();
    document.getSelection().addRange(selected);
  }
  cb && cb(isCopy);
};