From 25361c847b32f248fd65114a94e39d11a5f98590 Mon Sep 17 00:00:00 2001 From: Ethan Liu Date: Wed, 21 Jun 2023 12:20:49 +0800 Subject: [PATCH] fix: Reduce ineffective triggering of the clipboard --- components/chat-message-actions.tsx | 11 ++++++----- components/ui/codeblock.tsx | 7 ++++++- lib/hooks/use-copy-to-clipboard.tsx | 10 +++++----- 3 files changed, 17 insertions(+), 11 deletions(-) diff --git a/components/chat-message-actions.tsx b/components/chat-message-actions.tsx index 2905f8a..d4e4b40 100644 --- a/components/chat-message-actions.tsx +++ b/components/chat-message-actions.tsx @@ -18,6 +18,11 @@ export function ChatMessageActions({ }: ChatMessageActionsProps) { const { isCopied, copyToClipboard } = useCopyToClipboard({ timeout: 2000 }) + const onCopy = () => { + if (isCopied) return + copyToClipboard(message.content) + } + return (
- diff --git a/components/ui/codeblock.tsx b/components/ui/codeblock.tsx index 438c42c..aabda4e 100644 --- a/components/ui/codeblock.tsx +++ b/components/ui/codeblock.tsx @@ -84,6 +84,11 @@ const CodeBlock: FC = memo(({ language, value }) => { URL.revokeObjectURL(url) } + const onCopy = () => { + if (isCopied) return + copyToClipboard(value) + } + return (
@@ -102,7 +107,7 @@ const CodeBlock: FC = memo(({ language, value }) => { variant="ghost" size="icon" className="text-xs hover:bg-zinc-800 focus-visible:ring-1 focus-visible:ring-slate-700 focus-visible:ring-offset-0" - onClick={() => copyToClipboard(value)} + onClick={onCopy} > {isCopied ? : } Copy code diff --git a/lib/hooks/use-copy-to-clipboard.tsx b/lib/hooks/use-copy-to-clipboard.tsx index 9f9b8e3..62f7156 100644 --- a/lib/hooks/use-copy-to-clipboard.tsx +++ b/lib/hooks/use-copy-to-clipboard.tsx @@ -12,11 +12,11 @@ export function useCopyToClipboard({ const [isCopied, setIsCopied] = React.useState(false) const copyToClipboard = (value: string) => { - if ( - typeof window === 'undefined' || - !navigator.clipboard || - !navigator.clipboard.writeText - ) { + if (typeof window === 'undefined' || !navigator.clipboard?.writeText) { + return + } + + if (!value) { return }