Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

2.2 KB
Raw Blame
import { CSSProperties, type MouseEvent, useCallback } from 'react';
import { Check, Copy } from '@signozhq/icons';
import { Button } from '@signozhq/ui/button';
import cx from 'classnames';

import styles from './CopyButton.module.scss';
import { useCopyButton } from './useCopyButton';
import { Tooltip } from '@signozhq/ui/tooltip';

export interface CopyButtonProps {
	/** Text written to the clipboard on click. */
	value: string;
	/** Icon size in px. Default 14. */
	size?: number;
	/** Accessible label for the idle (not-yet-copied) state. Default "Copy". */
	ariaLabel?: string;
	testId?: string;
	/** Called after the copy is triggered (e.g. to show a toast). */
	onCopy?: () => void;
	/** Side on which the tooltip should appear. Default "right". */
	tooltipSide?: 'top' | 'right' | 'bottom' | 'left';
}

/**
 * Square, icon-only copy button. Shows a copy icon that cross-fades to a
 * checkmark (blur + rotate + fade) on copy, reverting after 2s. The checkmark
 * uses the hover-state icon colour.
 */
function CopyButton({
	value,
	size = 14,
	ariaLabel = 'Copy',
	testId,
	onCopy,
	tooltipSide = 'top',
}: CopyButtonProps): JSX.Element {
	const { copyToClipboard, isCopied } = useCopyButton();

	const handleClick = useCallback(
		(e: MouseEvent<HTMLButtonElement>): void => {
			e.stopPropagation();
			copyToClipboard(value);
			onCopy?.();
		},
		[copyToClipboard, value, onCopy],
	);

	const stackStyle: CSSProperties = { width: size, height: size };

	return (
		// TODO: remove wrapper once Button supports tooltip
		<Tooltip title={isCopied ? 'Copied' : ariaLabel} side={tooltipSide}>
			<Button
				variant="ghost"
				color="secondary"
				size="sm"
				icon
				onClick={handleClick}
				aria-label={isCopied ? 'Copied' : ariaLabel}
				testId={testId}
			>
				<span
					className={styles.iconStack}
					style={stackStyle}
					data-copied={isCopied}
				>
					<Copy size={size} className={cx(styles.icon, styles.copyIcon)} />
					<Check size={size} className={cx(styles.icon, styles.checkIcon)} />
				</span>
			</Button>
		</Tooltip>
	);
}

CopyButton.defaultProps = {
	size: 14,
	ariaLabel: 'Copy',
	testId: undefined,
	onCopy: undefined,
};

export default CopyButton;