2024-07-03 23:32:55 +02:00
|
|
|
// Copyright 2024, Command Line Inc.
|
|
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
|
|
|
|
import { clsx } from "clsx";
|
2024-09-09 20:56:21 +02:00
|
|
|
import { useEffect, useRef, useState } from "react";
|
2024-07-03 23:32:55 +02:00
|
|
|
import { Button } from "./button";
|
|
|
|
import "./copybutton.less";
|
|
|
|
|
|
|
|
type CopyButtonProps = {
|
|
|
|
title: string;
|
|
|
|
className?: string;
|
|
|
|
onClick: (e: React.MouseEvent<HTMLButtonElement>) => void;
|
|
|
|
};
|
|
|
|
|
|
|
|
const CopyButton = ({ title, className, onClick }: CopyButtonProps) => {
|
2024-09-09 20:56:21 +02:00
|
|
|
const [isCopied, setIsCopied] = useState(false);
|
|
|
|
const timeoutRef = useRef<NodeJS.Timeout | null>(null);
|
2024-07-03 23:32:55 +02:00
|
|
|
|
|
|
|
const handleOnClick = (e: React.MouseEvent<HTMLButtonElement>) => {
|
|
|
|
if (isCopied) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
setIsCopied(true);
|
|
|
|
if (timeoutRef.current) {
|
|
|
|
clearTimeout(timeoutRef.current);
|
|
|
|
}
|
|
|
|
timeoutRef.current = setTimeout(() => {
|
|
|
|
setIsCopied(false);
|
|
|
|
timeoutRef.current = null;
|
|
|
|
}, 2000);
|
|
|
|
|
|
|
|
if (onClick) {
|
|
|
|
onClick(e);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2024-09-09 20:56:21 +02:00
|
|
|
useEffect(() => {
|
2024-07-03 23:32:55 +02:00
|
|
|
return () => {
|
|
|
|
if (timeoutRef.current) {
|
|
|
|
clearTimeout(timeoutRef.current);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
return (
|
2024-09-09 20:56:21 +02:00
|
|
|
<Button
|
|
|
|
onClick={handleOnClick}
|
|
|
|
className={clsx("copy-button secondary ghost", className, { copied: isCopied })}
|
|
|
|
title={title}
|
|
|
|
>
|
2024-07-03 23:32:55 +02:00
|
|
|
{isCopied ? <i className="fa-sharp fa-solid fa-check"></i> : <i className="fa-sharp fa-solid fa-copy"></i>}
|
|
|
|
</Button>
|
|
|
|
);
|
|
|
|
};
|
|
|
|
|
|
|
|
export { CopyButton };
|