User:Valerio Bozzolan/cite-section.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.
/**
 * MediaWiki cite-section enhancement.
 *
 * Add a shortcut to cite a section.
 *
 * Screenshots:
 * * File:MediaWiki cite_section 1.png
 * * File:MediaWiki cite_section 2.png
 * 
 * Installation:
 * Copy here:
 * * meta:Special:MyPage/global.js
 * 
 * @license GNU AGPL v3+, CC BY-SA 3.0, CC BY-SA 4.0, GNU FDL (any of these, at your choice)
 * @author Valerio Bozzolan
 * @date 28 march 2017
 */

window.CITE_SECTION = {};

/**
 * Choose the behaviour without overloading the window.CITE_SECTION.cite()
 */
window.CITE_SECTION.SHORT = true;

/**
 * Maybe you hate hashtags.
 */
window.CITE_SECTION.PRE_SHORT = '#';

/**
 * Overload this to change the behaviour of the input text.
 */
window.CITE_SECTION.cite = function(h1text, htext) {
	var alias = window.CITE_SECTION.SHORT ? "|" + window.CITE_SECTION.PRE_SHORT + htext : '';
	return '[['
		+ h1text
		+ "#"
		+ htext
		+ alias
		+ ']]'
};

window.CITE_SECTION._bracket = function (html) {
	return $('<span class="mw-editsection-bracket">').clone().html(html);
};

window.CITE_SECTION._appendAction = function ($parent, name, action) {
	var $piero = $('<a href="#">').text(name).click(action);
	var $newbtn = $('<span class="mw-editsection">')
		.append( window.CITE_SECTION._bracket('[') )
		.append( $('<span class="pieroaction">').append($piero) )
		.append( window.CITE_SECTION._bracket(']') );
	$parent.append( $newbtn );
	return $piero;
};

window.CITE_SECTION.run = function () {
	var h1text = $('#firstHeading').text();
	var hash = '#';
	$('.mw-headline').each( function(i) {
		var htext = $(this).text();
		window.CITE_SECTION._appendAction( $(this).parent(), '#', function (event) {
			$(this).parent().html( $('<input type="text" readonly="readonly" />').val( window.CITE_SECTION.cite(h1text, htext) ) );
			event.preventDefault();
		})
	} );
};

window.CITE_SECTION.run();