-
Notifications
You must be signed in to change notification settings - Fork 501
/
Copy pathCopyToClipboard.js
120 lines (100 loc) · 2.94 KB
/
CopyToClipboard.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
import React from 'react';
import JSONBig from 'json-bigint';
import { toType } from './../helpers/util';
//clibboard icon
import { Clippy } from './icons';
//theme
import Theme from './../themes/getStyle';
export default class extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
copied: false
};
}
copiedTimer = null;
componentWillUnmount() {
if (this.copiedTimer) {
clearTimeout(this.copiedTimer);
this.copiedTimer = null;
}
}
handleCopy = () => {
const container = document.createElement('textarea');
const { clickCallback, src, namespace } = this.props;
container.innerHTML = JSONBig.stringify(
this.clipboardValue(src),
null,
' '
);
document.body.appendChild(container);
container.select();
document.execCommand('copy');
document.body.removeChild(container);
this.copiedTimer = setTimeout(() => {
this.setState({
copied: false
});
}, 5500);
this.setState({ copied: true }, () => {
if (typeof clickCallback !== 'function') {
return;
}
clickCallback({
src: src,
namespace: namespace,
name: namespace[namespace.length - 1]
});
});
};
getClippyIcon = () => {
const { theme } = this.props;
if (this.state.copied) {
return (
<span>
<Clippy class="copy-icon" {...Theme(theme, 'copy-icon')} />
<span {...Theme(theme, 'copy-icon-copied')}>✔</span>
</span>
);
}
return <Clippy class="copy-icon" {...Theme(theme, 'copy-icon')} />;
};
clipboardValue = value => {
const type = toType(value);
switch (type) {
case 'function':
case 'regexp':
return value.toString();
default:
return value;
}
};
render() {
const { src, theme, hidden, rowHovered } = this.props;
let style = Theme(theme, 'copy-to-clipboard').style;
let display = 'inline';
if (hidden) {
display = 'none';
}
return (
<span
className="copy-to-clipboard-container"
title="Copy to clipboard"
style={{
verticalAlign: 'top',
display: rowHovered ? 'inline-block' : 'none'
}}
>
<span
style={{
...style,
display: display
}}
onClick={this.handleCopy}
>
{this.getClippyIcon()}
</span>
</span>
);
}
}