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.

1.3 KB
Raw Blame
import React, { useState } from 'react';
import { Check, Copy } from '@signozhq/icons';
import cx from 'classnames';

import './CodeCopyBtn.scss';

function CodeCopyBtn({
	children,
	onCopyClick,
}: {
	children: React.ReactNode;
	onCopyClick?: (additionalInfo?: Record<string, unknown>) => void;
}): JSX.Element {
	const [isSnippetCopied, setIsSnippetCopied] = useState(false);

	const handleClick = (): void => {
		let copiedText = '';
		if (children && Array.isArray(children)) {
			setIsSnippetCopied(true);
			// oxlint-disable-next-line signoz/no-navigator-clipboard
			navigator.clipboard.writeText(children[0].props.children[0]).finally(() => {
				copiedText = (children[0].props.children[0] as string).slice(0, 200); // slicing is done due to the limitation in accepted char length in attributes
				setTimeout(() => {
					setIsSnippetCopied(false);
				}, 1000);
			});
			copiedText = (children[0].props.children[0] as string).slice(0, 200);
		}

		onCopyClick?.({ copiedText });
	};

	return (
		<div className={cx('code-copy-btn', isSnippetCopied ? 'copied' : '')}>
			<button type="button" onClick={handleClick}>
				{!isSnippetCopied ? <Copy size="md" /> : <Check size="md" />}
			</button>
		</div>
	);
}

CodeCopyBtn.defaultProps = {
	onCopyClick: (): void => {},
};

export default CodeCopyBtn;