forked from 10up/block-components
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
63 lines (53 loc) · 1.32 KB
/
index.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
import PropTypes from 'prop-types';
import { useCopyToClipboard } from '@wordpress/compose';
import { useState, useEffect } from '@wordpress/element';
import { Button } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
export const ClipboardButton = (props) => {
const { text, disabled, onSuccess, labels } = props;
const [hasCopied, setHasCopied] = useState(false);
const copy = labels.copy ? labels.copy : __('Copy');
const copied = labels.copied ? labels.copied : __('Copied');
useEffect(() => {
let timerId;
if (hasCopied) {
timerId = setTimeout(() => {
setHasCopied(false);
}, 3000);
}
return () => {
if (timerId) {
clearTimeout(timerId);
}
};
}, [hasCopied]);
function successfullyCopied() {
/**
* The 'copied' label stays for 3 seconds.
* We don't want to save again within the same time frame.
*/
if (hasCopied) {
return;
}
onSuccess();
setHasCopied(true);
}
const ref = useCopyToClipboard(text, successfullyCopied);
return (
<Button disabled={disabled} ref={ref}>
{hasCopied ? copied : copy}
</Button>
);
};
ClipboardButton.defaultProps = {
text: '',
disabled: false,
onSuccess: () => {},
labels: {},
};
ClipboardButton.propTypes = {
text: PropTypes.string,
disabled: PropTypes.bool,
onSuccess: PropTypes.func,
labels: PropTypes.object,
};