MediaWiki:Gadget-Scriptus.js

Википедия — эркин энциклопедияны бети.

Эслегиз: Бетде сакъланнгандан сора тюрлендириуле кёрюнюрча браузеригизни кэшин ариулатыргъа керек болургъа боллукъду.

  • Firefox / Safari: Shift тиекни басыб тургъанлай адырланы панелинде Джангырт тиекни басыгъыз, неда Ctrl-F5 басыгъыз, неда Ctrl-R (Mac-да — ⌘-Shift-R)
  • Google Chrome: Ctrl-Shift-R басыгъыз (Mac-да — ⌘-Shift-R)
  • Internet Explorer / Edge: Ctrl тиекни басыб тургъанлай Джангырт тиекни басыгъыз, неда Ctrl-F5 басыгъыз
  • Opera: Ctrl-F5 басыгъыз.
/*
 * Scriptus
 *
 * La fonction Scriptus sert à rédiger sur wikipédia de manière naturelle, 
 * par simple doubleclic et confimation de sauvegarde. 
 * La définition de ce script se trouve ici : 
 * http://fr.wikipedia.org/wiki/Wikip%C3%A9dia:Brouillons/interface_ajax
 *
 * Le code du script est librement inspiré du système de modification-inline de Olivier Lance
 * http://olance.developpez.com/articles/web/javascript/modification-inline/
 *
 * Auteurs : ivo talvet (fr:user:Tavernier) , JoKerozen (fr:user:JoKerozen)
 * Date de dernière révision : 20 octobre 2007 - 0.1 (alpha) - fonctionnalités basiques, non optimisées
 * snapshot depuis http://fr.wikipedia.org/w/index.php?title=Wikip%C3%A9dia:Brouillons/interface_ajax/js&oldid=21985960
 * {{Projet:JavaScript/Script|Scriptus}}
 */

function Scriptus() {
   if (!wgIsArticle) return; //si non editable, sortie
   if (mw.config.get('wgNamespaceNumber')/2 != Math.round(mw.config.get('wgNamespaceNumber')/2)) return; //si impair (discussion), retour
   if (  (mw.config.get('wgPageName').search('Wikipédia:Le_Bistro') != -1)
       ||(mw.config.get('wgPageName').search('Wikipédia:Bulletin_des_administrateurs') != -1)
       ||(document.getElementById("transformeEnPageDeDiscussion"))
      ) return; //cas exceptionnels de discussion dans ns pair

   loadEventsScriptus();
}


function loadEventsScriptus() {

   var intro = getElementsByClass("firstHeading")[0];

   intro.className = "mw-headline firstHeading"; //cohérence
   var sections = getElementsByClass("mw-headline");
   for each (var section in sections) {
       
       try {
       var hrefSection = getElementsByClass("mw-editsection", section.parentNode)[0]
                        .getElementsByTagName('a')[0]
                        .getAttribute('href');
       } catch(e) {}
       if (section.className == "mw-headline firstHeading") {
           var numSection = 0; //firstHeading
       } 
       else {
       var numSection = hrefSection.replace(/.*section=([0-9]+)/g, '$1');
       }
       section.addEventListener("dblclick", findBlocScriptus(numSection), false);
   }
}


function findBlocScriptus(numSection) 
{
    return function()
    {
    if (document.getElementsByTagName('textarea').length) return;

    document.ou = numSection;


    var headers = new Array();
    headers['Cache-Control'] = 'no-cache, must-revalidate';
    headers['Pragma'] = 'no-cache';


    // quitte a charger la page d'edit, autant le faire ici et récupérer wpTextbox1, qui normalement est a jour 

    if (document.ou == 0) {
    var demandeSection = ''
    } 
    else {
    var demandeSection = '&section=' + document.ou
    }

    var editFormSeek = wpajaxScriptus.http({ url: mw.config.get('wgServer') + wgScriptPath 
                                                  + '/index.php?title=' 
                                                  + encodeURIComponent(mw.config.get('wgPageName')) 
                                                  + '&action=edit' 
                                                  + demandeSection,
                                             async: false,
                                             headers: headers,
                                             });

    var parser = new DOMParser();

    var doc = parser.parseFromString(editFormSeek.responseText, 'application/xhtml+xml');

    var inputs = doc.getElementById('editform').getElementsByTagName('input');
    var editform = new Array();

    for (i=0; i<inputs.length; i++) {
      editform[inputs[i].name] = inputs[i].value;
    }

    // on place des inputs hidden pour "sauvegarder" les infos dont on aura besoin

    var titre = getElementsByClass('mw-headline firstHeading')[0]

    var wpTextbox1 = doc.getElementById('wpTextbox1').value;
    var hiddenTxt = document.createElement("input");
    hiddenTxt.type = "hidden";
    hiddenTxt.value = wpTextbox1;
    hiddenTxt.id = "hiddenTxt";
    titre.appendChild(hiddenTxt);

    var wpStarttime = encodeURIComponent(editform['wpStarttime']);
    var hiddenStarttime = document.createElement("input");
    hiddenStarttime.type = "hidden";
    hiddenStarttime.value = wpStarttime;
    hiddenStarttime.id = "hiddenStarttime";
    titre.appendChild(hiddenStarttime);

    var wpEdittime = encodeURIComponent(editform['wpEdittime']);
    var hiddenEdittime = document.createElement("input");
    hiddenEdittime.type = "hidden";
    hiddenEdittime.value = wpEdittime;
    hiddenEdittime.id = "hiddenEdittime";
    titre.appendChild(hiddenEdittime);

// test recuperation token autrement

    var wpEditToken = encodeURIComponent(editform['wpEditToken']);
    var hiddenEditToken = document.createElement("input");
    hiddenEditToken.type = "hidden";
    hiddenEditToken.value = wpEditToken;
    hiddenEditToken.id = "hiddenEditToken";
    titre.appendChild(hiddenEditToken);

    var wpSection = encodeURIComponent(editform['wpSection']);
    var hiddenSection = document.createElement("input");
    hiddenSection.type = "hidden";
    hiddenSection.value = wpSection;
    hiddenSection.id = "hiddenSection";
    titre.appendChild(hiddenSection);

    afficheBlocScriptus(editFormSeek);

    };
}


function afficheBlocScriptus(contenu) {


    var texte = gml_XMLParse(contenu.responseText);

    if (document.ou == 0) {
        var bloc = getElementsByClass('mw-headline firstHeading')[0];
    } 
    else {
        var bloc = getElementsByClass('mw-headline')[document.ou].parentNode;
    }

    var form = document.createElement("form");
    form.className = 'ajaxedit';
    form.name = 'ajaxEditForm';
    form.method = 'get';
    form.action = "javascript:envoye2BlocScriptus();"; //redondant ? (non en cas de touche entree sur le input de résumé) 

    var ajaxTxtarea = document.getElementById('hiddenTxt');
    var wpTextbox1 = ajaxTxtarea.value;

    var textarea = document.createElement("textarea");
    textarea.className = "ajaxTextarea";
    var lines = wpTextbox1.split(/\n/).length;
    var nbchars = wpTextbox1.length;

    textarea.appendChild(document.createTextNode(wpTextbox1));
    form.appendChild(textarea);

    var summary = document.createElement("input");
    summary.type = "Text";
    summary.name = "wpSummary";
    summary.id = "wpSummary"
    summary.value="Veuillez résumer vos modifications"
    form.appendChild(summary);

    var save = document.createElement("input");
    save.type = "button";
    save.value = "Envoyer"
    form.appendChild(save);

    var preview = document.createElement("input");
    preview.type = "button";
    preview.value = "Prévisualisation"
    form.appendChild(preview);

    var annuler = document.createElement("input");
    annuler.type = "button";
    annuler.value = "Annuler"
    form.appendChild(annuler);




    bloc.appendChild(form); 

    var largeur = form.offsetWidth;
    var colones = largeur*10/75;
    var nblines = nbchars/colones+lines;
    textarea.rows = nblines;

    save.addEventListener("click", envoye2BlocScriptus, false);
    annuler.addEventListener("click", annuleScriptus, false);
    preview.addEventListener("click", previsualisationScriptus, false);
}

function annuleScriptus() {

    if (document.ou == 0) {
        var bloc = getElementsByClass('mw-headline firstHeading')[0];
    } 
    else {
        var bloc = getElementsByClass('mw-headline')[document.ou].parentNode;
    }

    var form = getElementsByClass('ajaxedit')[0]
    if (document.getElementById('wikiPreview')) {
        var oldpreview = document.getElementById('wikiPreview').parentNode.removeChild(document.getElementById('wikiPreview'))
    }
    var oldform = bloc.removeChild(form);


}

function envoye2BlocScriptus() {

    var wpTextbox1 = encodeURIComponent(document.getElementsByTagName('textarea')[0].value);
    var wpSection = document.ou
    var wpSummary = encodeURIComponent(document.getElementById('wpSummary').value);
    if (wpSummary == encodeURI("Veuillez résumer vos modifications")) wpSummary = ""; 

    // recuperation des champ hidden

    var wpEdittime = document.getElementById('hiddenEdittime').value;
    var wpEditToken = document.getElementById('hiddenEditToken').value;
    var wpStarttime = document.getElementById('hiddenStarttime').value;

    if (document.ou == 0) {
    var Section_editee = ''
    } else {
    var Section_editee = '&wpSection=' + wpSection
    }

    if (document.getElementById('ca-unwatch')) {
      var suivi = '&wpWatchthis=1';
    } else {
      var suivi = '';
    }

    var headers = new Array();
    headers['Content-Type'] = 'application/x-www-form-urlencoded';
    headers['Cache-Control'] = 'no-cache, must-revalidate';


    document.HttpWPedit = wpajaxScriptus.http({ url: mw.config.get('wgServer') + wgScriptPath + '/index.php?title=' 
                                 + encodeURIComponent(mw.config.get('wgPageName')) 
                                 + '&action=submit',
                          method: "POST", 
                          headers: headers,
                          async: false,
                          data: 'wpSave=1&wpTextbox1=' + wpTextbox1 
                                + '&wpStarttime=' + wpStarttime 
                                + '&wpEdittime=' + wpEdittime
                                + '&wpEditToken=' + wpEditToken 
                                + Section_editee
                                + suivi
                                + '&wpSummary=' + wpSummary + encodeURIComponent(' (mpa)')}); 
    apresModifScriptus();
}



function previsualisationScriptus() {

    if (document.getElementById('wikiPreview')) {
        var oldpreview = document.getElementById('wikiPreview').parentNode.removeChild(document.getElementById('wikiPreview'));
    }

    var wpTextbox1 = encodeURIComponent(document.getElementsByTagName('textarea')[0].value);
    var wpSection = document.ou
    var wpSummary = encodeURIComponent(document.getElementById('wpSummary').value);
    if (wpSummary == encodeURI("Veuillez résumer vos modifications")) wpSummary = ""; 

    // recuperation des champ hidden

    var wpEdittime = document.getElementById('hiddenEdittime').value;
    var wpEditToken = document.getElementById('hiddenEditToken').value;
    var wpStarttime = document.getElementById('hiddenStarttime').value;

    if (document.ou == 0) {
    var Section_editee = ''
    } else {
    var Section_editee = '&wpSection=' + wpSection
    }

    if (document.getElementById('ca-unwatch')) {
      var suivi = '&wpWatchthis=1';
    } else {
      var suivi = '';
    }

    var headers = new Array();
    headers['Content-Type'] = 'application/x-www-form-urlencoded';
    headers['Cache-Control'] = 'no-cache, must-revalidate';


    document.HttpWPpreview = wpajaxScriptus.http({ url: mw.config.get('wgServer') + wgScriptPath + '/index.php?title=' 
                                 + encodeURIComponent(mw.config.get('wgPageName')) 
                                 + '&action=submit',
                          method: "POST", 
                          headers: headers,
                          async: false,
                          data: 'wpSave=1&wpTextbox1=' + wpTextbox1 
                                + '&wpStarttime=' + wpStarttime 
                                + '&wpEdittime=' + wpEdittime
                                + '&wpEditToken=' + wpEditToken 
                                + Section_editee
                                + '&wpPreview=Prévisualisation'
                                + suivi
                                + '&wpSummary=' + wpSummary + encodeURIComponent(' (mpa)')});

    var parser = new DOMParser();

    var previewRetour = parser.parseFromString(document.HttpWPpreview.responseText, 'application/xhtml+xml');
    var previewHtml = previewRetour.getElementById('wikiPreview');
    var previewDiv = document.createElement("div");
    previewDiv = previewHtml;

    var titre = previewDiv.getElementsByTagName('h2')[0];

    var Aretirer = previewDiv.getElementsByTagName('div')[0];
    previewDiv.removeChild(Aretirer);

    var form = getElementsByClass('ajaxedit')[0];
 
    previewDiv = form.parentNode.parentNode.insertBefore(previewDiv, form.parentNode.nextSibling);
    previewDiv.style.border = "2px solid #FF8080";
    previewDiv.style.backgroundColor = "#FCFFE5";
    titre.style.color = "#FF8080";

    var fermeturePreview = document.createElement("span");
    fermeturePreview.style.fontSize = "xx-small";
    fermeturePreview.style.fontWeight = "normal";
    fermeturePreview.style.cssFloat = "none";
    fermeturePreview = titre.appendChild(fermeturePreview);
    fermeturePreview.innerHTML = '<a href="javascript:var temporaire = document.getElementById(\'wikiPreview\').parentNode.removeChild(document.getElementById(\'wikiPreview\'));" title="Fermer la prévisualisation">fermer</a>'; //virer le innerHTML

}

function apresModifScriptus() {

    annuleScriptus();

    var parser = new DOMParser();

    var doc = parser.parseFromString(document.HttpWPedit.responseText, 'application/xhtml+xml');
    var entirepage = doc.getElementById('bodyContent');
    var bodycontent = document.getElementById('bodyContent');
    var bodyparent = bodycontent.parentNode;
    var oldBody = bodyparent.removeChild(bodycontent);
    var newbody = document.createElement("div");
    newbody = entirepage;
    bodyparent.appendChild(newbody);

}

var wpajaxScriptus = { // depuis http://fr.wikipedia.org/wiki/Utilisateur:EDUCA33E/LiveRC.js
  http: function(bundle) {
    // mandatory: bundle.url
    // optional:  bundle.async
    // optional:  bundle.method
    // optional:  bundle.headers
    // optional:  bundle.data
    // optional:  bundle.onSuccess (xmlhttprequest, bundle)
    // optional:  bundle.onFailure (xmlhttprequest, bundle)
    // optional:  bundle.otherStuff OK too, passed to onSuccess and onFailure
    var xmlhttp;
        try {xmlhttp = new XMLHttpRequest();} catch (e) {xmlhttp = false}
 
    if (xmlhttp) {
      xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4) {
          wpajaxScriptus.httpComplete(xmlhttp,bundle);
        }
      }
      xmlhttp.open(bundle.method ? bundle.method : "GET",bundle.url,bundle.async == false ? false : true);
      if (bundle.headers) {
        for (var field in bundle.headers)
          xmlhttp.setRequestHeader(field,bundle.headers[field]);
      }
      xmlhttp.send(bundle.data ? bundle.data : null); 
    }

    return xmlhttp;
  },
 
  httpComplete: function(xmlhttp,bundle) {

    if (xmlhttp.status == 200 || xmlhttp.status == 302) {
      if (bundle.onSuccess) {
        bundle.onSuccess(xmlhttp,bundle);
      } else if (bundle.onFailure) {
      bundle.onFailure(xmlhttp,bundle);
      } else {
      // A activer en debug mode ?
      if (xmlhttp.statusText != "OK") alert(xmlhttp.statusText);
      }
    }
  }
};

// Parser
if (document.implementation.createDocument) {
  var gml_xmlparser = new DOMParser();
}
 
function gml_XMLParse(string) {
  if (document.implementation.createDocument) {
    return gml_xmlparser.parseFromString(string, "text/xml");
  }
  return null;
}

addLoadEvent(Scriptus);