All files / src/utils/edit clipboard.js

2.56% Statements 1/39
0% Branches 0/14
0% Functions 0/6
2.56% Lines 1/39

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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89            7x                                                                                                                                                                    
/**
 * https://github.com/zenorocha/clipboard.js/blob/master/src/clipboard-action.js
 */
 
import select from './select';
 
const clipboard = {
    fakeElem: undefined,
    container: undefined,
    init() {
        this.container = document.body;
        if (!this.fakeElem)
            this.initFake();
    },
    initFake() {
        const isRTL = document.documentElement.getAttribute('dir') === 'rtl';
 
        this.removeFake();
 
        this.fakeElem = document.createElement('textarea');
        // Prevent zooming on iOS
        this.fakeElem.style.fontSize = '12pt';
        // Reset box model
        this.fakeElem.style.border = '0';
        this.fakeElem.style.padding = '0';
        this.fakeElem.style.margin = '0';
        // Move element out of screen horizontally
        this.fakeElem.style.position = 'absolute';
        this.fakeElem.style[isRTL ? 'right' : 'left'] = '-9999px';
        // Move element to the same position vertically
        const yPosition = window.pageYOffset || document.documentElement.scrollTop;
        this.fakeElem.style.top = `${yPosition}px`;
 
        this.container.appendChild(this.fakeElem);
    },
    removeFake() {
        if (this.fakeElem) {
            this.container.removeChild(this.fakeElem);
            this.fakeElem = undefined;
        }
    },
    destroy() {
        this.removeFake();
    },
    copy(text) {
        this.fakeElem.value = text;
        select(this.fakeElem);
 
        let succeeded;
 
        try {
            succeeded = document.execCommand('copy');
        } catch (err) {
            succeeded = false;
        }
 
        return succeeded;
    },
};
 
/**
 * @param { Element | String } text - target or text
 */
export function copy(text) {
    if (!text)
        return false;
    let target;
    if (text instanceof HTMLElement)
        target = text;
    else {
        if (!clipboard.fakeElem)
            clipboard.init();
        target = clipboard.fakeElem;
        target.value = text;
    }
 
    select(target);
 
    let succeeded;
    try {
        succeeded = document.execCommand('copy');
    } catch (err) {
        succeeded = false;
    }
 
    return succeeded;
}