[Feature] Copy-to-clipboard button in View Query (#3571)

* added copy-to-clipboard button to explore/view query

* modified CopyToClipboard to deselect current before copying
This commit is contained in:
Jeff Niu 2017-10-03 22:34:40 -07:00 committed by Maxime Beauchemin
parent 40fbf1c761
commit 7e64f2e988
2 changed files with 28 additions and 4 deletions

View File

@ -52,6 +52,10 @@ export default class CopyToClipboard extends React.Component {
}
copyToClipboard(textToCopy) {
const selection = document.getSelection();
selection.removeAllRanges();
document.activeElement.blur();
const range = document.createRange();
const textArea = document.createElement('textarea');
textArea.style.position = 'fixed';
@ -59,7 +63,8 @@ export default class CopyToClipboard extends React.Component {
textArea.value = textToCopy;
document.body.appendChild(textArea);
textArea.select();
range.selectNode(textArea);
selection.addRange(range);
try {
if (!document.execCommand('copy')) {
throw new Error(t('Not successful'));
@ -69,6 +74,11 @@ export default class CopyToClipboard extends React.Component {
}
document.body.removeChild(textArea);
if (selection.removeRange) {
selection.removeRange(range);
} else {
selection.removeAllRanges();
}
this.setState({ hasCopied: true });
this.props.onCopyEnd();

View File

@ -4,8 +4,10 @@ import SyntaxHighlighter, { registerLanguage } from 'react-syntax-highlighter/di
import html from 'react-syntax-highlighter/dist/languages/htmlbars';
import markdown from 'react-syntax-highlighter/dist/languages/markdown';
import github from 'react-syntax-highlighter/dist/styles/github';
import CopyToClipboard from './../../components/CopyToClipboard';
import ModalTrigger from './../../components/ModalTrigger';
import Button from '../../components/Button';
import { t } from '../../locales';
registerLanguage('markdown', markdown);
@ -85,9 +87,21 @@ export default class DisplayQueryButton extends React.PureComponent {
return <pre>{this.state.error}</pre>;
} else if (this.state.query) {
return (
<SyntaxHighlighter language={this.state.language} style={github}>
{this.state.query}
</SyntaxHighlighter>);
<div>
<CopyToClipboard
text={this.state.query}
shouldShowText={false}
copyNode={
<Button style={{ position: 'absolute', right: 20 }}>
<i className="fa fa-clipboard" />
</Button>
}
/>
<SyntaxHighlighter language={this.state.language} style={github}>
{this.state.query}
</SyntaxHighlighter>
</div>
);
}
return null;
}