Skip to content

Commit

Permalink
Copy to clipboard: restore focus state and show 'copied' text
Browse files Browse the repository at this point in the history
  • Loading branch information
johnwatkins0 committed Oct 28, 2020
1 parent 0153b68 commit ddf5ec4
Showing 1 changed file with 32 additions and 3 deletions.
35 changes: 32 additions & 3 deletions assets/src/amp-validation/copy-to-clipboard-buttons.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,53 @@
*/
import Clipboard from 'clipboard';

/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n';

/**
* Internal dependencies
*/
import { getURLValidationTableRows } from './get-url-validation-table-rows';

/**
* Success handler, called when data is copied to the clipboard.
*
* @param {Object} event
* @param {HTMLElement} event.trigger The element triggering the event.
*/
function onSuccess( { trigger } ) {
trigger.focus();
const originalText = trigger.innerText;
trigger.innerText = __( 'Copied to clipboard', 'amp' );

setTimeout( () => {
if ( document.body.contains( trigger ) ) {
trigger.innerText = originalText;
}
}, 4000 );
}

/**
* Sets up the "Copy to clipboard" buttons on the URL validation screen.
*/
export function handleCopyToClipboardButtons() {
const clipboards = [];

// eslint-disable-next-line no-new
new Clipboard( 'button.single-url-detail-copy', {
clipboards.push( new Clipboard( 'button.single-url-detail-copy', {
text: ( btn ) => {
const json = JSON.parse( btn.getAttribute( 'data-error-json' ) );
const statusSelect = btn.closest( 'tr' ).querySelector( '.amp-validation-error-status' );
json.status = statusSelect.options[ statusSelect.selectedIndex ].text;

return JSON.stringify( json, null, '\t' );
},
} );
} ) );

// eslint-disable-next-line no-new
new Clipboard( 'button.copy-all', {
clipboards.push( new Clipboard( 'button.copy-all', {
text: () => {
const value = getURLValidationTableRows( { checkedOnly: true } ).map( ( row ) => {
const copyButton = row.querySelector( '.single-url-detail-copy' );
Expand All @@ -42,5 +67,9 @@ export function handleCopyToClipboardButtons() {

return JSON.stringify( value, null, '\t' );
},
} ) );

clipboards.forEach( ( clipboard ) => {
clipboard.on( 'success', onSuccess );
} );
}

0 comments on commit ddf5ec4

Please sign in to comment.