User:RamSeraph/IndianopenmapsLocater.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.
/*
 * Heavily copied from https://www.wikidata.org/wiki/User:Lectrician1/embeds.js
 * License: CC0
 * To use it, add the following line to your common.js:
 * mw.loader.load("//www.wikidata.org/w/index.php?title=User:RamSeraph/IndianopenmapsLocater.js&action=raw&ctype=text/javascript");
 */

(function () {
	"use strict";
	"esversion: 9";
	const COORDINATES_PROP = 'P625';
	const COORDINATES_GEOGRAPHIC_CENTER_PROP = 'P5140';
	
	const COORDS_PROPS = [ COORDINATES_PROP, COORDINATES_GEOGRAPHIC_CENTER_PROP ];
	
	function addLink(claimID, claimValue) {
		if (claimValue === undefined) {
			return;
		}
		
		// Escape to prevent XSS vulnerability
		const lat = mw.html.escape(claimValue.latitude.toFixed(5));
		const lon = mw.html.escape(claimValue.longitude.toFixed(5));
		claimID = mw.html.escape(claimID);
		const linkHtml = `<a href="https://indianopenmaps.fly.dev/wikidata-locater?markerLat=${lat}&markerLon=${lon}" target="_blank">Indianopenmaps Locater: ${lat}, ${lon}</a>`;
		$("#" + $.escapeSelector(claimID) + " .wikibase-edittoolbar-container")
			.after( $("<div />")
				.attr({
					"id": "link-" + claimID,
					"style": "padding-left: 26px; padding-top: 15px; max-width: 25em"
				})
				.html(linkHtml)
			);
	}
	
	// When the page has rendered
	mw.hook("wikibase.entityPage.entityView.rendered").add(function () {
		// When the entity has rendered
		mw.hook("wikibase.entityPage.entityLoaded").add(function (entity) {
			for (const prop of COORDS_PROPS) {
				if (entity.claims.hasOwnProperty(prop)) {
					$.each(entity.claims[prop], function (index, claim) {
						addLink(claim.id, claim.mainsnak.datavalue.value);
					});
				}
			}
		});
	});
	
	// When a new statement is saved
	mw.hook("wikibase.statement.saved").add(function (entityID, claimID, oldClaim, newClaim) {
		for (const prop of COORDS_PROPS) {
			if (newClaim.getClaim().getMainSnak().getPropertyId() == prop) {
						
				var linkNode = $(`#link-${$.escapeSelector(claimID)}`);
				var claimValue = newClaim.getClaim().getMainSnak().getValue().getValue();
						
				// If there already was a link on the claim
				if (linkNode.length) {
					linkNode.remove();
				}
				addLink(claimID, claimValue);
			}
		}
	});
})();