headplane/app/components/Code.tsx

53 lines
1.2 KiB
TypeScript
Raw Normal View History

2025-01-28 16:04:42 -05:00
import { CheckIcon, CopyIcon } from '@primer/octicons-react';
import { HTMLProps, useState } from 'react';
2025-01-28 17:46:16 -05:00
import cn from '~/utils/cn';
2025-01-28 16:04:42 -05:00
import toast from '~/utils/toast';
2024-11-20 18:01:20 -05:00
interface Props extends HTMLProps<HTMLSpanElement> {
2024-12-31 10:30:14 +05:30
isCopyable?: boolean;
2024-11-20 18:01:20 -05:00
}
export default function Code(props: Props) {
2024-12-31 10:30:14 +05:30
const [isCopied, setIsCopied] = useState(false);
2024-03-29 16:14:35 -04:00
return (
2024-11-20 18:01:20 -05:00
<>
2024-12-31 10:30:14 +05:30
<code
className={cn(
'bg-ui-100 dark:bg-ui-800 p-0.5 rounded-md',
props.className,
)}
>
2024-11-20 18:01:20 -05:00
{props.children}
</code>
{props.isCopyable ? (
2024-11-20 18:01:20 -05:00
<button
2025-01-28 16:04:42 -05:00
type="button"
2024-11-20 18:01:20 -05:00
className={cn(
'ml-1 p-1 rounded-md',
'bg-ui-100 dark:bg-ui-800',
'text-ui-500 dark:text-ui-400',
2024-12-31 10:30:14 +05:30
'inline-flex items-center justify-center',
2024-11-20 18:01:20 -05:00
)}
onClick={() => {
if (!props.children) {
throw new Error('Made copyable without children');
}
2024-12-31 10:30:14 +05:30
navigator.clipboard.writeText(props.children.join(''));
toast('Copied to clipboard');
setIsCopied(true);
setTimeout(() => setIsCopied(false), 1000);
2024-11-20 18:01:20 -05:00
}}
>
2024-12-31 10:30:14 +05:30
{isCopied ? (
<CheckIcon className="h-3 w-3" />
) : (
2024-11-20 18:01:20 -05:00
<CopyIcon className="h-3 w-3" />
2024-12-31 10:30:14 +05:30
)}
2024-11-20 18:01:20 -05:00
</button>
2024-12-31 10:30:14 +05:30
) : undefined}
2024-11-20 18:01:20 -05:00
</>
2024-12-31 10:30:14 +05:30
);
}