nope/resources/ui/helpers/clipboard.ts
2020-10-25 21:14:51 +01:00

85 lines
2.2 KiB
TypeScript

/**
* Function to Copy a String to the Clipboard
* @param input
*/
export function writeToClipboard(input: string){
const element = document.createElement('textarea');
const previouslyFocusedElement = document.activeElement as any;
element.value = input;
// Prevent keyboard from showing on mobile
element.setAttribute('readonly', '');
element.style.position = 'absolute';
element.style.left = '-9999px';
element.style.fontSize = '12pt'; // Prevent zooming on iOS
const selection = document.getSelection();
let originalRange: any = false;
if (selection.rangeCount > 0) {
originalRange = selection.getRangeAt(0);
}
document.body.append(element);
element.select();
// Explicit selection workaround for iOS
element.selectionStart = 0;
element.selectionEnd = input.length;
let isSuccess = false;
try {
isSuccess = document.execCommand('copy');
} catch (_) {}
element.remove();
if (originalRange) {
selection.removeAllRanges();
selection.addRange(originalRange);
}
// Get the focus back on the previously focused element, if any
if (previouslyFocusedElement) {
previouslyFocusedElement.focus();
}
return isSuccess;
}
/**
* Function to Read from Clipboard. Returns a String.
*/
export function readFromClipboard(){
const id = 'paster'+Date.now().toString();
const element = document.createElement('textarea');
const previouslyFocusedElement = document.activeElement as any;
// Prevent keyboard from showing on mobile
// element.setAttribute('readonly', '');
element.style.position = 'absolute';
element.style.left = '300px';
element.style.fontSize = '12pt'; // Prevent zooming on iOS
element.setAttribute('id', id);
document.body.append(element);
document.getElementById(id).focus();
(document.getElementById(id) as any).select();
document.execCommand('paste', true);
const text: string = element.textContent;
// Get the focus back on the previously focused element, if any
if (previouslyFocusedElement) {
previouslyFocusedElement.focus();
}
// Remove the Text
element.parentNode.removeChild(element);
return text;
}