This repository was archived by the owner on May 15, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 99
Expand file tree
/
Copy pathcopy-button.jsx
More file actions
79 lines (74 loc) · 2.35 KB
/
copy-button.jsx
File metadata and controls
79 lines (74 loc) · 2.35 KB
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
77
78
79
const React = require("react");
/* Copy to clipboard button
* attach to input, textarea or any other "text container" (div, span, label..)
*/
const CopyButton = React.createClass({
propTypes: {
className: React.PropTypes.string,
defaultLabel: React.PropTypes.string,
didCopyLabel: React.PropTypes.string,
notSupportedLabel: React.PropTypes.string,
notSupportedLabelMac: React.PropTypes.string,
targetElement: React.PropTypes.func.isRequired,
},
getDefaultProps: function() {
return {
defaultLabel: "Copy",
didCopyLabel: "Copied",
notSupportedLabel: "Ctrl+C to copy",
notSupportedLabelMac: "⌘-C to copy",
};
},
getInitialState: function() {
return {text: this.props.defaultLabel};
},
_copy: function() {
const element = this.props.targetElement();
const selection = window.getSelection();
if (element.nodeName === 'INPUT' || element.nodeName === 'TEXTAREA') {
element.focus();
element.setSelectionRange(0, element.value.length);
} else {
const range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
}
const result = document.execCommand('copy');
this._handleResult(result, selection);
},
_handleResult: function(result, selection) {
let label;
if (!result) {
if (navigator.platform.indexOf("Mac") !== -1) {
label = this.props.notSupportedLabelMac;
} else {
label = this.props.notSupportedLabel;
}
} else {
label = this.props.didCopyLabel;
this.props.targetElement().blur();
selection.removeAllRanges();
}
this.setState({
text: label,
});
const _this = this;
setTimeout(function() {
_this.setState({
text: _this.props.defaultLabel,
});
}, 1000);
},
render: function() {
return (
<button
className={this.props.className}
onClick={this._copy}
>
{this.state.text}
</button>
);
},
});
module.exports = CopyButton;