import consoleWarn from '../console/warn';
/**
* @module clipboard
* @description Copies a string to the clipboard. Must be called from within an event handler such as click.
* May return false if it failed, but this is not always possible. Browser support for Chrome 43+,
* Firefox 42+, Safari 10+, Edge and Internet Explorer 10+.
*
* @since 1.0.0
*
* @param {string} text The text to copy to the clipboard.
*
* @return {boolean|*} Returns the methods applying the copy or false if it failed.
*
* @example
* import { clipboard } from "@gravityforms/utils";
*
* function Example() {
* const shortcode = `[gravityform id="${ this.options.data.form_id }" title="true"]`;
* clipboard( shortcode );
* }
*
*/
export default function clipboard( text = '' ) {
if ( window.clipboardData && window.clipboardData.setData ) {
// Internet Explorer-specific code path to prevent textarea being shown while dialog is visible.
return window.clipboardData.setData( 'Text', text );
} else if ( document.queryCommandSupported && document.queryCommandSupported( 'copy' ) ) {
const textarea = document.createElement( 'textarea' );
textarea.textContent = text;
textarea.style.position = 'fixed'; // Prevent scrolling to bottom of page in Microsoft Edge.
document.body.appendChild( textarea );
textarea.select();
try {
return document.execCommand( 'copy' ); // Security exception may be thrown by some browsers.
} catch ( ex ) {
consoleWarn( 'Copy to clipboard failed.', ex );
return false;
} finally {
document.body.removeChild( textarea );
}
}
}