21700: Install Bundler system-wide in Rails postinst
[arvados.git] / services / workbench2 / src / components / copy-to-clipboard / copy-result-to-clipboard.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import React from 'react';
6 import { ReactElementLike } from 'prop-types';
7 import copy from 'copy-to-clipboard';
8
9 interface CopyToClipboardProps {
10   getText: (() => string);
11   children: ReactElementLike;
12   onCopy?(text: string, result: boolean): void;
13   options?: {
14     debug?: boolean;
15     message?: string;
16     format?: string; // MIME type
17   };
18 }
19
20 export default class CopyResultToClipboard extends React.PureComponent<CopyToClipboardProps> {
21   static defaultProps = {
22     onCopy: undefined,
23     options: undefined
24   };
25
26   onClick = event => {
27     const {
28       getText,
29       onCopy,
30       children,
31       options
32     } = this.props;
33
34     const elem = React.Children.only(children);
35
36     const text = getText();
37
38     const result = copy(text, options);
39
40     if (onCopy) {
41       onCopy(text, result);
42     }
43
44     // Bypass onClick if it was present
45     if (elem && elem.props && typeof elem.props.onClick === 'function') {
46       elem.props.onClick(event);
47     }
48   };
49
50
51   render() {
52     const {
53       getText: _getText,
54       onCopy: _onCopy,
55       options: _options,
56       children,
57       ...props
58     } = this.props;
59     const elem = React.Children.only(children);
60
61     return React.cloneElement(elem, {...props, onClick: this.onClick});
62   }
63 }