User:YFdyh000/langlinks replace.js

注意:保存之后,你必须清除浏览器缓存才能看到做出的更改。Google ChromeFirefoxMicrosoft EdgeSafari:按住⇧ Shift键并单击工具栏的“刷新”按钮。参阅Help:绕过浏览器缓存以获取更多帮助。
//based on [[User:喵/langlinks_replace.js]]

// To apply this script on the current article, open the EDIT page of the article, and use this bookmarklet:
// javascript:importScriptURI("https://zh.wikipedia.org/w/index.php?title=User:%E5%96%B5/langlinks_replace.js&action=raw");
// After quries, the wikilinks in the editbox will be replaced by its corresponding article in ZHWP.
// Please do NOT save the replaced article. Instead, copy the content to ZHWP.
// <nowiki>
(function (mw, $) {
  var api = new mw.Api();
  var wlregex = /\[\[([^:|\]]+)(\|[^\]]*)?\]\]/g;
  var map = {};
  var requests = [];
  var current = 0;
  var textbox = $('#wpTextbox1');
  var wikitext = textbox.val();
  if (textbox.length === 0) {
    alert('This script must be run on the EDIT page.');
    return;
  }
  var request_langlink = function (articles, opt_llcontinue) {
  	var req = {
      action: 'query',
      format: 'json',
      titles: articles.join('|'),
      prop: 'langlinks',
      redirects: 'follow',
      lllimit: '500',
    };
    req = $.extend({}, req, opt_llcontinue); // or Object.assign()
    return api.get(req);
  };
  var query_complete = function (data) {
  	var sitecode = window.location.host.split(".")[0];
    var pages = data.query.pages;
    for (var p in pages)
    {
      var ll = pages[p].langlinks;
      for (var i in ll) {
        if (ll[i].lang == "zh") {
          map[pages[p].title] = ll[i]["*"];
        }
      }
    }
    var redirects = data.query.redirects;
    if (redirects) {
      for (var i in redirects) {
        map[redirects[i].from] = map[redirects[i].to];
      }
    }
    var norm = data.query.normalized;
    if (norm) {
      for (var i in norm) {
        map[norm[i].from] = map[norm[i].to];
      }
    }
    // todo: check {{Lowercase}}, like iOS, macOS, etc.
    if (data["continue"]) {
      request_langlink(
          requests[current],
          data["continue"]
      ).done(query_complete);
    } else {
      current++;
      if (current >= requests.length) {
        var result = wikitext.replace(
          wlregex,
          function (s) {
            //debugger;
            // tools: http://www.regexr.com/ and http://www.debuggex.com for review regex
            // Example: [[JavaServer Pages|JSP]]
            // q got: Array [ "[[JavaServer Pages|JSP]]", "JavaServer Pages", "|JSP" ]
            var q = /\[\[([^:|\]]+)(\|[^\]]*)?\]\]/g.exec(s); // new same regex for avoid touching exec();
            var re = map[q[1]]; // re got: "JSP"
            //if (!re) return s;
            // ref: {{le}}, {{link-en}}, etc.
            if (!re) return s.replace(/\[\[(.+?)\]\]/, '{{tsl|' + sitecode + '|$1}}');
            if (q[2] && q[2].replace('|', '') == re) return s.replace(q[1] + '|', ''); // keep one only if s1 and s2 are same string.
            return s.replace(q[1], re); // replace the target page to localized pages
          }
        );
        $('#wpTextbox1').val(result);
        $('#wpSave').attr('disabled', true); // todo: response to undo action.
        alert("Done!");
      } else {
        request_langlink(requests[current], {}).done(query_complete);
      }
    }
  };

  // todo: improve or refactoring
  // todo: can't ingest pagetitle like "xx: xx". how to resolve namespaces.
  var match = wlregex.exec(wikitext);
  var t = [];
  while (match !== null) {
    t.push(match[1]);
    match = wlregex.exec(wikitext);
  }
  var chunk = 50;
  while (t.length > 0)
    requests.push(t.splice(0, chunk));
  //console.log(requests,current)
  request_langlink(requests[current], {}).done(query_complete);
})(mediaWiki, jQuery);
// </nowiki>