1
0
mirror of https://github.com/lensapp/lens.git synced 2025-05-20 05:10:56 +00:00
lens/dashboard/client/utils/copyToClipboard.ts
Jari Kolehmainen 1d0815abd2
Lens app source code (#119)
Signed-off-by: Jari Kolehmainen <jari.kolehmainen@gmail.com>
2020-03-15 09:52:02 +02:00

22 lines
681 B
TypeScript

// Helper for selecting element's text content and copy in clipboard
export function copyToClipboard(elem: HTMLElement, resetSelection = true): boolean {
let clearSelection: () => void;
if (isSelectable(elem)) {
elem.select();
clearSelection = () => elem.setSelectionRange(0, 0)
}
else {
const selection = window.getSelection();
selection.selectAllChildren(elem);
clearSelection = () => selection.removeAllRanges();
}
const copyResult = document.execCommand("copy");
if (resetSelection) clearSelection();
return copyResult;
}
function isSelectable(elem: HTMLElement): elem is HTMLInputElement {
return !!(elem as HTMLInputElement).select;
}