2024-06-28 22:42:04 +00:00
|
|
|
/**
|
|
|
|
* Initializes the share button functionality for Citizen
|
|
|
|
*
|
|
|
|
* @return {void}
|
|
|
|
*/
|
|
|
|
function init() {
|
|
|
|
if ( !mw.config.get( 'wgIsArticle' ) ) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2024-11-13 03:36:59 +00:00
|
|
|
const shareButton = document.getElementById( 'citizen-share' );
|
|
|
|
if ( !shareButton ) {
|
|
|
|
mw.log.error( '[Citizen] Unable to find share button (#shareButton not found)' );
|
2024-06-28 22:42:04 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
const canonicalLink = document.querySelector( 'link[rel="canonical"]' );
|
2024-11-13 03:26:03 +00:00
|
|
|
const url = canonicalLink ? canonicalLink.href : window.location.href;
|
2024-06-28 22:42:04 +00:00
|
|
|
const shareData = {
|
|
|
|
title: document.title,
|
2024-11-13 03:26:03 +00:00
|
|
|
url: url
|
2024-06-28 22:42:04 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
// eslint-disable-next-line es-x/no-async-functions
|
|
|
|
const handleShareButtonClick = async () => {
|
2024-11-13 03:36:59 +00:00
|
|
|
shareButton.disabled = true; // Disable the button
|
2024-06-28 22:42:04 +00:00
|
|
|
try {
|
2024-11-13 03:36:59 +00:00
|
|
|
if ( navigator.share ) {
|
2024-11-13 03:26:03 +00:00
|
|
|
await navigator.share( shareData );
|
2024-11-13 03:36:59 +00:00
|
|
|
} else if ( navigator.clipboard ) {
|
2024-11-13 03:26:03 +00:00
|
|
|
// Fallback to navigator.clipboard if Share API is not supported
|
|
|
|
await navigator.clipboard.writeText( url );
|
|
|
|
mw.notify( mw.msg( 'citizen-share-copied' ), {
|
|
|
|
tag: 'citizen-share',
|
|
|
|
type: 'success'
|
|
|
|
} );
|
|
|
|
}
|
2024-06-28 22:42:04 +00:00
|
|
|
} catch ( error ) {
|
|
|
|
mw.log.error( `[Citizen] ${ error }` );
|
|
|
|
} finally {
|
2024-11-13 03:36:59 +00:00
|
|
|
shareButton.disabled = false; // Re-enable button after error or share completes
|
2024-06-28 22:42:04 +00:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2024-11-13 03:36:59 +00:00
|
|
|
shareButton.addEventListener( 'click', mw.util.debounce( handleShareButtonClick, 100 ) );
|
2024-06-28 22:42:04 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
init: init
|
|
|
|
};
|