nkbt / react-copy-to-clipboard

Copy-to-clipboard React component
MIT License
2.33k stars 123 forks source link

feat: add disabled prop #183

Closed cwjTerrace closed 2 years ago

cwjTerrace commented 2 years ago
function Text(props: TextProps) {
  const timeout = useRef<number>();
  const [success, setSuccess] = useState(false);
  const { children, copyable, ...rest } = props;

  const cleanCopyId = () => {
    clearTimeout(timeout.current!);
  };

  React.useEffect(() => cleanCopyId, []);

  if (copyable) {
    const { iconSize = 'small', ...copyPropsRest } = copyable as CopyProps;
    const copyProps = {
      ...copyPropsRest,
      text: copyPropsRest.text || String(children) || '',
    };

    const CopyIcon = (
      <Icon type={!success ? 'copy' : 'check'} size={iconSize} className={genClass('copy-icon')} />
    );

    return (
      <WrapperText {...rest}>
        {children}
        {success ? (
          CopyIcon
        ) : (
          <CopyToClipboard
            {...copyProps}
            onCopy={(text: string, result: boolean) => {
              if (result) {
                setSuccess(result);
                cleanCopyId();
                timeout.current = window.setTimeout(() => setSuccess(false), 3000);
              }
              copyProps.onCopy?.(text, result);
            }}
          >
            {CopyIcon}
          </CopyToClipboard>
        )}
      </WrapperText>
    );
  }

  return <WrapperText {...rest}>{children}</WrapperText>;
}
function Text(props: TextProps) {
  const timeout = useRef<number>();
  const [success, setSuccess] = useState(false);
  const { children, copyable, ...rest } = props;

  const cleanCopyId = () => {
    clearTimeout(timeout.current!);
  };

  React.useEffect(() => cleanCopyId, []);

  if (copyable) {
    const { iconSize = 'small', ...copyPropsRest } = copyable as CopyProps;
    const copyProps = {
      ...copyPropsRest,
      text: copyPropsRest.text || String(children) || '',
    };

    const CopyIcon = (
      <Icon type={!success ? 'copy' : 'check'} size={iconSize} className={genClass('copy-icon')} />
    );

    return (
      <WrapperText {...rest}>
        {children}
        <CopyToClipboard
          {...copyProps}
          disabled={success}
          onCopy={(text: string, result: boolean) => {
            if (result) {
              setSuccess(result);
              cleanCopyId();
              timeout.current = window.setTimeout(() => setSuccess(false), 3000);
            }
            copyProps.onCopy?.(text, result);
          }}
        >
          {CopyIcon}
        </CopyToClipboard>
      </WrapperText>
    );
  }

  return <WrapperText {...rest}>{children}</WrapperText>;
}