From 9ea21305f5f2ee1400ecb5714f8d9881db654f24 Mon Sep 17 00:00:00 2001 From: igoradamenko Date: Sat, 24 Nov 2018 23:23:34 +0200 Subject: [PATCH] improve `copy` helper for copying text styles --- web/app/common/copy.js | 42 ++++++++++++++++++++++++++++-------------- 1 file changed, 28 insertions(+), 14 deletions(-) diff --git a/web/app/common/copy.js b/web/app/common/copy.js index eae7206d..3a352488 100644 --- a/web/app/common/copy.js +++ b/web/app/common/copy.js @@ -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) {