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; +}