import { useState, useEffect } from 'react';
// https://github.com/agneym/react-use-web-share/blob/master/src/
/**
* Get the URL to be shared.
* If the site uses canonical URL, then use that URL otherwise the current URL
* @param url URL that might be passed on by the user
*/
function getUrl(url) {
if (!!url) {
return url;
} else {
const canonicalEl = document.querySelector('link[rel=canonical]');
return canonicalEl ? canonicalEl.href : window.location.href;
}
}
/**
* Trigger native share popup
*/
function shareContent(onSuccess, onError) {
return function (config) {
const url = getUrl(config.url);
const title = config.title || document.title;
const text = config.text;
navigator.share({ text, title, url }).then(onSuccess).catch(onError);
};
}
export default function useNavigatorShare(onSuccess = () => {}, onError = () => {}) {
const [loading, setLoading] = useState(true);
const [isSupported, setSupport] = useState(false);
useEffect(() => {
if (!!navigator.share) {
setSupport(true);
} else {
setSupport(false);
}
setLoading(false);
}, [onSuccess, onError]);
return {
loading,
isSupported,
share: shareContent(onSuccess, onError)
};
}