From b206a58be1456920261999d9da589675d8c4f76d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=90=E6=B6=9B?= Date: Fri, 3 Jan 2025 17:21:40 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E4=B8=80=E4=B8=AA=E5=85=A8?= =?UTF-8?q?=E5=B1=80=E5=8F=AF=E7=94=A8=E7=9A=84=E5=A4=8D=E5=88=B6=E6=8C=87?= =?UTF-8?q?=E5=AE=9A=E9=A2=9C=E8=89=B2=E4=BB=A3=E7=A0=81=E5=88=B0=E5=89=AA?= =?UTF-8?q?=E8=B4=B4=E6=9D=BF=E7=9A=84Hook=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/hooks/useCopyColor.ts | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 src/hooks/useCopyColor.ts diff --git a/src/hooks/useCopyColor.ts b/src/hooks/useCopyColor.ts new file mode 100644 index 0000000..69c1e69 --- /dev/null +++ b/src/hooks/useCopyColor.ts @@ -0,0 +1,31 @@ +import { isNil } from 'lodash-es'; +import { useCallback, useEffect } from 'react'; +import { useCopyToClipboard } from 'react-use'; +import { NotificationType, useNotification } from '../components/Notifications'; + +export function useCopyColor() { + const { showToast } = useNotification(); + const [cpState, copyToClipboard] = useCopyToClipboard(); + const copyAction = useCallback((color: string) => { + if (color.startsWith('#')) { + copyToClipboard(color); + } else { + copyToClipboard(`#${color}`); + } + }, []); + + useEffect(() => { + if (!isNil(cpState.error)) { + showToast(NotificationType.ERROR, 'Failed to copy to clipboard', 'tabler:alert-circle', 3000); + } else if (!isNil(cpState.value)) { + showToast( + NotificationType.SUCCESS, + `${cpState.value} has been copied to clipboard.`, + 'tabler:circle-check', + 3000, + ); + } + }, [cpState]); + + return copyAction; +}