User:Jeeputer/coordInserter.js

//

mw.loader.using(['mediawiki.util', 'jquery.ui'], function() {

var ad = ' (using coordInserter)';

var config = {

ns: mw.config.get('wgNamespaceNumber'),

title: mw.config.get('wgTitle'),

action: mw.config.get('wgAction'),

wikibaseItemId: mw.config.get('wgWikibaseItemId'),

script: mw.config.get('wgScript'),

WBQueryUrl: 'https://www.wikidata.org/w/rest.php/wikibase/v1/entities/items/'

};

var coordMaintCat = 'Articles missing coordinates with coordinates on Wikidata';

var isCoordMaintCat = config.title === coordMaintCat;

var isScriptActivated = !!new URLSearchParams(window.location.search).get('coordInserter');

var precSuggestions = {

// 1-2

'Q473972' : '1-2', // protected area

// 1-3

'Q23397' : '1-3', // lake

'Q170321' : '1-3', // wetland

'Q3409269' : '1-3', // statistical unit

'Q28872924' : '1-3', // designation for an administrative territorial entity of a single country

// 2-3

'Q11315' : '2-3', // shopping center

'Q50199' : '2-3', // administrative territorial entity of Laos

'Q56061' : '2-3', // administrative territorial entity

'Q690840' : '2-3', // district of Ethiopia

'Q1080224' : '2-3', // state electoral district

'Q2365748' : '2-3', // administrative territorial entity of India

'Q2916486' : '2-3', // administrative territorial entity type of Turkey

'Q3356092' : '2-3', // administrative territorial entity of Ireland

'Q3502496' : '2-3', // administrative territorial entity of Senegal

'Q3700011' : '2-3', // district of Indonesia

'Q5283521' : '2-3', // district of Laos

'Q12249052' : '2-3', // subdistrict of Iraq

'Q14925259' : '2-3', // administrative territorial entity of Iraq

'Q15617994' : '2-3', // administrative territorial entity type

'Q15642541' : '2-3', // human-geographic territorial entity

'Q65241205' : '2-3', // new town

'Q98966309' : '2-3', // classification of human settlements

'Q105626471': '2-3', // subdistrict of India

// 3-4

'Q16917' : '3-4', // hospital

'Q6023295' : '3-4', // funerary structure

'Q11668217' : '3-4', // type of station

'Q17063241' : '3-4', // state-funded school

// 2-5

'Q3950' : '3-5', // villa

// 3-5

'Q33506' : '3-5', // museum

'Q188055' : '3-5', // siege

'Q650711' : '3-5', // battle

'Q811102' : '3-5', // building type

'Q1354775' : '3-5', // memory space

'Q10624527' : '3-5', // biographical museum

'Q56242063' : '3-5', // Protestant church building

'Q111972893': '3-5', // type of structure

// 4-5

'Q32815' : '4-5', // mosque

'Q54050' : '4-5', // hill

'Q2065736' : '4-5', // cultural property

'Q2385804' : '4-5', // educational institution

// 5

'Q4022' : '5' // river

};

function precisionAssistance(data) {

var P31Value = data.statements.P31 && data.statements.P31[0].value.content;

if (P31Value) {

$.get(config.WBQueryUrl + P31Value).then(function(P31data) {

console.log(P31data);

var type = P31data.labels.en || 'non-specified';

var desc = P31data.descriptions.en || 'non-specified';

var suggestedPrecision = 'Suggested precision';

var typeOfType;

if (precSuggestions[P31data.id]) {

typeOfType = precSuggestions[P31data.id];

} else if (P31data.statements.P31 && P31data.statements.P31[0].value.content) {

typeOfType = precSuggestions[P31data.statements.P31[0].value.content];

}

var parentClassOfType;

if (!typeOfType && P31data.statements.P279) {

for (var sc = 0; sc < P31data.statements.P279.length; sc++) {

if (precSuggestions[P31data.statements.P279[sc].value.content]) {

parentClassOfType = precSuggestions[P31data.statements.P279[sc].value.content];

break;

}

}

}

var $notifText = $('

').append($('Type: ' + type + '
Description: ' + desc + '
'));

if (typeOfType || parentClassOfType) {

$notifText.append($('' + suggestedPrecision + ': ' + (typeOfType ? typeOfType : parentClassOfType) + ''));

} else {

$notifText.append(

$('No suggestions found for this type.
You can file a request!
')

.css({'font-size': '90%'})

);

}

mw.notify(

$notifText,

{

title: 'Precision assistance',

autoHide: false

}

);

});

}

}

function createEditLink(item) {

var href = item.href;

href = href + '?action=edit&coordInserter=1';

var a = $('')

.attr({

href: href,

target: '_blank'

})

.text('Edit');

$(item).parent().append(' | (').append(a).append(')');

}

if (config.ns === 14 && isCoordMaintCat) {

var randomURL = mw.util.getUrl(

'Special:RandomInCategory',

{

wpcategory: coordMaintCat,

action: 'edit',

coordInserter: '1'

}

);

var listItems = $("div.mw-category").find("li > a");

for (var i = 0; i < listItems.length; i++) {

createEditLink(listItems[i]);

}

var scriptHeader = $('

')

.append('To add coordinates to an article in this category, click on the "Edit" link next to its title below or ')

.append($('')

.attr({

href: randomURL,

target: '_blank'

})

.text('click here'))

.append(' to edit a random page');

$('#mw-pages')

.find('.mw-category-columns')

.before($('

')

.css({

'text-align': 'center',

'font-weight': 'bold',

'font-size': '105%'

})

.append(scriptHeader)

);

} else if (config.ns == 0 && config.action == 'edit' && isScriptActivated) {

var wikidataItem = $('#t-wikibase > a').attr('href').match(/EntityPage\/(Q\d*)/);

var qid = config.wikibaseItemId || (wikidataItem && wikidataItem[1]);

if (!qid) {

mw.notify($('Could not find Wikidata entity id for this page!
' +

'Please report the issue on ' +

'Script\'s talk page.'), {type: 'error'});

return;

}

$.get(config.WBQueryUrl + qid).then(function(data) {

if (!data.statements.P625) {

mw.notify('No coordinates on wikidata!', {type: 'warn'});

return;

}

if (!data.statements && data.code) {

mw.notify(

'Error: "' + data.message ? data.message : data.code + ' (' + data.code + ')',

{

type: 'warn',

autoHide: false

}

);

return;

}

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(?:s|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(

$('No "coord" or "coordinates" parameter found inside the page\'s wikitext.
' +

'In case you want to place the template somewhere else on the page, ' +

'Click on this pop-up to copy the syntax of the Coord template ' +

'to your clipboard.'),

{autoHide: false}

).done(function(notificationData) {

var $element = notificationData.$notification;

$element.on('click', function() {

// https://stackoverflow.com/a/11605419/15104823

$textBox.on("paste", function(e) {

var pastedData = e.originalEvent.clipboardData.getData('text');

if (pastedData.match('{{coord')) {

$('#wpSummary').val(summary);

$textBox.off('paste');

mw.notify('DO NOT FORGET TO REMOVE {{coord missing}} FROM THE PAGE!', {type: 'warn'});

}

});

// 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);

});

});

}

$textBox.focus();

precisionAssistance(data);

} else {

mw.notify($('No coordinates: Not found on

'#P625"; target="_blank">the Wikidata item.'));

}

});

}

});

//