User:Jeblad/spellchecker/script.js

From Meta, a Wikimedia project coordination wiki

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)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
/** 
 * Loosely based on [[User:ערן/spellchecker.js]] and [[de:MediaWiki:Gadget-Rechtschreibpruefung.js]]
 **/
function spellChecker() {
    'use strict';

	var dependencies = [
		'jquery.wikibase.linkitem',
		'mediawiki.jqueryMsg',
		'mediawiki.api',
		'mediawiki.util',
		'mediawiki.ForeignApi',
		'oojs-ui-core',
		'mw.config.values.wbRepo' ];
 
	var marker = 'misspell';
	var configEntityId = 'Q53648436';
    var ignorePages = [];

    // create config and extend it from session storage
    var config = {
    	"variants": [],
    	"accepted": [],
    	"affix-pages": [],
    	"term-pages": [] };
    jQuery.extend( config,
    	JSON.parse(sessionStorage.getItem( marker + '-config' ) ) || {} );

    // create entity and extend it from session storage
    var entity;//= {};
    //jQuery.extend( entity,
    //	JSON.parse(sessionStorage.getItem( marker + '-entity' ) ) || {} );

    // language variants: the script looks for the keys of the dictionary below
    // and if it finds them in article code it loads the specific variant instead
    // of default
    var langVariants = { };

    //var store = {}; //sessionStorage.mispellsList;//not maintained || $.cookie( 'mispellsList' );
    var dictionary = {
        misspells: {},
        keys: []
    };

    // create fallback messages
    var fallback = {
		'misspell-notify-title': 'Misspell detection',
    	//'misspell-localize-warn': 'Can not find language “$1”, using fallback messages.',
    	'misspell-connect-error': 'Can not find a dictionary for spelling mistakes, create it and link it from [[d:$1|misspell config]].',
    	'misspell-config-error': 'Failed during configuration, returns.',
    	'misspell-api-failure': 'Failure in the api.'
    };
    
    var inContentNamespace = function( namespaces ) {
		return 0 <= namespaces.indexOf( mw.config.get( 'wgNamespaceNumber' ) );
	};

	if ( !inContentNamespace( mw.config.get( 'wgContentNamespaces' ) )
		|| ( mw.config.get( 'wgAction' ) !== 'edit' )
	) {
		return;
	}

    $.when( mw.loader.using( dependencies ) )
		.then( function() {
			var messages = sessionStorage.getItem( marker + '-messages' );
			var promise;
			if ( messages ) {
				// messages exists from a previous invoke
				promise = Promise.resolve( messages );
			}
			else {
				// messages must be fetched
				promise = new mw.Api()
					.getMessages( Object.keys( fallback ), { amlang: mw.config.get( 'wgUserLanguage' ) } );
			}
			promise.then( function( messages ) {
				// override fallback messages
	    		$.each( jQuery.extend( fallback, messages ), function( key, message ) {
					mw.messages.set( key, message );
				} );
				// cache for later
				sessionStorage.setItem( marker + '-messages', JSON.stringify( fallback ) );
			}, function() {
				// use fallback messages
	    		$.each( fallback, function( key, message ) {
					mw.messages.set( key, message );
				} );
				// cache for later
				sessionStorage.setItem( marker + '-messages', JSON.stringify( fallback ) );
			} );
			return promise;
		} )
		.then( function() {
            var siteId = mw.config.get( 'wgDBname' );
			// entity is reused from a previous invoke
			entity = sessionStorage.getItem( marker + '-entity' );
			if ( entity ) {
				return;
			}
			var repoConfig = mw.config.get( 'wbRepo' );
			var repoApiUrl = repoConfig.url + repoConfig.scriptPath + '/api.php';
			var mwApiForRepo = wikibase.api.getLocationAgnosticMwApi( repoApiUrl );
        	var repoApi = new wikibase.api.RepoApi( mwApiForRepo );
            repoApi.getEntities( configEntityId, 'sitelinks')
                .then( function( data ) {
					var $content = $( '<div>' );
					if ( !data.success ) {
						var text = mw.message( 'misspell-api-failure' ).escaped();
						$( '<div>' ).text( text ).appendTo( content );
					}
					if ( data.warnings && data.warnings.wbgetentities ) {
						var $dl = $( '<dl>' );
						for ( var msg of data.warnings.wbgetentities ) {
							$( '<li>' ).text( msg ).appendTo( $dl );
						}
						$dl.appendTo( $content );
                        mw.notify( content, {
							title: mw.message( 'misspell-notify-title' ).escaped(),
							autoHide: false,
							tag: marker
						} );
						return;
					}
                    var entities = data.entities || {};
                    entity = data.entities[configEntityId];
                    if ( entity.sitelinks && entity.sitelinks[siteId] ) {
						sessionStorage.setItem( marker + '-config', JSON.stringify( entity.sitelinks[siteId] ) );
                    }
                    else {
                        mw.notify( mw.message( 'misspell-connect-error', configEntityId ).parseDom(), {
							title: mw.message( 'misspell-notify-title' ).escaped(),
							autoHide: false,
							tag: marker
						} );
                    }
                },
				function() {
					mw.notify( mw.message( 'misspell-config-error' ).parseDom(), {
						title: mw.message( 'misspell-notify-title' ).escaped(),
						autoHide: false,
						tag: marker
					} );
				} );
			//return repoApi;
        } )
       // .then();
    }
 
$(function(){
    // run only on active tabs
    if ( typeof document.hidden === "undefined" || !document.hidden) spellChecker();
    // wait for visibility change
    else $(document).one('visibilitychange', spellChecker);
});