improve copy helper for copying text styles

This commit is contained in:
igoradamenko
2018-11-24 23:23:34 +02:00
parent 154e23f8fb
commit 9ea21305f5
+28 -14
View File
@@ -1,35 +1,49 @@
// https://github.com/sindresorhus/copy-text-to-clipboard
// based on https://github.com/sindresorhus/copy-text-to-clipboard, but improved to copy text styles too
module.exports = input => {
const el = document.createElement('textarea');
const el = document.createElement('div');
el.value = input;
// Prevent keyboard from showing on mobile
el.setAttribute('readonly', '');
el.innerHTML = input;
el.style.contain = 'strict';
el.style.position = 'absolute';
el.style.left = '-9999px';
el.style.fontSize = '12pt'; // Prevent zooming on iOS
const selection = document.getSelection();
document.body.appendChild(el);
const currentSelection = document.getSelection();
let originalRange = false;
if (selection.rangeCount > 0) {
originalRange = selection.getRangeAt(0);
if (currentSelection.rangeCount > 0) {
originalRange = currentSelection.getRangeAt(0);
}
document.body.appendChild(el);
el.select();
let range, selection;
// Explicit selection workaround for iOS
el.selectionStart = 0;
el.selectionEnd = input.length;
if (document.body.createTextRange) {
range = document.body.createTextRange();
range.moveToElement(el);
range.select();
} else if (window.getSelection) {
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(el);
selection.removeAllRanges();
selection.addRange(range);
}
document.execCommand('copy');
let success = false;
try {
success = document.execCommand('copy');
} catch (err) {}
if (!document.body.createTextRange && window.getSelection) {
window.getSelection().removeAllRanges();
}
document.body.removeChild(el);
if (originalRange) {