All files / src/components/elements/CopyToClipboard CopyToClipboard.tsx

0% Statements 0/20
0% Branches 0/14
0% Functions 0/7
0% Lines 0/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                                                                                                 
import * as React from "react";
import styled from "styled-components";
import { ContentCopy, Check } from "@rimble/icons";
import { Box, Button, Flex } from "rimble-ui";
import { baseColors, colors } from "../../../themes";
import { copyToClipboard } from "../../../utils";
 
interface ContentCopyStyledProps {
  hoverColor?: string;
}
 
const ContentCopyStyled = styled.span`
  cursor: pointer;
  &:hover svg {
    fill: ${(props: ContentCopyStyledProps) => (props.hoverColor ? props.hoverColor : colors.primary.base)};
    transition: 250ms ease;
  }
`;
 
export interface CopyToClipboardProps {
  text: string;
  color?: string;
  iconPadding?: string | number;
  hoverColor?: string;
  hoverTitle?: string;
  size?: string;
  textButton?: boolean;
  textButtonTitle?: string;
  buttonOverride?(copied: boolean): JSX.Element;
}
 
export const CopyToClipboard: React.FunctionComponent<CopyToClipboardProps> = (props) => {
  const [copied, setCopied] = React.useState(false);
 
  React.useEffect(() => {
    if (copied) {
      setTimeout(() => {
        setCopied(false);
      }, 2500);
    }
  }, [copied]);
 
  if (props.buttonOverride) {
    return <span onClick={() => setCopied(copyToClipboard(props.text))}>{props.buttonOverride(copied)}</span>;
  }
 
  if (copied) {
    if (props.textButton) {
      return <Button.Outline size="small">Copied</Button.Outline>;
    }
    return <Check color={colors.success.base} size={props.size} />;
  }
 
  if (props.textButton) {
    return (
      <Button.Outline
        color={props.color}
        onClick={() => setCopied(copyToClipboard(props.text))}
        size="small"
        style={{ backgroundColor: baseColors.white }}
      >
        <Flex alignItems="center" justifyContent="center">
          <ContentCopy size="16px" style={{ marginRight: "4px" }} />
          {props.textButtonTitle || "Copy"}
        </Flex>
      </Button.Outline>
    );
  }
  return (
    <ContentCopyStyled
      hoverColor={props.hoverColor}
      onClick={() => setCopied(copyToClipboard(props.text))}
      title={props.hoverTitle}
    >
      <Box p={props.iconPadding}>
        <ContentCopy color={props.color} size={props.size} />
      </Box>
    </ContentCopyStyled>
  );
};