1.7 KB66 lines
Blame
1/**
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
8import {Icon} from 'isl-components/Icon';
9import {Tooltip} from 'isl-components/Tooltip';
10import {useEffect, useState} from 'react';
11import {T} from './i18n';
12import platform from './platform';
13
14import './Copyable.css';
15
16/** Click to copy text and show a confirmation tooltip. If content is provided, use that instead of */
17export function Copyable({
18 children,
19 className,
20 iconOnly,
21}: {
22 children: string;
23 className?: string;
24 iconOnly?: boolean;
25}) {
26 const [showingSuccess, setShowingSuccess] = useState(false);
27 useEffect(() => {
28 if (showingSuccess) {
29 const timeout = setTimeout(() => setShowingSuccess(false), 1500);
30 return () => clearTimeout(timeout);
31 }
32 }, [showingSuccess, setShowingSuccess]);
33
34 return (
35 <Tooltip
36 trigger="manual"
37 shouldShow={showingSuccess}
38 component={CopiedSuccessTooltipContent(children)}>
39 <div
40 className={
41 'copyable' + (className ? ` ${className}` : '') + (iconOnly === true ? ' icon-only' : '')
42 }
43 tabIndex={0}
44 onClick={e => {
45 platform.clipboardCopy(children);
46 setShowingSuccess(true);
47 e.preventDefault();
48 e.stopPropagation();
49 }}>
50 {iconOnly !== true && children}
51 <Icon icon="copy" />
52 </div>
53 </Tooltip>
54 );
55}
56
57function CopiedSuccessTooltipContent(text: string) {
58 return () => (
59 <span className="copyable-success-tooltip">
60 <T replace={{$copiedText: <span className="copyable-success-overflow">{text}</span>}}>
61 Copied '$copiedText'.
62 </T>
63 </span>
64 );
65}
66