( getLink?: () => string, shorten = false, )
| 20 | | ((props?: CopyNotifyFunctionProps) => Promise<void>); |
| 21 | |
| 22 | export function useCopyLink( |
| 23 | getLink?: () => string, |
| 24 | shorten = false, |
| 25 | ): [boolean, CopyNotifyFunction] { |
| 26 | const [copying, setCopying] = useState(false); |
| 27 | const { displayToast } = useToastNotification(); |
| 28 | const { getShortUrl } = useGetShortUrl(); |
| 29 | |
| 30 | const copy: CopyNotifyFunction = async (props = {}) => { |
| 31 | const link = props.link || getLink(); |
| 32 | const shortenLink = props.shorten || shorten; |
| 33 | |
| 34 | if (link) { |
| 35 | // write the link to clipboard |
| 36 | await navigator.clipboard.writeText(link); |
| 37 | |
| 38 | // try with a shortened link as well, if requested |
| 39 | if (shortenLink) { |
| 40 | try { |
| 41 | const clipBoardItem = new ClipboardItem({ |
| 42 | 'text/plain': getShortUrl(link).then((shortenedLink) => { |
| 43 | return new Blob([shortenedLink], { type: 'text/plain' }); |
| 44 | }), |
| 45 | }); |
| 46 | await navigator.clipboard.write([clipBoardItem]); |
| 47 | } catch (e) { |
| 48 | // eslint-disable-next-line no-console |
| 49 | console.warn('Error copying to clipboard', e); |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | if (!props.disableToast) { |
| 54 | displayToast(props.message || defaultLinkMessage, props); |
| 55 | } |
| 56 | } else { |
| 57 | displayToast(noLinkErrorMessage, props); |
| 58 | } |
| 59 | |
| 60 | setCopying(true); |
| 61 | setTimeout(() => { |
| 62 | setCopying(false); |
| 63 | }, 1000); |
| 64 | }; |
| 65 | |
| 66 | return [copying, copy]; |
| 67 | } |
| 68 | |
| 69 | export function useCopyText(text?: string): [boolean, CopyNotifyFunction] { |
| 70 | const [copying, setCopying] = useState(false); |
no test coverage detected