Jump to content

User:Alex brollo/eis.js

From Wikisource

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.
// versione dicembre 2018 - ripassata con JSLINT su Notepad++ (modifica parziale)
(function eisMain($, mw) {
 if (typeof alex === 'undefined') {
  alex = {};
} 
  //const alex = {};
  switch (mw.config.get('wgServerName')) {
    case 'la.wikisource.org':
      alex.nomeIndice = 'Liber';
      alex.nomePagina = 'Pagina';
      alex.indexFilter = '.prp-index-pagelist a';
      break;
    case 'wikisource.org':
      alex.nomeIndice = 'Index';
      alex.nomePagina = 'Page';
      alex.indexFilter = 'table table p a';
      break;
    case 'it.wikisource.org':
      alex.nomeIndice = 'Indice';
      alex.nomePagina = 'Pagina';
      alex.indexFilter = '#pagineDellEdizione a';
      break;
    case 'vec.wikisource.org':
      alex.nomeIndice = 'Indice';
      alex.nomePagina = 'Pagina';
      alex.indexFilter = '#pagineDellEdizione a';
      break;
    default:
      alex.nomeIndice = 'Index';
      alex.nomePagina = 'Page';
      alex.indexFilter = 'table table p a';
  }
  const eis = {};
  eis.cp = {};


  // console.log("passo 1");
  if (mw.config.get('wgCanonicalNamespace') !== 'Page' || mw.config.get('wgAction') !== 'edit') {
    // console.log('eis non eseguito');
    return false;
  }
  eis.base = /:(.+)\/\d+$/.exec(mw.config.get('wgPageName'))[1];
  eis.html = $.ajax({
    url: `/w/index.php?action=render&title=${alex.nomeIndice}:${eis.base}`,
    async: false,
  }).responseText;
  eis.indexLength = $(alex.indexFilter, $(eis.html)).length - 1;
  alex.eis=eis;
  // console.log("passo 2");


  /* passo 1 :  costruire l'ambiente */
  // in nsPage, and in edit mode, eis environment is built
  function activate() {
    // access button

    if (mw.user.options.get('gadget-barbaforcutanew') === null) {
      $('<li id="ca-eis"><span><a href="#" title="Attiva eis" >eis</a></span></li>').click(() => {
        $('#wptextbox1').css('font-size', '.9pc');
        creaEis();
        pp();
      }).insertAfter($('#ca-edit'));
      // loading wikitext of three pages
    } else {
      $('<button id="ca-eis" type="button">eis</button>').click(() => {
        $('#wpTextbox1').css('font-size', '.9pc');
        creaEis();
        pp();
      }).appendTo($('.editButtons'));
      // loading wikitext of three pages
    }

    return false;
  } // fine activate()

  // initializing function, it disables some buttons, builds preview box, build action buttons
  function creaEis() {
    // disabilitazioni
    $('#ca-proofreadPagePrevLink a, #ca-proofreadPageNextLink a').remove();
    $('#wpSave, #wpPreview, #wpDiff, #wikiPreview').remove();
    $('.mw-summary, .editCheckboxes').remove();
    $('#ca-eis').remove();

    $('body').append('<div id="findReplaceEis_box" style="display:none; font-size:90%; width:500px;position:fixed; z-index:1500;top:0px;right:0px;background-color:white;border:2px solid #0645AD;padding:10px">' +
   '<div style="float:left">Cerca testo:</div>' +
   '<div style="float:right"><input type="text" id="findReplaceEis_find" size="30" style="background-color:#efefef" readonly/></div>' +
   '<div style="clear:both;float:left">Sostituisci con: </div>' +
   '<div style="float:right"><input type="text" id="findReplaceEis_replace" size="30"/></div>' +
   '<div style="clear:both;float:left">' +
   '<div style="float:right;margin-top:10px;"><input type="button" id="findReplaceEis_ok"  value="OK"/></div>');


    const box = $("<div id='editBoxEis' style='background-color:#dfdfdf; min-height:10px; display:inline-block;position:fixed; top:0; left:0; z-index:100' ></div>");

    if (mw.user.options.get('gadget-barbaforcutanew') === null) {
      box.resizable();
      $('#content').append(box);
    } else {
      box.css('position', 'static').appendTo($('.editButtons'));
    }


    let qb = '<span id="radiobuttons">' +
   '<span class="quality0"><input tabindex="5" title="Pagine_SAL_00%" type="radio" value="0" name="wpQuality"></span>' +
   '<span class="quality2"><input tabindex="6" title="Pagine_SAL_50%" type="radio" value="2" name="wpQuality"></span>' +
   '<span class="quality1"><input tabindex="7" title="Pagine_SAL_25%" type="radio" value="1" name="wpQuality"></span>' +
   '<span class="quality3"><input tabindex="8" title="Pagine_SAL_75%" checked="" type="radio" value="3" name="wpQuality"></span>' +
   '<span id="radioQuality4" class="quality4" style="visibility:hidden;"><input tabindex="9" title="Pagine_SAL_100%" type="radio" value="4" name="wpQuality">&nbsp;&nbsp;</span></span>';

    qb += '<span>&nbsp;&nbsp;' +
   '<button class="baseButton" id="wpPrev" style="display: inline; padding: 1px 2px;" type="button" title="Vai alla pagina precedente" ><small>&lt;</small></button>' +
   '<button class="baseButton" id="wpNext" style="display: inline; padding: 1px 2px;" type="button" title="Vai alla pagina successiva" ><small>&gt;</small></button>' +
   '<button class="baseButton" id="wpSaveStay" style="display: inline; padding: 1px 2px;" type="button" title="Salva le modifiche" ><small>Salva</small></button>' +
   '<button class="baseButton" id="wpSave" style="display: inline; padding: 1px 2px;" type="button" title="Salva le modifiche e apri la pagina successiva" ><small>Salva e procedi</small></button>' +
   '<button class="baseButton" id="wpPreview" style="display: inline; padding: 1px 2px;" type="button" title="Visualizza anteprima" ><small>Anteprima</small></button>' +
   '<button class="baseButton" id="wpWikitext" style="display: none; padding: 1px 2px;" type="button" title="Visualizza anteprima" ><small>Wikitesto</small></button>' +
   // '<button class="baseButton" id="wpExit" style="display: inline; padding: 1px 2px;" type="button" title="Annulla e chiudi" ><small>Annulla</small></button>'+
   '&nbsp;<input type="text" id="wpComment" value="Ajax eis edit" size="25"></span>' +
   '<img alt="✔" src="//upload.wikimedia.org/wikipedia/commons/thumb/f/fb/Yes_check.svg/15px-Yes_check.svg.png" style="width:px; height:15px;display:none" id="ok_img"/> ';
    $('#editBoxEis').append($(qb));

    $("span[class^='quality'] input").click(function () {
      $('#wpComment').val(`/* new eis level${$(this).attr('value')} */`);
    });

    $('#wpExit').click(() => {
      window.open(`/wiki/${eis.cp.title}`, '_self');
    });
    $('#wpSave').click(() => {
      pageSave(1);
    });
    $('#wpSaveStay').click(() => {
      pageSave(0);
    });
    $('#wpPreview').click(() => {
      // pp(prevPage());

      $('#divPreview').css('display', 'block');
      $('#wpPreview').css('display', 'none');
      $('#wpWikitext').css('display', 'inline');
      pagePreview();
    });
    $('#wpWikitext').click(() => {
      // pp(prevPage());

      $('#divPreview').css('display', 'none');
      $('#wpPreview').css('display', 'inline');
      $('#wpWikitext').css('display', 'none');
    });

    $('#wpPreviewSave').click(() => {
      pagePreview();
    });
    $('#wpPrev').click(() => {
      pp(prevPage());
    });
    $('#wpNext').click(() => {
      // $("#divPreview").css("display","none");
      pp(nextPage());
    });
    // creazione box divPreview
    const divPreview = $('<div>').css({
      position: 'absolute',
      top: '0',
      left: '0',
      width: '100%',
      height: $('.prp-page-image').css('height'),
      overflow: 'auto',
      padding: '10px',
      'z-index': '150',
      'background-color': 'white',
      border: '1px solid black',
      display: 'none',
    }).attr('id', 'divPreview')
    // .dblclick(function() {$("#divPreview").toggle();})
      .append($('<div>').attr('id', 'previewContent'));
    $('<div>').attr('style', 'position:absolute; top:0;right:0;cursor:pointer; z-index:200;')
      .append($('<button class="baseButton" id="wpPreviewExit" style="display: inline; padding: 1px 2px;" type="button" title="Chiudi" ><small>Annulla</small></button>').click(() => { $('#divPreview').toggle(); }));

    $('.prp-page-content').css('position', 'relative').append(divPreview);

    $('#previewContent').mouseup(() => {
      const text = $.trim(getSelectedText());

      //
      if (text !== '') {
        /* $("#findReplaceEis_box").css("display","block");
       $("#findReplaceEis_find").val(text);
       $("#findReplaceEis_replace").val(text).focus(); */
        $('#inputField').remove();
        const s = getSelection();
        const r = s.getRangeAt(0).getBoundingClientRect();
        $('<input>').attr('id', 'inputField').attr('type', 'text')
          .css({
            position: 'fixed', top: r.y - 3, left: r.x, height: r.height, width: r.width,
          })
          .val(text)
          .appendTo($('.pagetext'));
        $('#inputField').focus();
        $('#inputField').keyup((event) => {
          const keycode = event.keyCode || event.which;
          if (keycode === '13') {
            gestisciInput(text);
          }
          if (keycode === '27') {
            $('#inputField').remove();
          }
        }).focusout(() => { gestisciInput(text); });
      }
    });

    function gestisciInput(oldText) {
      const newText = $('#inputField').val();
      if (newText !== oldText) {
        scriviBox(leggiBox().replace(oldText, newText));
      }
      $('#inputField').remove();
      pagePreview();
    }

    eis.baseImg = $('.prp-page-image img').attr('src').match(/(.+page)\d+(-\d+px.+)/);
 
/* eis.baseImg[1]+[numero pagina]+eis.baseImg[2] è l'url dell'immagine
     della pagina [numero pagina)]
     può essere caricato con
     $(".prp-page-image img").attr("src",eis.baseImg[1]+211+eis.baseImg[2]);
*/
  } // fine creaEis()
  
  // build name of next page
  function nextPage() {
    const np = eis.cp.title.match(/(.+\/)(\d+)$/);
    if (np[2] === eis.indexLength - 1) $('#wpNext').css('display', 'none'); else $('#wpNext').css('display', 'inline');
    return np[1] + ((np[2] * 1) + 1);
  } // fine nextPage()
  
  // build name of prevous page
  function prevPage() {
    const np = eis.cp.title.match(/(.+\/)(\d+)$/);
    if (np[2] === 2) $('#wpPrev').css('display', 'none'); else $('#wpNext').css('display', 'inline');
    return np[1] + ((np[2] * 1) - 1);
  } // fine prevPage()
  
  // splits wiki code into header,body,footer
  function splitPagina(tpp) {
    const testo = ['', '', ''];
    testo[0] = tpp.substring(0, tpp.indexOf('</noinclude>') + 12);
    testo[2] = tpp.substring(tpp.lastIndexOf('<noinclude>'));
    testo[1] = tpp.substring(testo[0].length, tpp.length - testo[2].length);
    return testo;
  } // fine splitPagina
  
  // reads three pages code (current, previous, previous of previous)
  function pp(pageName) {
    if (pageName === undefined) pageName = mw.config.get('wgPageName');
    pageName = pageName.replace(/_/g, ' ');
    const pagine = {};
    const t = (/(.+\/)(.+)$/).exec(pageName);
    const t1 = (t[2] * 1) - 1;
    const t2 = (t[2] * 1) - 2;
    const pCor = pageName;
    const pPrec1 = t[1] + t1;
    const pPrec2 = t[1] + t2;
    // console.log(pPrec2,pPrec1,pCor);
    const api = new mw.Api();
    $('#firstHeading').text(`Modifica eis di ${pageName}`);
    // lettura di tre pagine

    api.get({
      action: 'query',
      prop: 'revisions',
      titles: `${pPrec2}|${pPrec1}|${pCor}`,
      rvprop: 'content',
    }).done((data) => {
      alex.query = data.query.pages;
      $.each(data.query.pages, (index, value) => {
        if (alex.query[index].missing !== undefined) { pagine[alex.query[index].title] = ['', '', '']; } else { pagine[alex.query[index].title] = splitPagina(alex.query[index].revisions[0]['*']); }
      });
      eis.p_2 = [pPrec2, pagine[pPrec2]];
      eis.p_1 = [pPrec1, pagine[pPrec1]];
      eis.p_0 = [pCor, pagine[pCor]];
      alex.p_2 = eis.p_2;
      alex.p_1 = eis.p_1;
      alex.p_0 = eis.p_0;
      testoPag2Prec = alex.p_2[1];
      testoPagPrec = alex.p_1[1];

      // settaggi comuni
      eis.cp.basePageName = t[1];
      eis.cp.basePageNum = t[2];
      eis.cp.title = eis.p_0[0];

      mw.config.set('wgTitle', eis.cp.title);
      mw.config.set('wgPageName', /.+\//.exec(mw.config.get('wgPageName'))[0] + eis.cp.basePageNum);

      // oscuramento next se ultima pagina e prev se prima
      if (eis.cp.basePageNum >= eis.indexLength) $('#wpNext').css('display', 'none'); else $('#wpNext').css('display', 'inline');
      if (eis.cp.basePageNum === 1) $('#wpPrev').css('display', 'none'); else $('#wpPrev').css('display', 'inline');

      // modifica link Leggi e Modifica
      if ($('#ca-view a').length === 1) {
        eis.cp.linksUrl = $('#ca-view a').attr('href').replace(/\d+$/, eis.cp.basePageNum);
        $('#ca-view a').attr('href', eis.cp.linksUrl);
        $('#ca-edit a').attr('href', eis.cp.linksUrl);
      }


      let urlpc = /.+\//.exec($('#ca-nstab-page a').attr('href'))[0] + eis.cp.basePageNum;
      $('#ca-nstab-page a').attr('href', urlpc).attr('target', '_blank');
      urlpc = /.+\//.exec($('#ca-talk a').attr('href'))[0] + eis.cp.basePageNum;
      $('#ca-talk a').attr('href', urlpc).attr('target', '_blank');
      if ($('#croptool').length > 0) {
        eis.cp.croptool = $('#t-cropNew a').attr('href').replace(/\d+$/, eis.cp.basePageNum);
        $('#t-cropNew a').attr('href', eis.cp.croptool);
      }
      const urlImg = $('.prp-page-image img').attr('src').match(/(.+page)(\d+)(-.+)/);
      eis.cp.imageUrl = urlImg[1] + eis.cp.basePageNum + urlImg[3];

      // assegno valori alle variabili globali testoPagPrec e testo2PagPrec per renderli visibili a autoPt e autoRi7
      testoPagPrec = eis.p_1[1];
      testo2PagPrec = eis.p_2[1];
      $('#radioQuality4').css('visibility', 'hidden');
      $('.prp-page-image img').attr('src', eis.cp.imageUrl);

      if (eis.p_0[1].toString() === ',,') {
        // caso pagina corrente non esistente
        // leggo la pagina...
        $.get(`${mw.config.get('wgServer')}/w/index.php?title=${mw.config.get('wgPageName')}&action=edit&redlink=1`, (data) => {
          $('#wpTextbox1').val($('#wpTextbox1', $(data)).val());


          eis.cp.header = '';
          eis.cp.footer = '';
          $('#wpHeaderTextbox').val(eis.cp.header);
          $('#wpFooterTextbox').val(eis.cp.footer);

          // eseguo autoRi, Rv, postOcr, regex
          // preOCR();
          $('#buttonautoRi').click();
          $('#buttonpostOCR').click();
          // $("#button6").click();
          $('#buttonRunregex').click();
          eis.p_0[1][1] = $('#wpTextbox1').val();
          eis.cp.user = mw.config.get('wgUserName');
          eis.cp.level = '1';
          $(`#radiobuttons input[value='${eis.cp.level}']`).click();
          pagePreview();
        });
      } else {
        // caso pagina esistente
        eis.cp.user = eis.p_0[1][0].match(/user="([^"]*)" \/>/)[1];
        eis.cp.level = eis.p_0[1][0].match(/level="(\d+)" /)[1];
        eis.cp.header = $.trim(eis.p_0[1][0].replace(/<noinclude\><pagequality.+?>/, '').replace('</noinclude>', ''));
        eis.cp.footer = $.trim(eis.p_0[1][2].replace('<noinclude>', '').replace('<references/>', '').replace('</noinclude>', ''));
        $('#wpHeaderTextbox').val(eis.cp.header);
        $('#wpFooterTextbox').val(eis.cp.footer);
        $('#wpTextbox1').val(eis.p_0[1][1]);

        // if level=3 and user is another one, or if level=4 display radiobutton4
        if ((eis.cp.level === '3' && eis.cp.user !== mw.config.get('wgUserName')) || eis.cp.level === '4') $('#radioQuality4').css('visibility', 'visible');

        $(`#radiobuttons input[value='${eis.cp.level}']`).click();
        pagePreview();
      }
    });
    $('.prp-page-image img').css('top', '0');
    $('#wpTextbox1').scrollTop(0);
  } // fine pp()
  
  function chiudiEditBox() {
    $('#sfondoeis').toggle();
  } // fine chiudiEditBox
  
  // build wikitext of whole page (header, body, footer)
  function pageBuild() {
    const template = '<noinclude><pagequality level="#LEVEL#" user="#USER#" />#HEADER#</noinclude>' +
  '#BODY#<noinclude>#FOOTER#\n</noinclude>';
    let wikicode = template.replace('#HEADER#', $('#wpHeaderTextbox').val())
      .replace('#BODY#', $('#wpTextbox1').val())
      .replace('#FOOTER#', $('#wpFooterTextbox').val());
    if (eis.cp.level === $('input:checked', '#radiobuttons').val()) {
      wikicode = wikicode.replace('#LEVEL#', eis.cp.level).replace('#USER#', eis.cp.user);
    } else {
      wikicode = wikicode.replace('#LEVEL#', $('input:checked', '#radiobuttons').val())
        .replace('#USER#', mw.config.get('wgUserName'));
    }

    return wikicode;
  } // fine pageBuid()

  // saves page
  function pageSave(azione) {
    const wikicode = pageBuild();
    new mw.Api().postWithToken('edit', {
      action: 'edit',
      title: eis.cp.title,
      summary: $('#wpComment').val(),
      text: wikicode,
    }).done((data) => {
      if (data && data.edit && data.edit.result === 'Success') {
        $('#ok_img').toggle();
        setTimeout(() => {
          $('#ok_img').toggle();
        }, 500);
        if (azione === 1 && eis.cp.basePageNum < eis.indexLength) $('#wpNext').click();
        if (azione === -1) $('#wpPrev').click();
      } else {
        alert('Errore nel salvataggio della pagina');
      }
    });
  } // fine pageSave()
  
  // displays preview
  function pagePreview() {
    // caricamento preview
    const wikicode = pageBuild();
    $.ajax({
      url: mw.util.wikiScript('api'),
      data: {
        format: 'json',
        action: 'parse',
        title: eis.cp.title,
        summary: 'ajax preview',
        text: wikicode,
        time: $.now(),
      },
      dataType: 'json',
      type: 'POST',
      success(data) {
        if (data && data.parse) {
          $('#previewContent').html($(data.parse.text['*']));
        } else if (data && data.error) {
          alert(`Error: API returned error code "${data.error.code}": ${data.error.info}`);
        } else {
          alert('Error: Unknown result from API.');
        }
      },
      error(xhr) {
        alert('Error: Request failed.');
      },
    });
  } // fine pagePreview()
  mw.pagePreview = pagePreview;

  // text selection from html view
  function getSelectedText() {
    if (window.getSelection) {
      return window.getSelection().toString();
    } else if (document.selection) {
      return document.selection.createRange().text;
    }
    return '';
  }
  activate();
  return false;
}(jQuery, mw));