UNPKG

@helpscout/hsds-react

Version:

React component library for Help Scout's Design System

63 lines (49 loc) 1.53 kB
"use strict"; exports.__esModule = true; exports.selectText = exports.copyToClipboard = void 0; /* istanbul ignore file */ // Excluding most of the branches in these functions from test coverage. // Reason is because interactions are difficult to mock or are not supported // by JSDOM. /** * Copies the selected content to user's clipboard. */ var copyToClipboard = function copyToClipboard() { if (document && document.execCommand) { document.execCommand('copy'); } }; /** * Selects text content within an HTMLElement * * @param { HTMLElement } element The targeted HTMLElement * @returns { string } The selected text */ exports.copyToClipboard = copyToClipboard; var selectText = function selectText(element) { var selectedText; if (element.nodeName === 'INPUT' || element.nodeName === 'TEXTAREA') { var isReadOnly = element.hasAttribute('readonly'); if (!isReadOnly) { element.setAttribute('readonly', ''); } element.select(); element.setSelectionRange(0, element.value.length); if (!isReadOnly) { element.removeAttribute('readonly'); } selectedText = element.value; } else { if (element.hasAttribute('contenteditable')) { element.focus(); } var selection = window.getSelection(); var range = document.createRange(); range.selectNodeContents(element); selection.removeAllRanges(); selection.addRange(range); selectedText = selection.toString(); } return selectedText || ''; }; exports.selectText = selectText;