Jump to content

User:Jeeputer/coordInserter.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
//<nowiki>
mw.loader.using(['mediawiki.util', 'jquery.ui'], function() {
    var ad = ' (using [[User:Jeeputer/coordInserter|coordInserter]])';
    var ns = mw.config.get('wgNamespaceNumber');
    var isCoordMaintCat = mw.config.get('wgTitle') === 'Articles missing coordinates with coordinates on Wikidata';
    var isScriptActivated = !!new URLSearchParams(window.location.search).get('coordInserter');
    /* var getTemplateInput = function (QID) {
    	var type, precision;
    	switch (QID) {
    		case 'Q41176':
    			out = '|type:landmark';
    			precision = 100000;
    			break;
			case '': 
    	}
    	return {type: type, percision: precision};
    }; */
    function createEditLink(item) {
        var href = item.href;
        href = href + '?action=edit&coordInserter=1';
        var a = $('<a>')
            .attr({
                href: href,
                target: '_blank'
            })
            .text('Edit');
        $(item).parent().append(' | (').append(a).append(')');
    }
    if (ns === 14 && isCoordMaintCat) {
        var listItems = $("div.mw-category").find("li > a");
        for (var i = 0; i < listItems.length; i++) {
            createEditLink(listItems[i]);
        }
    } else if (ns == 0 && mw.config.get('wgAction') == 'edit' && isScriptActivated) {
    	var wikidataItem = $('#t-wikibase > a').attr('href').match(/EntityPage\/(Q\d*)/);
        var qid = mw.config.get('wgWikibaseItemId') || (wikidataItem && wikidataItem[1]);
        if (!qid) {
        	mw.notify($('<span>Could not find Wikidata entity id for this page!<br/>' +
        	'Please report the issue on <a href="/wiki/User_talk:Jeeputer/coordInserter">' +
        	'Scripts talk page</a>.</span>'), {type: 'error'});
        	return;
        }
        $.get('https://www.wikidata.org/w/rest.php/wikibase/v0/entities/items/' + qid).then(function(data) {
            if (!data.statements.P625) {
                mw.notify('No coordinates on wikidata!', {type: 'warn'});
                return;
            }
            //var type = data.statements.P31[0].value.content;
            //templateInput = getTemplateInput(type)
            var $textBox = $('#wpTextbox1');
	    	var summary = 'Inserting {{coord}} using values from Wikidata' + ad;
            var restricted = data.statements.P625[0].value.type === 'somevalue'; // see [[wikidata:Q47460806]]
            var content = !restricted ? data.statements.P625[0].value.content : '';
            var latitude = !restricted ? Math.round(content.latitude * 100000) / 100000 : '';
            var longitude = !restricted ? Math.round(content.longitude * 100000) / 100000 : '';
            var coordMissingRegExp = /\n{0,2}\{\{(no geolocation|(coord(s|inates|missing)?|missing|needs|locate)?\s?)(coord(s|inates|missing)?|me|missing)?(\|[^\}]*)?\}\}/i;
            var template = !restricted ? '{{coord|' + latitude + '|' + longitude + '|display=inline,title}}' : '';
            var editBoxContent = $('#wpTextbox1').textSelection('getContents');
			var contentWithCoordMissingRemoved = editBoxContent.replace(coordMissingRegExp, '');
            var coordParam = editBoxContent.match(/\|\s*coord(?:inates)?\s*(\=)/si);
            if (!restricted) {
	            if (!!coordParam) {
	            	$textBox.textSelection('setContents', contentWithCoordMissingRemoved);
	                var indexOfEqSign = ((coordParam[0]).indexOf(coordParam[1])) + coordParam.index;
	                $textBox.textSelection('setSelection', {start: indexOfEqSign + 1});
	                $textBox.textSelection('encapsulateSelection', {post: " " + template});
	                $textBox.textSelection('setSelection', {start: indexOfEqSign + 2, end: (indexOfEqSign + 2) + template.length});
	                $textBox.textSelection('scrollToCaretPosition', {force: true});
	                $('#wpSummary').val(summary);
	                mw.notify('The coord template has been inserted.', {type: 'success'});
	            } else {
					var notification = mw.notify(
	                	$('<span>No "coord" or "coordinates" parameter found inside the page\'s wikitext.<br/>' +
						'In case you want to place the template somewhere else on the page, ' +
						'<b>Click on this pop-up to copy the syntax of the Coord template ' +
						'to your clipboard.</span>'),
						{autoHide: false}
					).done(function(data){
					    var $element = data.$notification;
					    $element.on('click', function() {
					    	// https://stackoverflow.com/a/11605419/15104823
						    $textBox.bind("paste", function(e) {
							    var pastedData = e.originalEvent.clipboardData.getData('text');
							    if (pastedData.match('{{coord')) {
	                				$('#wpSummary').val(summary);
	                				mw.notify('DO NOT FORGET TO REMOVE {{coord missing}} FROM THE PAGE!', {type: 'warning'});
							    }
							});
			                // Code borrowed from [[User:DannyS712/Easy-link.js#L-36]]
							var ignore_this = document.createElement("input");
							document.createElement("input");
						    document.body.appendChild(ignore_this);
						    ignore_this.value = template.replace('inline,', '');
						    ignore_this.select();
						    document.execCommand("copy");
						    document.body.removeChild(ignore_this);
					    });
					});
	            }
            } else {
            	mw.notify($('<span>No coordinates: Not found on <a href=' +
            	'"https://www.wikidata.org/wiki/Special:EntityPage/' + qid +
            	'#P625"; target="_blank">the Wikidata item</a>.</span>'));
            }
        });
    }
});
//</nowiki>