keeweb/app/scripts/comp/browser/copy-paste.js

72 lines
2.2 KiB
JavaScript
Raw Normal View History

2019-09-15 14:16:32 +02:00
import Backbone from 'backbone';
import { Launcher } from 'comp/launcher';
import { AppSettingsModel } from 'models/app-settings-model';
2015-10-29 22:13:15 +01:00
2017-01-31 07:50:28 +01:00
const CopyPaste = {
simpleCopy: !!(Launcher && Launcher.clipboardSupported),
2016-01-22 18:51:36 +01:00
2019-08-18 10:17:09 +02:00
copy(text) {
if (this.simpleCopy) {
2016-01-22 18:51:36 +01:00
Launcher.setClipboardText(text);
2017-01-31 07:50:28 +01:00
const clipboardSeconds = AppSettingsModel.instance.get('clipboardSeconds');
2016-01-22 18:51:36 +01:00
if (clipboardSeconds > 0) {
2017-11-26 20:44:53 +01:00
const clearClipboard = () => {
2016-01-22 18:51:36 +01:00
if (Launcher.getClipboardText() === text) {
Launcher.clearClipboardText();
}
2017-11-26 20:44:53 +01:00
};
Backbone.on('main-window-will-close', clearClipboard);
setTimeout(() => {
clearClipboard();
Backbone.off('main-window-will-close', clearClipboard);
2016-01-22 18:51:36 +01:00
}, clipboardSeconds * 1000);
}
2019-08-16 23:05:39 +02:00
return { success: true, seconds: clipboardSeconds };
2016-01-22 18:51:36 +01:00
} else {
try {
if (document.execCommand('copy')) {
2019-08-16 23:05:39 +02:00
return { success: true };
2016-01-22 18:51:36 +01:00
}
2019-08-16 23:05:39 +02:00
} catch (e) {}
2015-10-17 23:49:24 +02:00
return false;
}
},
2019-08-18 10:17:09 +02:00
createHiddenInput(text) {
2017-01-31 07:50:28 +01:00
const hiddenInput = $('<input/>')
2015-10-17 23:49:24 +02:00
.val(text)
.attr({ type: 'text', 'class': 'hide-by-pos' })
2015-10-27 22:57:56 +01:00
.appendTo(document.body);
hiddenInput[0].selectionStart = 0;
hiddenInput[0].selectionEnd = text.length;
2015-10-29 22:13:15 +01:00
hiddenInput.focus();
2015-10-17 23:49:24 +02:00
hiddenInput.on({
2019-08-18 10:17:09 +02:00
'copy cut paste'() {
2019-08-16 23:05:39 +02:00
setTimeout(() => hiddenInput.blur(), 0);
},
2019-08-18 10:17:09 +02:00
blur() {
2019-08-16 23:05:39 +02:00
hiddenInput.remove();
}
2015-10-17 23:49:24 +02:00
});
},
copyHtml(html) {
const el = document.createElement('div');
el.innerHTML = html;
document.body.appendChild(el);
const range = document.createRange();
range.selectNodeContents(el);
const sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
const result = document.execCommand('copy');
el.remove();
return result;
2015-10-17 23:49:24 +02:00
}
};
2019-09-15 14:16:32 +02:00
export { CopyPaste };