|
| 1 | +import { makeStyles } from "@material-ui/core/styles" |
| 2 | +import Button from "@material-ui/core/Button" |
| 3 | +import Tooltip from "@material-ui/core/Tooltip" |
| 4 | +import Check from "@material-ui/icons/Check" |
| 5 | +import React, { useState } from "react" |
| 6 | +import { FileCopy } from "../Icons" |
| 7 | + |
| 8 | +interface CopyButtonProps { |
| 9 | + text: string |
| 10 | + className?: string |
| 11 | +} |
| 12 | + |
| 13 | +/** |
| 14 | + * Copy button used inside the CodeBlock component internally |
| 15 | + */ |
| 16 | +export const CopyButton: React.FC<CopyButtonProps> = ({ className = "", text }) => { |
| 17 | + const styles = useStyles() |
| 18 | + const [isCopied, setIsCopied] = useState<boolean>(false) |
| 19 | + |
| 20 | + const copyToClipboard = async (): Promise<void> => { |
| 21 | + try { |
| 22 | + await window.navigator.clipboard.writeText(text) |
| 23 | + setIsCopied(true) |
| 24 | + |
| 25 | + window.setTimeout(() => { |
| 26 | + setIsCopied(false) |
| 27 | + }, 1000) |
| 28 | + } catch (err) { |
| 29 | + const wrappedErr = new Error("copyToClipboard: failed to copy text to clipboard") |
| 30 | + if (err instanceof Error) { |
| 31 | + wrappedErr.stack = err.stack |
| 32 | + } |
| 33 | + console.error(wrappedErr) |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + return ( |
| 38 | + <Tooltip title="Copy to Clipboard" placement="top"> |
| 39 | + <div className={`${styles.copyButtonWrapper} ${className}`}> |
| 40 | + <Button className={styles.copyButton} onClick={copyToClipboard} size="small"> |
| 41 | + {isCopied ? <Check className={styles.fileCopyIcon} /> : <FileCopy className={styles.fileCopyIcon} />} |
| 42 | + </Button> |
| 43 | + </div> |
| 44 | + </Tooltip> |
| 45 | + ) |
| 46 | +} |
| 47 | + |
| 48 | +const useStyles = makeStyles((theme) => ({ |
| 49 | + copyButtonWrapper: { |
| 50 | + display: "flex", |
| 51 | + marginLeft: theme.spacing(1), |
| 52 | + }, |
| 53 | + copyButton: { |
| 54 | + borderRadius: 7, |
| 55 | + background: theme.palette.codeBlock.button.main, |
| 56 | + color: theme.palette.codeBlock.button.contrastText, |
| 57 | + padding: theme.spacing(0.85), |
| 58 | + minWidth: 32, |
| 59 | + |
| 60 | + "&:hover": { |
| 61 | + background: theme.palette.codeBlock.button.hover, |
| 62 | + }, |
| 63 | + }, |
| 64 | + fileCopyIcon: { |
| 65 | + width: 20, |
| 66 | + height: 20, |
| 67 | + }, |
| 68 | +})) |
0 commit comments