User:QTHCCAN/jsonLexeme.js

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.
/*	jsonLexeme.js
	
	To use this script, add 
		importScript('User:Okkn/jsonLexeme.js');
	into your [[User:UserName/common.js]].
	
	Original version (User:GZWDer/newentity.js) was created by [[User:GZWDer]].
	Thank you so much, GZWDer!
*/ 

mw.loader.using( ['mediawiki.language','jquery.ui','mediawiki.api','mediawiki.language','mediawiki.util'] ).then( function ( mw, $ ) {
	'use strict';/*
	var i18nData = {
		'en': {
			'create-title': 'Create entity',
			'create-button': 'Create'
		},
	};

	var chain = mw.language.getFallbackLanguageChain(),
		len = chain.length,
		messages = {},
		i;
	for ( i = len - 1; i >= 0; i-- ) {
		if ( i18nData.hasOwnProperty( chain[ i ] ) ) {
			$.extend( messages, i18nData[ chain[ i ] ] );
		}
	}

	mw.messages.set( messages );
*/
	mw.messages.set( {
			'create-title': 'Create Lexeme',
			'create-button': 'Create',
			'edit-title': 'Edit Lexeme',
			'edit-button': 'Edit'
		});

	/**
	 * Called on error
	 */
	function onError() {
		$.removeSpinner( 'CreateEntity' );
		$( '#create-button' ).button( 'option', 'disabled', false );
	}

	/**
	 * Called on API error
	 */
	function onApiError( jqXHR, textStatus, errorThrown ) {
		alert( mw.msg( 'API Error: ' + textStatus.error.code + ": " + textStatus.error.info.replace(/"/g, '') ) );
		onError();
	}
	
	/**
	 * Called on JSON.perse error
	 */
	function onJsonError( error ) {
		alert( mw.msg( 'JSON.parse Error: ' + error ) );
		onError();
	}
	
	/**
	 * Called on type error
	 */
	function onTypeError( error ) {
		alert( mw.msg( 'Type Error: ' + error ) );
		onError();
	}

	function createEntity (entitydata, summary) {
		//var entitytype='item';
		//if (JSON.parse(entitydata).datatype) entitytype='property';
		//if (JSON.parse(entitydata).lexicalCategory) entitytype='lexeme';
		var parseddata;
		if(entitydata) {
	    	try {
	        	parseddata = JSON.parse(entitydata);
		    } catch(e) {
		        onJsonError(e);
		        return;
		    }
		}
		var entitytype;
		if (parseddata.lexicalCategory) {
			entitytype='lexeme';
		} else {
			onTypeError( 'JSON syntax is OK, but data is not a valid lexeme' );
			return;
		}
		new mw.Api().postWithToken( 'csrf', {
			action: 'wbeditentity',
			'new': entitytype,
			data: entitydata,
			summary: summary
		} )
		.done( function ( data ) {
			if ( data.entity) {
		    	$( '#CreatedEntities' ).append("Created " + data.entity.id+"<br/>");
			} else {
				onApiError();
			}
		} )
		.fail( onApiError );
    }
    
    function editEntity (entitydata, lexemeid, summary) {
		//var entitytype='item';
		//if (JSON.parse(entitydata).datatype) entitytype='property';
		//if (JSON.parse(entitydata).lexicalCategory) entitytype='lexeme';
		var parseddata;
		if(entitydata) {
	    	try {
	        	parseddata = JSON.parse(entitydata);
		    } catch(e) {
		        onJsonError(e);
		        return;
		    }
		}
		var entitytype;
		if (parseddata.lexicalCategory) {
			entitytype='lexeme';
		} else {
			onTypeError( 'JSON syntax is OK, but data is not a valid lexeme' );
			return;
		}
		new mw.Api().postWithToken( 'csrf', {
			action: 'wbeditentity',
			id: lexemeid,
			data: entitydata,
			summary: summary
		} )
		.done( function ( data ) {
			if ( data.entity) {
		    	$( '#EditedEntities' ).append("Edited " + data.entity.id+"<br/>");
				if (mw.config.get( 'wgNamespaceNumber' ) == 146 && mw.config.get( 'wgTitle' ) == $( '#lexemeid' ).val()){
					setTimeout(window.location.reload.bind(window.location), 1000);
				}
			} else {
				onApiError();
			}
		} )
		.fail( onApiError );
    }

	function work() {
		new mw.Api().get( {
			action: 'expandtemplates',
			prop: 'wikitext',
			text: $( '#entitydata' ).val()
		} )
		.done( function ( data ) {
			if ( data.expandtemplates) {
				createEntity ( data.expandtemplates.wikitext , $( '#entitydata' ).val() );
			} else {
				onApiError();
			}
		}  )
		.fail( onApiError );
	}
	
	function work2() {
		new mw.Api().get( {
			action: 'expandtemplates',
			prop: 'wikitext',
			text: $( '#entitydata2' ).val()
		} )
		.done( function ( data ) {
			if ( data.expandtemplates) {
				editEntity ( data.expandtemplates.wikitext, $( '#lexemeid' ).val() , $( '#entitydata2' ).val() );
			} else {
				onApiError();
			}
		}  )
		.fail( onApiError );
	}
	

	/**
	 * Show the dialog
	 */
	function show() {
		$( '#CreateEntity-error' ).html( '' );
		$( 'div#CreateEntity' ).dialog( 'open' );
		return false;
	}
	
	function show2() {
		$( '#EditEntity-error' ).html( '' );
		$( 'div#EditEntity' ).dialog( 'open' );
		if (mw.config.get( 'wgNamespaceNumber' ) == 146) { //if current page is 146: Lexeme
			$( '#lexemeid' ).val(mw.config.get( 'wgTitle' ));
			$( '#entitydata2' ).focus();
		}
		return false;
	}

	/**
	 * Create the dialog and add a link in toolBox
	 */
	function init() {
		mw.loader.using( ['jquery.ui'],function(){$( '<div>' ).attr( {
			id: 'CreateEntity',
			title: mw.msg( 'create-title' )
		} ).append(
			$( '<form>' ).attr( {
				style: 'height:100%;',
			} ).append(
				$( '<textarea id="entitydata" style="height:calc(100% - 2em);margin:0;">' ).attr( {
					placeholder: 'Input JSON data here to create a new lexeme, ' + 
								'according to the Wikibase API. ' +
								'Templates are going to be expanded, ' +
								'so you can use templates or modules '+
								'to generate JSON. Example: ' +
								'"{{#invoke:Lexeme-ja|verbForms|勝つ|かつ|ta-go}}"',
				}),
				$( '<span class="error" id="CreateEntity-error" style="height:2em;margin:0;">' ),
				$( '<span id="CreatedEntities" style="height:2em;margin:0;">' )
			)
		)
		.appendTo( '#content' )
		.dialog( {
			autoOpen: false,
			modal: true,
			width: 500,
			height: 400,
			buttons: [ {
				id: 'createEntity-create-button',
				text: mw.msg( 'create-button' ),
				click: work
			} ]
		} );

		var portletLink = mw.util.addPortletLink( 'p-tb', '#', mw.msg( 'create-title' ), 't-CreateLexeme', mw.msg( 'create-title' ) );
		$( portletLink ).click( show );});
		
		mw.loader.using( ['jquery.ui'],function(){$( '<div>' ).attr( {
			id: 'EditEntity',
			title: mw.msg( 'edit-title' )
		} ).append(
			$( '<form>' ).attr( {
				style: 'height:100%;',
			} ).append(
				$( '<label for="lexemeid">' ).html('Lexeme ID: '),
				$( '<input type="text" id="lexemeid" style="height:1em;margin:0;">' ),
				$( '<textarea id="entitydata2" style="height:calc(100% - 3em);margin:0;">' ).attr( {
					placeholder: 'Input JSON data here to update the lexeme, ' + 
								'according to the Wikibase API. ' +
								'Templates are going to be expanded, ' +
								'so you can use templates or modules '+
								'to generate JSON. Example: ' +
								'"{{#invoke:Lexeme-ja|verbForms|勝つ|かつ|ta-go}}"',
				}),
				$( '<span class="error" id="EditEntity-error" style="height:2em;margin:0;">' ),
				$( '<span id="EditedEntities" style="height:2em;margin:0;">' )
			)
		)
		.appendTo( '#content' )
		.dialog( {
			autoOpen: false,
			modal: true,
			width: 500,
			height: 400,
			buttons: [ {
				id: 'editEntity-edit-button',
				text: mw.msg( 'edit-button' ),
				click: work2
			} ]
		} );
		var portletLink2 = mw.util.addPortletLink( 'p-tb', '#', mw.msg( 'edit-title' ), 't-EditLexeme', mw.msg( 'edit-title' ) );
		$( portletLink2 ).click( show2 );});
	}

	$( init );
} ( mediaWiki, jQuery ) );