( getLink?: () => string, shorten = false, )
| 29 | | ((props?: CopyNotifyFunctionProps) => Promise<void>); |
| 30 | |
| 31 | export function useCopyLink( |
| 32 | getLink?: () => string, |
| 33 | shorten = false, |
| 34 | ): [boolean, CopyNotifyFunction] { |
| 35 | const [copying, setCopying] = useState(false); |
| 36 | const { displayToast } = useToastNotification(); |
| 37 | const { getShortUrl } = useGetShortUrl(); |
| 38 | |
| 39 | const copy: CopyNotifyFunction = async (props = {}) => { |
| 40 | // getLink is optional: useCopyPostLink omits it when the link is only |
| 41 | // known at press time, and those callers pass it in props instead. |
| 42 | const link = props.link || getLink?.(); |
| 43 | const shortenLink = props.shorten || shorten; |
| 44 | const format = props.format || ((value: string) => value); |
| 45 | |
| 46 | if (link) { |
| 47 | try { |
| 48 | // write the link to clipboard |
| 49 | await navigator.clipboard.writeText(format(link)); |
| 50 | } catch { |
| 51 | displayToast(blockedMessage, { variant: ToastType.Error }); |
| 52 | |
| 53 | return; |
| 54 | } |
| 55 | |
| 56 | // try with a shortened link as well, if requested |
| 57 | if (shortenLink) { |
| 58 | try { |
| 59 | const clipBoardItem = new ClipboardItem({ |
| 60 | // A promise, not an awaited value: awaiting the shortener first |
| 61 | // would end the task that handled the gesture, and Safari refuses |
| 62 | // the write after that. |
| 63 | 'text/plain': getShortUrl(link, props.cid).then((shortenedLink) => { |
| 64 | return new Blob([format(shortenedLink)], { type: 'text/plain' }); |
| 65 | }), |
| 66 | }); |
| 67 | await navigator.clipboard.write([clipBoardItem]); |
| 68 | } catch (e) { |
| 69 | // eslint-disable-next-line no-console |
| 70 | console.warn('Error copying to clipboard', e); |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | if (!props.disableToast) { |
| 75 | displayToast(props.message || defaultLinkMessage, props); |
| 76 | } |
| 77 | } else { |
| 78 | displayToast(noLinkErrorMessage, { variant: ToastType.Error }); |
| 79 | |
| 80 | return; |
| 81 | } |
| 82 | |
| 83 | setCopying(true); |
| 84 | setTimeout(() => { |
| 85 | setCopying(false); |
| 86 | }, 1000); |
| 87 | }; |
| 88 |
no test coverage detected