User:SilentSpike/sortQualifiers.js

From Wikidata
Jump to navigation Jump to search

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)
  • Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
/**
 * Sorts statements on an item in the UI based on qualifiers:
 *   P1545
 *   P585 (WIP)
 *   P580 (WIP)
 */
(function(mw, $) {
	// Do nothing if not viewing an entity (Q, P or L)
	if ([0, 120, 146].indexOf(mw.config.get('wgNamespaceNumber')) === -1 ||
		!mw.config.exists('wbEntityId') ||
		!mw.config.get('wbIsEditView') ||
		!mw.config.get('wgIsProbablyEditable')
	) {
		return;
	}

	function getQualifierValue(claim, qual) {
		let quals = $(`.wikibase-statementview-qualifiers a[href$=${qual}]`, claim);

		// No value sorted to the top (allows multiple levels of sorting)
		// Multiple values sorted to the top (make problematic visible)
		if (quals.length != 1) {
			return Infinity;
		}

		// Must first ascend in DOM to drill back down to value
		let container = quals
			.parent()
			.parent()
			.parent();

		let value = $('.wikibase-snakview-value-container .wikibase-snakview-value', container);
		
		// Seems only sometimes the value has font elements within it?
		let fontValue = $('font > font', value);
		if (fontValue.length == 1) {
			value = fontValue;
		}

		return value.text();
	}

	function sortByQualifer(parent, qual) {
		let sorted = parent.children('div').sort((a,b) => {
			let vA = getQualifierValue(a, qual);
			let vB = getQualifierValue(b, qual);
			return (vA < vB) ? -1 : (vA > vB) ? 1 : 0;
		});

		parent.append(sorted);
	}
	
	// Only sort once the page has loaded
	window.addEventListener("load", function() {
		// Sort each set of claims individually
		$('.wikibase-statementlistview-listview').each(function() {
			// Sort the children
			sortByQualifer($(this), 'P1545');
		});
	});
}(mediaWiki, jQuery));