Utilisateur:Dr Brains/BandeauxEbauches.js

Une page de Wikipédia, l'encyclopédie libre.
Note : après avoir enregistré la page, vous devrez forcer le rechargement complet du cache de votre navigateur pour voir les changements.

Mozilla / Firefox / Konqueror / Safari : maintenez la touche Majuscule (Shift) en cliquant sur le bouton Actualiser (Reload) ou pressez Maj-Ctrl-R (Cmd-R sur Apple Mac) ;

Chrome / Internet Explorer / Opera : maintenez la touche Ctrl en cliquant sur le bouton Actualiser ou pressez Ctrl-F5.
//<noinclude>{{Catégorisation JS|BandeauxEbauches}}</noinclude>

//

// Documentation : [[Projet:JavaScript/Notices/BandeauxEbauches]]

//<syntaxhighlight lang=javascript>
//<pre><nowiki>


////////////////////////////////////////////////////////////////////////////////////////// VARIABLES PERSONNALISABLES

window.BandeauxEbauches_MaxParams = 6;          // Nombre maximum de paramètres pour le modèle {{Ébauche}}

if(typeof(window.BandeauxEbauches_AutoEdit)=='undefined') window.BandeauxEbauches_AutoEdit = true;         // Publication automatique

if(typeof(window.BandeauxEbauches_MinorEdit)=='undefined') window.BandeauxEbauches_MinorEdit = 1;          // Modification mineure

if(typeof(window.BandeauxEbauches_Watchthis)=='undefined') window.BandeauxEbauches_Watchthis = -1;         // Suivre la page

if(typeof(window.BandeauxEbauches_TailleListe)=='undefined') window.BandeauxEbauches_TailleListe = 5;      // Nombre de suggestions

if(typeof(window.BandeauxEbauches_ListeBas)=='undefined') window.BandeauxEbauches_ListeBas = true;         // Affichage des suggestions vers le bas

if(typeof(window.BandeauxEbauches_KeyboardDelay)=='undefined') window.BandeauxEbauches_KeyboardDelay = 5;  // Délai (en secondes) lors de la sélection d'une suggestion au clavier

// Groupe nécessaire pour appliquer une balise
if(typeof window.BandeauxEbauches_TagGroup === 'undefined') window.BandeauxEbauches_TagGroup = "user";

// Balise à appliquer aux modifs
if(typeof window.BandeauxEbauches_Tag === 'undefined'){
  window.BandeauxEbauches_Tag = "";
  if(mw.config.get('wgServer') == '//fr.wikipedia.org') window.BandeauxEbauches_Tag = "BandeauxEbauches";
}

////////////////////////////////////////////////////////////////////////////////////////// AJAX

window.BandeauxEbauches_ajax = {
  http: function(bundle) {
    var xmlhttp;
    try {
      xmlhttp = new XMLHttpRequest();
    } catch(e) {
      try {
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
        try {
          xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {
          xmlhttp = false;
        }
      }
    }
    if (xmlhttp) {
      xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4)
          BandeauxEbauches_ajax.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)
          try {
            xmlhttp.setRequestHeader(field,bundle.headers[field]);
          } catch(err) {  }
      }
      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);
    }
  }
};



////////////////////////////////////////////////////////////////////////////////////////// LANCEMENT

 
window.BandeauxEbauches_gettag = function(){
  if(!BandeauxEbauches_Tag || !BandeauxEbauches_TagGroup) return false;
  var UserGroups = mw.config.get('wgUserGroups');
  if(UserGroups.indexOf(BandeauxEbauches_TagGroup) !== -1) return BandeauxEbauches_Tag;
  return false;
}

window.BandeauxEbauches = function(){
      var EbaucheCount = -1;
      var AllDivs = document.getElementsByTagName('div');
      for(var a=0;a<AllDivs.length;a++){
            if($( AllDivs[a] ).hasClass( 'bandeau-niveau-ebauche' )){
                  EbaucheCount++;
                  var BandeauTable = AllDivs[a].getElementsByTagName('table')[0];
                  if (BandeauTable){
	                  BandeauTable.id = 'TableBandeau_'+EbaucheCount;
                  }
                  var StrongText = AllDivs[a].getElementsByTagName('strong')[0];
                  StrongText.innerHTML += ' (<a href="javascript:BandeauxEbauches_GetBandeaux(\''+EbaucheCount+'\');" title="Modifier le bandeau d\'ébauche">modifier</a>)';
            }
      }
      if(EbaucheCount<0){
            var Cactions = document.getElementById('p-cactions');
            if(Cactions){
                  var UL = Cactions.getElementsByTagName('ul')[0];
                  if(UL){
                        var LI = document.createElement('li');
                        LI.innerHTML = '<a href="javascript:BandeauxEbauches_CreateBandeau();" title="Ajouter un bandeau d\'ébauche">Ébauche</a>';
                        UL.appendChild(LI);
                        $( Cactions ).removeClass( 'emptyPortlet' );
                  }
            }
      }
}

if ( ( mw.config.get( 'wgAction' ) === 'view' ||
       mw.config.get( 'wgAction' ) === 'purge' ) &&
      mw.config.get( 'wgNamespaceNumber' ) > -1 ) {
	$( BandeauxEbauches );
}


////////////////////////////////////////////////////////////////////////////////////////// RECHERCHE DES PARAMÈTRES DU BANDEAU ACTUEL

window.BandeauxEbauches_GetBandeaux = function(BandeauCount){
     var URL = mw.config.get( 'wgServer' ) + mw.config.get( 'wgScript' ) + '?title=' + encodeURIComponent(mw.config.get( 'wgPageName' )) +'&action=edit&section=0';
     BandeauxEbauches_ajax.http({url: URL, onSuccess:BandeauxEbauches_UpdateDone,count:BandeauCount});
}

window.BandeauxEbauches_UpdateDone = function(Req, data){
     var BandeauCount = data.count;
     var Temp = document.createElement('div');
     //document.body.insertBefore(Temp, document.body.firstChild);
     Temp.innerHTML = Req.responseText;

     var OldText = Temp.getElementsByTagName('textarea')[0].value;
     OldText = OldText.replace(/\{\{ébauche/g, "\{\{Ébauche");
     OldText = OldText.replace(/\{\{Ébauche /g, "\{\{Ébauche\|");

     var BeforeModele = OldText.substring(0, OldText.indexOf('{{Ébauche'));
     var Modele = OldText.split(BeforeModele + '{{Ébauche').join('');
     while(Modele.indexOf('}}')!=-1){
          Modele = Modele.substring(0, Modele.indexOf('}}'));
          if(Modele.indexOf('}}')!=-1) break;
     }
     //alert(Modele);
     if(Modele!='') Modele = Modele + '|';
     var ListeBandeaux = new Array();
     var ListeBandeauxCount = -1;
     while(Modele.indexOf('|')!=-1){
          var Param = Modele.split('|')[1].split('|')[0];
          //alert(Param);
          ListeBandeauxCount++;
          ListeBandeaux[ListeBandeauxCount] = Param;
          Modele = Modele.split('|'+Param).join('');
     }
     BandeauxEbauches_ModifyBandeau(BandeauCount, ListeBandeaux);
}


////////////////////////////////////////////////////////////////////////////////////////// FORMULAIRE

window.BandeauxEbauches_CreateBandeau = function(){
      var Content = document.getElementById('bodyContent');
      if(!Content) Content = document.getElementById('mw_contentholder');
      if(!Content) Content = document.getElementById('article');
      if(!Content) return;
      var ListeBandeaux = new Array();
      var NewBandeau = document.createElement('div');
      NewBandeau.className = "plainlinks bandeau-niveau-ebauche bandeau";
      NewBandeau.innerHTML = '<table id="TableBandeau_0" style="background-color: transparent; display: block;"></table>';
      if( ["monobook","chick","myskin","simple","vector"].indexOf(mw.config.get('skin')) != -1 ){
            var ContentSub = document.getElementById('contentSub');
            Content.insertBefore(NewBandeau, ContentSub.nextSibling);
      }else if(mw.config.get('skin')=="modern"){
            var ContentSub = Content.firstChild;
            Content.insertBefore(NewBandeau, ContentSub.nextSibling);
      }else if(mw.config.get('skin')=="cologneblue"){
            var ContentSub = Content.getElementsByTagName('p')[0];
            Content.insertBefore(NewBandeau, ContentSub.nextSibling);
      }else if(mw.config.get('skin')=="standard"){
            var ContentSub = document.getElementById('catlinks');
            Content.insertBefore(NewBandeau, ContentSub.nextSibling);
      }else if(mw.config.get('skin')=="nostalgia"){
            Content.insertBefore(NewBandeau, Content.firstChild);
      }
      BandeauxEbauches_ModifyBandeau(0, ListeBandeaux);
}

window.BandeauxEbauches_ModifyBandeau = function(BandeauCount, ListeBandeaux){
      var Table = document.getElementById('TableBandeau_'+BandeauCount);
      Table.style.display = "none";
      var NewDivBandeau = document.createElement('div');
      NewDivBandeau.id = 'DivBandeau_'+BandeauCount;
      Table.parentNode.insertBefore(NewDivBandeau, Table);
      var Liste = '';
      var AllBandeaux = new Array();
      for(var a=0;a<BandeauxEbauches_MaxParams;a++){
            if(ListeBandeaux[a]){
                  AllBandeaux[a] = ListeBandeaux[a];
                  Liste += 'SPLIT'+ ListeBandeaux[a];
            }else{
                  AllBandeaux[a] = '';
            }
      }
      Liste = encodeURIComponent(Liste.replace(/'/g, "ZAPOSTROPHE"));
      var Boutons = '<input type="button" onclick="BandeauxEbauches_Edit(\''+BandeauCount+'\',\''+Liste+'\');" onselect="BandeauxEbauches_Edit(\''+BandeauCount+'\',\''+Liste+'\');" value="Valider"/>'
                  + '<input type="button" onclick="BandeauxEbauches_Cancel(\''+BandeauCount+'\',\''+Liste+'\')" onselect="BandeauxEbauches_Cancel(\''+BandeauCount+'\')" value="Annuler"/>';
      var Explication = '<strong><label for"FormBandeau_'+BandeauCount+'">Sélectionner les bandeaux d\'ébauche à apposer.</label></strong>';
      if(BandeauxEbauches_ListeBas){
            var TopForme = Explication + '&nbsp;&nbsp;' + Boutons;
            var BottomForme = '';
      }else{
            var TopForme = '';
            var BottomForme = Explication + '&nbsp;&nbsp;' + Boutons;
      }
      var NewDivBandeauHTML = '<form id="FormBandeau_'+BandeauCount+'">';
      NewDivBandeauHTML += TopForme + '<br/>';
      for(var a=0;a<BandeauxEbauches_MaxParams;a++){
           NewDivBandeauHTML += '<select id="SelectBandeau_'+BandeauCount+'_'+a+'" style="display:none;" title="Suggestions de bandeaux" />'
                              + '<input id="InputBandeau_'+BandeauCount+'_'+a+'" type="text" value="'+AllBandeaux[a]+'" onkeyup="BandeauxEbauches_TextChanged('+BandeauCount+','+a+')" />';
      }
      NewDivBandeauHTML += '<br/>' + BottomForme ;
      NewDivBandeauHTML += '</form>';
      NewDivBandeau.innerHTML = NewDivBandeauHTML;
      document.getElementById('InputBandeau_0_0').focus();
      for(var a=0;a<ListeBandeaux.length;a++){
            BandeauxEbauches_TextChanged(BandeauCount,a);
      }
}

window.BandeauxEbauches_Cancel = function(id, Liste){
      var BandeauTable = document.getElementById('TableBandeau_'+id);
      BandeauTable.style.display = 'block';
      var BandeauDiv = document.getElementById('DivBandeau_'+id);
      BandeauDiv.parentNode.removeChild(BandeauDiv);
      if(Liste=='')BandeauTable.parentNode.parentNode.removeChild(BandeauTable.parentNode);
}


////////////////////////////////////////////////////////////////////////////////////////// SUGGESTIONS

window.BandeauxEbauches_TextChanged_running = new Array ;
for(var run=0;run<BandeauxEbauches_MaxParams;run++){
     BandeauxEbauches_TextChanged_running[run] = 0;
}
window.BandeauxEbauches_Edit_running = 0;

window.BandeauxEbauches_TextChanged = function(id1, id2){
     if( ( BandeauxEbauches_TextChanged_running[id2])||(BandeauxEbauches_Edit_running) ) return ;
     var idSelect= 'SelectBandeau_' + id1 + '_' + id2;
     var idInput = 'InputBandeau_' + id1 + '_' + id2;
     var Select = document.getElementById(idSelect ) ;
     var Input = document.getElementById(idInput) ;
     if((!Input)||(!Select)) return;
     var Value = Input.value;
     if(Value==''){ Select.style.display = 'none'; return; }
     BandeauxEbauches_TextChanged_running[id2] = 1;
     var URL = mw.config.get( 'wgServer' ) + mw.config.get( 'wgScriptPath' ) + '/api.php?format=xml&action=query&list=allpages&apnamespace=10&aplimit='+BandeauxEbauches_TailleListe+'&apfrom=Ébauche/paramètres%20'+encodeURIComponent(Value)+'&continue=';
     BandeauxEbauches_ajax.http({url       : URL, 
                                 onSuccess : BandeauxEbauches_UpdateSelect,
                                 id1       : id1,
                                 id2       : id2
     });
}

window.BandeauxEbauches_UpdateSelect = function(Req, data){
     var id1 = data.id1;
     var id2 = data.id2;
     var idSelect= 'SelectBandeau_' + id1 + '_' + id2;
     var idInput = 'InputBandeau_' + id1 + '_' + id2;
     var Select = document.getElementById(idSelect ) ;
     var Input = document.getElementById(idInput) ;
     if((!Input)||(!Select)) return;
     var Value = Input.value;
     Select.innerHTML = '';
     var Infos = Req.responseXML;
     var NbOptions = 0;
     var P = Infos.getElementsByTagName('p');
     for(var a=0;a<P.length;a++){
          var ThisP = P[a];
          var TitrePage = ThisP.getAttribute('title')
          TitrePage = TitrePage.split('Ébauche/paramètres')[1].split('"')[0];
          TitrePage = TitrePage.replace(/^ /,'');
          TitrePageEncode = TitrePage.replace(/'/g,"ZAPOSTROPHE");
          Select.innerHTML +=  '<option value="'+TitrePage+'" '
                                      +'onclick="BandeauxEbauches_TextChanged_Set(\''+idInput+'\', \''+TitrePageEncode+'\'); '
                                      +'BandeauxEbauches_TextChanged(\''+id1+'\',\''+id2+'\');" '
                                      +'>'+TitrePage+'</option>';
          NbOptions++;
     }
     if(NbOptions>0){
          Select.onchange = function(){
               var Selected = this.getElementsByTagName('option');
               for(var a=0;a<Selected.length;a++){
                    if(Selected[a].selected){
                         var TextSelected = Selected[a].value;
                         document.getElementById(idInput).value = TextSelected;
                         //setTimeout("BandeauxEbauches_TextChanged(\''+id1+'\', \''+id2+'\');", BandeauxEbauches_KeyboardDelay*1000);
                    }
               }
          };
          Select.size = NbOptions;
          Select.style.display = 'inline';
          Select.style.zIndex = 5 ;
          Select.style.position = "absolute" ;
          Input.style.width = Select.offsetWidth + "px" ;
          if(BandeauxEbauches_ListeBas){
               Select.style.top = (parseInt(Input.offsetTop) + parseInt(Input.offsetHeight)) + 'px';
          }else{
               Select.style.top = (parseInt(Input.offsetTop) - Select.offsetHeight) + 'px';
          }
          Select.style.left = (parseInt(Input.offsetLeft ) - 1) + 'px';
     }else{
          Select.style.display = 'none';
          Select.innerHTML = '';
     }
     for(var a=0;a<BandeauxEbauches_MaxParams;a++){
          var AllSelect= document.getElementById('SelectBandeau_' + id1 + '_' + a);
          var AllInput = document.getElementById('InputBandeau_' + id1 + '_' + a);
          AllSelect.style.left = (parseInt(AllInput.offsetLeft ) - 1) + 'px';
     }
     BandeauxEbauches_TextChanged_running[id2] = 0;
}

window.BandeauxEbauches_TextChanged_Set = function(id, text){
     text = text.replace(/ZAPOSTROPHE/g,"'");
     document.getElementById(id).value = text;
     document.getElementById(id).focus() ;
}

////////////////////////////////////////////////////////////////////////////////////////// EDITION

window.BandeauxEbauches_Edit = function(id, OldListe, Supprimer){
      OldListe = decodeURIComponent(OldListe).replace(/ZAPOSTROPHE/g, "'").replace(/SPLIT/g, "|");
      var OldModele = '{{Ébauche' + OldListe + '}}';
      var NewModele = '';
      if(!Supprimer){
            NewModele += '{{Ébauche';
            var BandeauForm = document.getElementById('FormBandeau_'+id);
            var Inputs = BandeauForm.getElementsByTagName('input');
            for(var a=0;a<Inputs.length;a++){
                  if(Inputs[a].type == "text"){
                        var InputValue = Inputs[a].value;
                        if(InputValue !=''){
                              NewModele += '|' + InputValue;
                        }
                  }
            }
            NewModele += '}}\n';
            if(NewModele.indexOf('|')==-1){
                   NewModele = '';
            }
      }
      var SurEtCertain = confirm(OldModele + ' -> ' + NewModele + '\n\nOK ?');
      if(!SurEtCertain){ BandeauxEbauches_Cancel(id, OldListe); return; }
      for(var run=0;run<BandeauxEbauches_MaxParams;run++){
            BandeauxEbauches_TextChanged_running[run] = 1;
      }
      BandeauxEbauches_Edit_running = 1;
      var URL = mw.config.get( 'wgServer' ) + mw.config.get( 'wgScript' ) + '?title=' + encodeURIComponent(mw.config.get( 'wgPageName' )) + '&action=edit&section=0';
      BandeauxEbauches_ajax.http({url          : URL, 
                                  onSuccess    : BandeauxEbauches_DoEdit,
                                  oldtemplate  : OldModele,
                                  newtemplate  : NewModele
      });
}

window.BandeauxEbauches_DoEdit = function(Req, data){
      var OldModele = data.oldtemplate;
      var NewModele = data.newtemplate;
      while(document.body.firstChild){ document.body.removeChild(document.body.firstChild); }
      document.body.innerHTML = Req.responseText;
      if(BandeauxEbauches_AutoEdit) document.editform.style.display = 'none';

      var OldText = document.getElementById('wpTextbox1').value;

      OldText = OldText.replace(/\{\{ébauche/g, "\{\{Ébauche");
      OldText = OldText.replace(/\{\{Ébauche /g, "\{\{Ébauche\|");

      var BeforeModele = OldText.substring(0, OldText.indexOf('{{Ébauche|'));
      var Modele = OldText.substring(1, OldText.indexOf('{{Ébauche|'));
      var AfterModele = OldText.split(BeforeModele).join('').split(OldModele + '\n').join('');

      var TexteFinal = BeforeModele + NewModele + AfterModele;

      document.getElementById('wpMinoredit').checked = ( BandeauxEbauches_MinorEdit  ? "checked" : false );
      document.getElementById('wpTextbox1').value = TexteFinal;
      document.getElementById('wpSummary').value = 'Changement [[Modèle:Ébauche|{{Ébauche}}]] ; avec [[MediaWiki:Gadget-BandeauxEbauches.js|BandeauxEbauches]]';
      if(BandeauxEbauches_AutoEdit){
        var watchthisparam = {};
        watchthisparam[-1] = "nochange";
        watchthisparam[ 0] = "unwatch";
        watchthisparam[ 1] = "watch";
        var datas = {
              action    : 'edit',
              title     : mw.config.get('wgPageName'),
              section   : 0,
              text      : TexteFinal,
              summary   : document.editform.wpSummary.value,
              minor     : (document.editform.wpMinoredit.checked ? 1 : 0),
              watchlist : watchthisparam[BandeauxEbauches_Watchthis],
              token     : document.editform.wpEditToken.value
        };
        var ApplyTag = BandeauxEbauches_gettag();
        if(ApplyTag){
            datas.summary = 'Changement [[Modèle:Ébauche|{{Ébauche}}]]';
            datas.tags = ApplyTag;
        }
        var api = new mw.Api();
        api.post( datas, {'contentType':'application/x-www-form-urlencoded'} ).then( function ( data ) {
                  window.location.reload();
        });
      }
}

//</nowiki></pre></syntaxhighlight>