User:Nw520/StraightToCommons.js

From Meta, a Wikimedia project coordination wiki

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
/**
 * Replaces links to files on any Wikimedia-wiki to directly link to Wikimedia Commons saving you from having to wait for the on-wiki file page to load. Images and files hosted on Wikimedia Commons are highlighted with a green border to help distinguish between on-wiki files. Clicking on an image while holding down <kbd>Ctrl</kbd> copies the Common file name to your clipboard.
 **/
$.ready.then( function () {

	const strings = {
		'nw520-straighttocommons-copy-fail': {
			de: 'Dateiname konnte nicht in Zwischenablage kopiert werden.',
			en: 'Failed to copy file name to clipboard.'
		},
		'nw520-straighttocommons-copy-success': {
			de: 'Dateiname in Zwischenablage kopiert.',
			en: 'File name copied to clipboard.'
		}
	};

	function copyTextToClipboard( text ) {
		navigator.clipboard.writeText( text ).then( function () {
			mw.notify( mw.msg( 'nw520-straighttocommons-copy-success' ), {
				tag: 'straighttocommons',
				title: 'StraightToCommons',
				type: 'success'
			} );
		}, function () {
			mw.notify( mw.msg( 'nw520-straighttocommons-copy-fail' ), {
				tag: 'straighttocommons',
				title: 'StraightToCommons',
				type: 'error'
			} );
		} );
	}

	function main() {
		mw.util.addCSS( `a[href^="//commons.wikimedia.org/wiki/"] > img[src^="//upload.wikimedia.org/wikipedia/commons"] {
				border: solid 2px rgba(0,255,0,.4);
			}
			a[href^="//commons.wikimedia.org/wiki/"] > img[src^="//upload.wikimedia.org/wikipedia/commons"]:hover {
				border-color: rgba(0,255,0,1);
			}` );
	
		setupStrings();
		mw.hook( 'wikipage.content' ).add( function ( $content ) {
			$content.find( 'a[href] > img[src^="//upload.wikimedia.org/wikipedia/commons"]' ).each( function ( i, va ) {
				var href = $( va ).parent().attr( 'href' );
				if ( href.startsWith( '/wiki/' ) ) {
					var matches = href.match( /\/wiki\/(Bild|Datei|Fichier|File|Image):(.*)/ );
					if ( matches !== null ) {
						var filename = matches[ 2 ];
						$( va ).parent().attr( 'href', `//commons.wikimedia.org/wiki/File:${filename}` ).on( 'click', function ( e ) {
							if ( e.ctrlKey ) {
								e.preventDefault();
								copyTextToClipboard( decodeURIComponent( filename ).replace( /_/g, ' ' ) );
							}
						} );
					}
				}
			} );
		} );
	}

	function setupStrings() {
		const lang = mw.config.get( 'wgUserLanguage' );
		mw.messages.set( Object.fromEntries( Object.keys( strings ).map( function ( stringKey ) {
			return [ stringKey, strings[ stringKey ][ lang ] ?? strings[ stringKey ].en ];
		} ) ) );
	}

	main();
} );