MediaWiki:Modernisation.js

From Wikisource
Jump to navigation Jump to search

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.
/***************
 modernisations
****************/

var ws_alphabet = {
	'pt':'a-záàâãçéêẽíóòôõq̃úűA-ZÁÀÂÃÇÉÊẼÍÓÒÔÕQ̃ÚŰĩq̃ĨQ̃',
	'pt-br':'a-záàâãçéêẽíóòôõq̃úűA-ZÁÀÂÃÇÉÊẼÍÓÒÔÕQ̃ÚŰĩq̃ĨQ̃',
	'fr':'a-zçâàäāãéèêẽëîïôöōõûùüÿœæA-ZÀÂÄÉÈÊËÎÏÔÖÙÛÜŸÇŒÆ&ßẞĩq̃ĨQ̃',
	'es':'a-zçâàäãéèêẽëîïôöõûùüÿœæñA-ZÀÂÄÉÈÊËÎÏÔÖÙÛÜŸŒÆÑ&ß'
};


var dictionary_page = {
	'pt':'Wikisource:Dicionário',
	'pt-br':'Wikisource:Dicionário/pt-br',
	'fr':'Wikisource:Dictionnaire',
	'es':'Wikisource:Diccionario'
};

var user_lang = false;
var lang = user_lang? mw.config.get('wgUserLanguage') : mw.config.get('wgContentLanguage');
var re_alphabet = RegExp("([^" + ws_alphabet[lang] + "]+)", "");

// This change are applied to all lang, only change safe for all lang can be put here. 
function mod_text(text) {
  text = text.replace(/ſ/g, "s");
  text = text.replace(/ff/g, "ff");
  text = text.replace(/fl/g, "fl");
  text = text.replace(/fi/g, "fi");
  text = text.replace(/ffi/g, "ffi");
  text = text.replace(/ffl/g, "ffl");
  text = text.replace(/ſt/g, "st");
  text = text.replace(/st/g, "st");
  return text;
}
 
function mod_node(node) {
  if (node.nodeType == 3) {
    node.data = mod_text(node.data);
  } else {
    for (var i=0; i<node.childNodes.length; i++) {
      if ((node.id != 'editform'))
        mod_node(node.childNodes[i]);
    }
  }
}
 
function mod_typo_document() {  
  if ($.inArray(mw.config.get('wgCanonicalNamespace'), ['', 'User', 'Category', 'Page', 'Index']) !== -1) {
    document.title = mod_text(document.title);
    mod_node(document.getElementById('content'));
  }
}



/*********************************************************************************/

//reexp split a string; based on http://stevenlevithan.com/assets/misc/split.js

function reg_split(str, separator) {

	var	output = [],
		lastLastIndex = 0,
		flags = (separator.ignoreCase ? "i" : "") +
			(separator.multiline  ? "m" : "") +
			(separator.sticky     ? "y" : ""),
		separator = RegExp(separator.source, flags + "g"), // make `global` and avoid `lastIndex` issues
		separator2, match, lastIndex, lastLength;

	var compliantExecNpcg = /()??/.exec("")[1] === undefined;

	str = str + ""; // type conversion
	if (!compliantExecNpcg)
		separator2 = RegExp("^" + separator.source + "$(?!\\s)", flags); // doesn't need /g or /y, but they don't hurt

	while (match = separator.exec(str)) {
		lastIndex = match.index + match[0].length; // `separator.lastIndex` is not reliable cross-browser

		if (lastIndex > lastLastIndex) {
			output.push(str.slice(lastLastIndex, match.index));

			// fix browsers whose `exec` methods don't consistently return `undefined` for nonparticipating capturing groups
			if (!compliantExecNpcg && match.length > 1) {
				match[0].replace(separator2, function () {
					for (var i = 1; i < arguments.length - 2; i++) {
						if (arguments[i] === undefined)
							match[i] = undefined;
					}
				});
			}
			if (match.length > 1 && match.index < str.length)
				Array.prototype.push.apply(output, match.slice(1));
			lastLength = match[0].length;
			lastLastIndex = lastIndex;
		}

		if (separator.lastIndex === match.index)
			separator.lastIndex++; // avoid an infinite loop
	}

	if (lastLastIndex === str.length) {
		if (!separator.test("") || lastLength)
			output.push("");
	} else {
		output.push(str.slice(lastLastIndex));
	}

	return output;

}




function mod2_text(text, dict, build, udict) {
  list = reg_split(text, re_alphabet);

  text = ""; 
  var prev_w="";

  for (var i=0, len=list.length; i<len; i++) {
     var w = list[i];
     var sub_w = w.toLowerCase();

     //lookahead search
     if(i+2<len) {
          var next_w = list[i+2];
          var query = w + ' ' + next_w;
          var nw2 = dict[query.toLowerCase()];
          if(nw2){
             text=text+nw2;
             i=i+2;
             continue;
          }
     }

     if(sub_w=="sort") { 
           text=text+w;continue; 
     }

     var nw = dict[sub_w];
     if(nw) {
       if(build) udict[sub_w] = nw;
       if ( w == sub_w ) {
           text=text+nw;
       }
       else if( w ==w.toUpperCase() ) {
           text=text+nw.toUpperCase();
       }
       else if( w[0] == w[0].toUpperCase() && w[1] == w[1].toLowerCase() ){
           text = text + nw[0].toUpperCase() + nw.substring(1);
       }
       else text=text+w;
     } 
     else if(w=="&") {
        pw = list[i-2];
        if(pw && pw==pw.toUpperCase()) text=text+"ET";
        else text=text+"et"; 
     }
     else text=text+w; 

 
  } 
  if(build) return udict; 
  else return text;
}
 
 


function mod2_node(node,dict,build,udict) {
    if (node.nodeType == 3) {
      var data = mod2_text(node.data,dict,build,udict);
      if(!build) node.data = data;
    } else {
      for (var i=0; i<node.childNodes.length; i++) {
        if ((node.id != 'editform'))
          mod2_node(node.childNodes[i],dict,build,udict);
       }
    }
}
 



/* if dictionary does not exist, create it */

function do_mod_callback(res) {

    mod_typo_document();

    for(var page in res.query.pages) {
      if(!res.query.pages[page].pageid){

        alert('pas de dictionnaire');
        continue;
        var udict = {};text="";
        mod2_node(document.getElementById('content'), dico, true, udict);
        for(var w in udict){
          text = text + w+":"+udict[w]+",\n";
        }
        alert(text);

      }
      else {
         var wsdict = [];
         for(var page in res.query.pages) {
            var str = res.query.pages[page].revisions[0]['*'];
            lines = str.split('\n');
            for(var i in lines) {
               var match2 = /^\*\s*(\S[^:]*?)\s*:\s*([\S].*?)\s*$/.exec(lines[i]);
               if( match2 ) {
                  wsdict[match2[1]]=match2[2];
                  continue;
               }
            }
        }
        document.title = mod2_text(document.title, wsdict);
        mod2_node(document.getElementById('content'), wsdict, false, null);
      }
    }


    mm=document.getElementById("modernisations");
    if (mw.config.get('wgNamespaceNumber') === 0 && mm ) {

            var wsdict = [];
            str = mm.innerHTML;
            lines = str.split('\n');
            for( i in lines) {
               var match2 = /^<li>\s*(\S[^:]*?)(\s|&#160;|&nbsp;)*:\s*([\S].*?)\s*<\/li>$/i.exec(lines[i])
               if( match2 ) {
                  wsdict[match2[1]]=match2[3];
                  continue;
               }
            }
            mod2_node(document.getElementById('content'), wsdict, false, null);
    }
    li_a = document.getElementById("mod_option").firstChild;
    if(li_a) li_a.innerHTML="<a href=\""+location.href+"\">Texte&nbsp;original</a>";
}


function do_mod(){
    if($.inArray(mw.config.get('wgCanonicalNamespace'), ['', 'User', 'Category', 'Page', 'Index']) === -1) return;
    url = mw.config.get('wgServer') + '/w/api.php?action=query&format=json&prop=revisions&titles=' + dictionary_page[lang] + '&rvprop=content&callback=do_mod_callback';
    mw.loader.load(url);
}


function mod_lookup() {
  var mm=document.getElementById("modernisations");
  if ( mm && mw.config.get('wgNamespaceNumber') === 0 ) {
	 mw.loader.using( 'mediawiki.util', function() {
        var optlist = get_optlist();
        mw.util.addPortletLink('p-displayOptions', 'javascript:do_mod();', 'Texte modernisé', 'mod_option' );
	 });
  }
}

$(mod_lookup);
if(self.gadget_typographie && !self.gadget_mod2) {
    $(mod_typo_document);
}