-
Notifications
You must be signed in to change notification settings - Fork 382
/
Copy pathcopy-to-clipboard-buttons.js
76 lines (63 loc) · 1.85 KB
/
copy-to-clipboard-buttons.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/**
* External dependencies
*/
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 newInnerText = __( 'Copied to clipboard', 'amp' );
// Exit if the user has already clicked the button and we are still within the
// 4000ms before the setTimeout callback runs.
if ( trigger.innerText === newInnerText ) {
return;
}
const originalText = trigger.innerText;
trigger.innerText = newInnerText;
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
clipboards.push( new Clipboard( 'button.single-url-detail-copy', {
text: ( btn ) => {
return JSON.stringify( JSON.parse( btn.getAttribute( 'data-error-json' ) ), null, '\t' );
},
} ) );
// eslint-disable-next-line no-new
clipboards.push( new Clipboard( 'button.copy-all', {
text: () => {
const value = getURLValidationTableRows( { checkedOnly: true } ).map( ( row ) => {
const copyButton = row.querySelector( '.single-url-detail-copy' );
if ( ! copyButton ) {
return null;
}
return JSON.parse( copyButton.getAttribute( 'data-error-json' ) );
} )
.filter( ( item ) => item );
return JSON.stringify( value, null, '\t' );
},
} ) );
clipboards.forEach( ( clipboard ) => {
clipboard.on( 'success', onSuccess );
} );
}