headplane/app/components/Code.tsx

52 lines
1.2 KiB
TypeScript
Raw Normal View History

import { useState, HTMLProps } from 'react';
2024-12-31 10:30:14 +05:30
import { CopyIcon, CheckIcon } from '@primer/octicons-react';
import { cn } from '~/utils/cn';
import { toast } from '~/components/Toaster';
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
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
);
}