Jump to content

User:ערן/TemplateDataI18n.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.
/*
This is very ugly and hackish script to translate parameters labels in VE template editor.
This works for Cite web as proof of concept -  when you load Cite web template, it loads the templatedata from [[User:ערן/Template:Cite web]] to get mapping to wikidata.
then it uses wikidata to translate parameters.
*/
mw.loader.load( [ 'wikibase.api.RepoApi', 'wikibase.client.getMwApiForRepo' ] );

function translateProperties( properties, callback ) {
	properties = properties.join('|');
	var lang = mw.config.get('wgUserLanguage');
	var repoApi = new wikibase.api.RepoApi( wikibase.client.getMwApiForRepo() );
	repoApi.getEntities(properties, 'labels', lang).done(function(data){
		var translations = {};
		for(var property in data.entities){
			try{
				translations[property] = data.entities[property].labels[lang].value;
			} catch(ex) {}
		}
		callback( translations );
	});
}

function bindTemplateDialog(dialog){
	setTimeout(function(){
		console.log('binding');
		dialog.transclusionModel.on('replace', function(rem, add) {
			if (add.title != 'Template:Cite web') return; // hack only Cite web...

			var api=new mw.Api().get({
					action:'templatedata',
					titles: 'User:ערן/Template:Cite web'
			}).done(function( tds ){
				for(var pageid in tds.pages){
					var transProp = [];
					for(var property in tds.pages[pageid].maps['wikidata']) transProp.push(property);
					translateProperties(transProp, function( translatedProperties ){
						for(var property in tds.pages[pageid].maps['wikidata']){
							var propParam = tds.pages[pageid].maps['wikidata'][property];
							add.getSpec().params[propParam].label = translatedProperties[property];
						}
						// trigger UI update
						add.addPromptedParameters('fakeparameter');
				
					});
				}
			});
		});
	}, 1000);

}


mw.libs.ve.targetLoader.addPlugin(function( target ){
  setTimeout( function(){
    console.log('baba!!!');
    ve.init.target.getSurface().getDialogs().on('opening', function(e){
    if(e instanceof ve.ui.MWTransclusionDialog)	bindTemplateDialog(e);
    })}, 2000);
	return mw.loader.using( [ 'user' ] ).then(
			null,
			function () {
				return $.Deferred().resolve();
			}
		);
});