User:Nikki/StatementCounts.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.
/* This script runs on category pages and adds the number of statements that
   each page in the category has on Wikidata after the link to that page.
   Links for pages with fewer than 5 statements are highlighted to make it
   easier to see which pages' items are most likely to need improvement.

   To use it, add the following line to your global.js on Meta-Wiki if you want
   it to work on all wikis, or to your common.js on a specific wiki if you only
   want to use it on that wiki:
   mw.loader.load("//meta.wikimedia.org/w/index.php?title=User:Nikki/StatementCounts.js&action=raw&ctype=text/javascript");

   License: CC0
   
   There are some alternative implementations of this feature by other people:
   * [[User:Lucas Werkmeister/addStatementCountsToCategories.js]]
   * [[User:CamelCaseNick/statementCountsInCategories.js]]
*/
$(document).ready(function () {
(function () {
	if (mw.config.get("wgCanonicalNamespace") !== "Category")
		return;

	var lang = mw.config.get("wgContentLanguage");
	var domain = mw.config.get("wgServerName");

	var pages = [];

	$(".ns-14 #mw-pages li a, .ns-14 #mw-subcategories li a").each(function (i, v) {
		var page = '"' + v.title.replace(/"/g, '\\\"') + '"@' + lang;
		pages.push(page);
	});
	
	if (!pages.length)
		return;

	var query = "\
		select * {\
			values ?page { " + pages.join(" ") + " }\
			?sitelink schema:name ?page;\
				schema:isPartOf <https://" + domain + "/>;\
				schema:about ?item.\
			?item wikibase:statements ?st.\
		}";

	$.post("https://query.wikidata.org/sparql?format=json", { query: query }, function (data) {
		$.each(data.results.bindings, function (i, v) {
			var qid = v.item.value.replace(/.*\//, "");
			var colour = "";
			if (v.st.value < 5)
				colour = " style='color: " + (v.st.value === "0" ? "#d33" : "chocolate") + "'";
			$("a[title='" + v.page.value.replace(/(['"])/g, "\\\$1") + "']")
				.after(" <small>(<a href='https://www.wikidata.org/wiki/" + qid + "'" + colour + ">statements: " + v.st.value + "</a>)</small>");
		});
	});
})();
});