Jump to content

User:Diegodlh/Web2Cit/script.js

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Diegodlh (talk | contribs) at 20:25, 4 May 2022. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
window.web2cit = {
  enable: function() {
    console.log("Enabling Web2Cit...");
    patchAjax();
    patchBuildTemplateResults();
  },
  disable: function() {
    console.log("Disabling Web2Cit...");
    unpatchAjax();
    unpatchBuildTemplateResults();
  },
  unpatched: {}
};

function patchInitialize() {
  window.web2cit.unpatched.initialize = ve.ui.CitoidInspector.prototype.initialize;
  ve.ui.CitoidInspector.prototype.initialize = function () {
    window.web2cit.unpatched.initialize.bind(this)();
    const disabled = localStorage.getItem("web2cit.disabled") === "true";
    const toggle = new OO.ui.ToggleSwitchWidget({
    // const toggle = new OO.ui.CheckboxInputWidget({
      value: !disabled
    });
    const field = new OO.ui.FieldLayout( toggle, {
      align: 'left',
      label: 'Web2Cit'
    } );
    toggle.on("change", (value) => {
      if (value) {
        localStorage.setItem("web2cit.disabled", "false");
        window.web2cit.enable();
      } else {
        localStorage.setItem("web2cit.disabled", "true");
        window.web2cit.disable();
      }
    })
    const parentElement = this.autoProcessPanels.lookup.$element;
    field.$element.insertAfter(parentElement.children().first());
  }
}

function patchAjax() {
  if (window.web2cit.unpatched.ajax) return;
  window.web2cit.unpatched.ajax = $.ajax;
  $.ajax = function(url, options) {
    // If url is an object, simulate pre-1.5 signature
    if ( typeof url === "object" ) {
      options = url;
      url = undefined;
    }
    // Force options to be an object
    options = options || {};
    
    url = url || options.url;
    const match = url.match(
      /^\/api\/rest_v1\/data\/citation\/mediawiki\/(?<search>.+)/
    );
    if (match !== null) {
      let { search } = match.groups;
      search = decodeURIComponent(search);
      
      // mimick citoid's CitoidService.js
      search = search.trim().toLowerCase();

      // if the query does not begin with either http:// or https://
      // only assume that the user meant a url if it follows the pattern
      // www.something.somethingelse
      // otherwise, we may miss DOIs, QIDs, PMCIDs, ISBNs or PMIDs
      // which are handled by Citoid differently
      // instruct the user to always add http:// or https:// at the beginning
      // to explicitly mean a url
      if (search.match(/^www\..+\..+/)) {
        search = "http://" + search;
      };
      if (
        search.match(/^https?:\/\/.+/) &&
        // to prevent an endless loop, continue using web2cit through citoid
        // if user explicitly asks to translate a web2cit url
        !search.match(/^https?:\/\/web2cit.toolforge.org\/.+/)
      ) {
        console.log('Search will be resolved using Web2Cit + Citoid...')
        url = "https://web2cit.toolforge.org/translate";
        options.data = {
          "citoid": "true",
          "format": "mediawiki",
          "url": search
        };
      }
    }
    return window.web2cit.unpatched.ajax.bind(this)(url, options);
  }  
}

function patchBuildTemplateResults() {
  if (window.web2cit.unpatched.buildTemplateResults) return;
  window.web2cit.unpatched.buildTemplateResults = ve.ui.CitoidInspector.prototype.buildTemplateResults;
  ve.ui.CitoidInspector.prototype.buildTemplateResults = function( searchResults ) {
    let url;
    let web2cit = false;
    for (const citation of searchResults) {
      let { source } = citation;
      if (source !== undefined) {
        if (!Array.isArray(source)) source = [ source ];
        if (source.includes('Web2Cit')) {
          url = citation.url;
          web2cit = true;
          break;
        }
      }
    }
    const credit = this.credit;
    const onLabelChange = function() {
      credit.off("labelChange", onLabelChange);
      console.log('Adding "Web2Cit" to credit label...');
      credit.setLabel($(
        `<div>${credit.label} & <a href="https://web2cit.toolforge.org/${url}" target="_blank">Web2Cit</a></div>`
      ));
    }
    if (web2cit) {
      credit.on("labelChange", onLabelChange);  
    }
    return window.web2cit.unpatched.buildTemplateResults.bind(this)(searchResults);
  }
}

function unpatchAjax() {
  if (!window.web2cit.unpatched.ajax) return;
  $.ajax = window.web2cit.unpatched.ajax;
  delete window.web2cit.unpatched.ajax;
}

function unpatchBuildTemplateResults() {
  if (!window.web2cit.unpatched.buildTemplateResults) return;
  ve.ui.CitoidInspector.prototype.buildTemplateResults = window.web2cit.unpatched.buildTemplateResults;
  delete window.web2cit.unpatched.buildTemplateResults;
}

patchInitialize();
if (!(localStorage.getItem("web2cit.disabled") === "true")) {
  window.web2cit.enable();
}