Commit | Line | Data |
---|---|---|
6973441b TD |
1 | /** |
2 | * Wrapper around the web browser's various clipboard APIs. | |
3 | * | |
4 | * @author Tim Duesterhus | |
7b7b9764 | 5 | * @copyright 2001-2019 WoltLab GmbH |
6973441b TD |
6 | * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> |
7 | * @module WoltLabSuite/Core/Clipboard | |
8 | */ | |
58b949c4 | 9 | define(['Environment', 'Ui/Screen'], function(Environment, UiScreen) { |
6973441b TD |
10 | "use strict"; |
11 | ||
12 | return { | |
8d1094cc | 13 | copyTextToClipboard: function (text) { |
6973441b | 14 | if (navigator.clipboard) { |
8d1094cc | 15 | return navigator.clipboard.writeText(text); |
6973441b | 16 | } |
8d1094cc TD |
17 | else if (window.getSelection) { |
18 | var textarea = elCreate('textarea'); | |
aa583b93 TD |
19 | textarea.contentEditable = true; |
20 | textarea.readOnly = false; | |
58b949c4 AE |
21 | |
22 | // iOS has some implicit restrictions that, if crossed, cause the browser to scroll to the top. | |
23 | var scrollDisabled = false; | |
24 | if (Environment.platform() === 'ios') { | |
25 | scrollDisabled = true; | |
26 | UiScreen.scrollDisable(); | |
27 | ||
28 | var topPx = (~~(window.innerHeight / 4) + window.pageYOffset); | |
29 | textarea.style.cssText = 'font-size: 16px; position: absolute; left: 1px; top: ' + topPx + 'px; width: 50px; height: 50px; overflow: hidden;border: 5px solid red;'; | |
30 | } | |
31 | else { | |
32 | textarea.style.cssText = 'position: absolute; left: -9999px; top: -9999px; width: 0; height: 0;'; | |
33 | } | |
34 | ||
8d1094cc TD |
35 | document.body.appendChild(textarea); |
36 | try { | |
aa583b93 | 37 | // see: https://stackoverflow.com/a/34046084/782822 |
8d1094cc | 38 | textarea.value = text; |
aa583b93 TD |
39 | var range = document.createRange(); |
40 | range.selectNodeContents(textarea); | |
41 | var selection = window.getSelection(); | |
42 | selection.removeAllRanges(); | |
43 | selection.addRange(range); | |
44 | textarea.setSelectionRange(0, 999999); | |
8d1094cc TD |
45 | if (!document.execCommand('copy')) { |
46 | return Promise.reject(new Error("execCommand('copy') failed")); | |
47 | } | |
48 | return Promise.resolve(); | |
49 | } | |
50 | finally { | |
51 | elRemove(textarea); | |
58b949c4 AE |
52 | |
53 | if (scrollDisabled) { | |
54 | UiScreen.scrollEnable(); | |
55 | } | |
8d1094cc | 56 | } |
6973441b TD |
57 | } |
58 | ||
8d1094cc TD |
59 | return Promise.reject(new Error('Neither navigator.clipboard, nor window.getSelection is supported.')); |
60 | }, | |
61 | ||
62 | copyElementTextToClipboard: function (element) { | |
e8ebe776 | 63 | return this.copyTextToClipboard(element.textContent.replace(/\u200B/g, '').replace(/\u00A0/g, ' ')); |
6973441b TD |
64 | } |
65 | }; | |
66 | }); |