User:ESanders (WMF)/commentlinks-v1.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.
/**
 * Adds a [ link ] button after the [ reply ] button to comments
 * which copies a hash link to that specific comment to the clipboard.
 */
mw.hook( 'wikipage.content' ).add( function ( $container ) {
	var canonicalUrl = $( 'link[rel=canonical]' ).attr( 'href' ) || '';
	$container.find( '.ext-discussiontools-init-replylink-reply' ).each( function () {
		var $buttons = $( this ).closest( '.ext-discussiontools-init-replylink-buttons' );
		var threadId = $buttons.data( 'mw-thread-id' );
		var $link = $( '<a>' ).attr( 'href', canonicalUrl + '#' + threadId ).text( 'link' )
			.on( 'click', function () {
				var $win = $( window );
				var scrollTop = $win.scrollTop();
				var $tmpInput = $( '<input>' )
					.val( this.href )
					.addClass( 'noime' )
					.css( {
						position: 'fixed',
						top: 0
					} )
					.appendTo( 'body' )
					.trigger( 'focus' );
				$tmpInput[ 0 ].setSelectionRange( 0, this.href.length );
				var copied;
				try {
					copied = document.execCommand( 'copy' );
				} catch ( e ) {
					copied = false;
				}
				if ( copied ) {
					mw.notify( 'Link to comment copied to clipboard.' );
				}
				$tmpInput.remove();
				// Restore scroll position
				requestAnimationFrame( function () {
					$win.scrollTop( scrollTop );
				} );
			} );
		$buttons.after(
			$( '<span>' )
				.addClass( 'ext-discussiontools-init-replylink-buttons' )
				.append(
					$( '<span>' ).addClass( 'ext-discussiontools-init-replylink-bracket' ).text( '[' ),
					$link.addClass( 'ext-discussiontools-init-replylink-reply' ).css( {
						// Reset CSS to prevent links being disabled when reply tool is open
						color: '#0645ad',
						'pointer-events': 'all'
					} ),
					$( '<span>' ).addClass( 'ext-discussiontools-init-replylink-bracket' ).text( ']' )
				)
				// Force visible as reply links may be hidden on the wiki
				.css( 'display', 'inline' )
		);
	} );
} );