frontend/hooks/useShare.ts (view raw)
1import {useTranslation} from 'react-i18next';
2import useToastStore from '../stores/useToastStore';
3
4const navigatorHasShareCapability = typeof navigator !== 'undefined' && !!navigator.share;
5const navigatorHasClipboardCapability = typeof navigator !== 'undefined' && !!navigator.clipboard;
6
7
8const useShare = () => {
9 const {t} = useTranslation();
10 const addToast = useToastStore(s => s.addToast);
11
12 return {
13 navigatorHasShareCapability,
14 share: async ({url, title}) => {
15 if (!url || !title) return null;
16 // If navigator share capability
17 if (navigatorHasShareCapability)
18 return await navigator.share({
19 title,
20 url,
21 });
22 // Else copy URL in clipboard
23 else if (navigatorHasClipboardCapability) {
24 await navigator.clipboard.writeText(url);
25 addToast(t('event.actions.copied'));
26 return true;
27 }
28 addToast(t('event.actions.noShareCapability'));
29 },
30 };
31};
32
33export default useShare;