import toggleSelection from './toggleSelection';
import createElement from '../utils/dom/createElement';
function copy(text) {
    var reselectPrevious;
    var range;
    var selection;
    var mark;
    var success = false;
    try {
        reselectPrevious = toggleSelection();
        range = document.createRange();
        selection = document.getSelection();
        mark = createElement('span');
        mark.textContent = text;
        mark.style.all = 'unset';
        mark.style.position = 'fixed';
        mark.style.top = '0';
        mark.style.clip = 'rect(0, 0, 0, 0)';
        mark.style.whiteSpace = 'pre';
        mark.style.webkitUserSelect = 'text';
        mark.style.MozUserSelect = 'text';
        mark.style.msUserSelect = 'text';
        mark.style.userSelect = 'text';
        document.body.appendChild(mark);
        range.selectNodeContents(mark);
        selection.addRange(range);
        var successful = document.execCommand('copy');
        if (!successful) {
            throw new Error('copy command was unsuccessful');
        }
        success = true;
    }
    catch (err) {
        try {
            window.clipboardData.setData('text', text);
            success = true;
        }
        catch (e) {
            console.error(e);
        }
    }
    finally {
        if (selection) {
            if (typeof selection.removeRange === 'function') {
                selection.removeRange(range);
            }
            else {
                selection.removeAllRanges();
            }
        }
        if (mark) {
            document.body.removeChild(mark);
        }
        reselectPrevious();
    }
    return success;
}
export default copy;
