MediaWiki:Gadget-RefToolbar2.0.js

MediaWiki系统消息页面
/* eslint-disable no-loop-func, no-undef */
'use strict';

/* <nowiki> */
/**
 * SPDX-License-Identifier: CC-BY-SA-4.0
 * _addText: '{{Gadget Header|license=CC-BY-SA-4.0}}'
 *
 * @source <zh.wikipedia.org/wiki/MediaWiki:RefToolbar.js>
 */
// TODO: make autodate an option in the CiteTemplate object, not a preference
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
(function ($, mw) {
  // Global object
  // TODO:
  // * Remove this once the page is moved to a module 'ext.gadget.refToolbarDialogs' depending on 'ext.gadget.refToolbarBase'
  if (typeof CiteTB === 'undefined') {
    CiteTB = {
      Templates: {},
      // All templates
      Options: {},
      // Global options
      UserOptions: {},
      // User options
      DefaultOptions: {},
      // Script defaults
      ErrorChecks: {} // Error check functions
    };
  }

  // Only execute when editing/previewing wikitext pages
  // TODO: Remove tests already done by [[MediaWiki:Gadget-RefToolbar.js]]
  if (['edit', 'submit'].includes(mw.config.get('wgAction')) && mw.config.get('wgPageContentModel') === 'wikitext') {
    mw.util.addCSS('.cite-form-td { height: 0 !important; padding: 0.1em !important; }');

    // Default options, these mainly exist so the script won't break if a new option is added
    CiteTB.DefaultOptions = {
      'date format': '<year>-<zmonth>-<zdate>',
      'autodate fields': [],
      months: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
      modal: true,
      autoparse: false,
      expandtemplates: false
    };

    // Get an option - user settings override global which override defaults
    CiteTB.getOption = function (opt) {
      if (CiteTB.UserOptions[opt] !== undefined) {
        return CiteTB.UserOptions[opt];
      } else if (CiteTB.Options[opt] !== undefined) {
        return CiteTB.Options[opt];
      }
      return CiteTB.DefaultOptions[opt];
    };
    CiteTB.init = function () {
      /* Main stuff, build the actual toolbar structure
       * 1. get the template list, make the dropdown list and set up the template dialog boxes
       * 2. actually build the toolbar:
       * - A section for cites
       * -- dropdown for the templates (previously defined)
       * -- button for named refs with a dialog box
       * -- button for errorcheck
       * 3. add the whole thing to the main toolbar
       */
      if (typeof $('div[rel=cites]')[0] !== 'undefined') {
        // Mystery IE bug workaround
        return;
      }
      $('head').trigger('reftoolbarbase');
      var $target = $('#wpTextbox1');
      var temlist = {};
      for (var t in CiteTB.Templates) {
        if (Object.prototype.hasOwnProperty.call(CiteTB.Templates, t)) {
          var tem = CiteTB.Templates[t];
          var sform = CiteTB.escStr(tem.shortform);
          var actionobj = {
            type: 'dialog',
            module: "cite-dialog-".concat(sform)
          };
          var dialogobj = {};
          dialogobj["cite-dialog-".concat(sform)] = {
            resizeme: false,
            titleMsg: "cite-dialog-".concat(sform),
            id: "citetoolbar-".concat(sform),
            init: function init() {},
            html: tem.getInitial(),
            dialog: {
              width: Math.round($(window).width() * 0.8),
              open: function open() {
                $(this).html(CiteTB.getOpenTemplate().getForm());
                /** @param {jQuery.Event} e */
                $('.cite-prev-parse').on('click', function (e) {
                  e.preventDefault();
                  CiteTB.prevParseClick();
                });
              },
              buttons: {
                'cite-form-submit': function citeFormSubmit() {
                  var ref = CiteTB.getRef(false, true);
                  $(this).dialog('close');
                  $.wikiEditor.modules.toolbar.fn.doAction($(this).data('context'), {
                    type: 'encapsulate',
                    options: {
                      post: ref
                    }
                  }, $(this));
                },
                'cite-form-showhide': CiteTB.showHideExtra,
                'cite-refpreview': function citeRefpreview() {
                  var ref = CiteTB.getRef(false, false);
                  var template = CiteTB.getOpenTemplate();
                  var div = $("#citetoolbar-".concat(CiteTB.escStr(template.shortform)));
                  div.find('.cite-preview-label').show();
                  div.find('.cite-ref-preview').text(ref).show();
                  if (CiteTB.getOption('autoparse')) {
                    CiteTB.prevParseClick();
                  } else {
                    div.find('.cite-prev-parse').show();
                    div.find('.cite-prev-parsed-label').hide();
                    div.find('.cite-preview-parsed').html('');
                  }
                },
                'wikieditor-toolbar-tool-link-cancel': function wikieditorToolbarToolLinkCancel() {
                  $(this).dialog('close');
                },
                'cite-form-reset': function citeFormReset() {
                  CiteTB.resetForm();
                }
              }
            }
          };
          try {
            $target.wikiEditor('addDialog', dialogobj);
          } catch (_unused) {}
          // TypeError: range is null
          // if (!CiteTB.getOption('modal')) {
          // $('#citetoolbar-'+sform).dialog('option', 'modal', false);
          // }
          temlist[sform] = {
            label: tem.templatename,
            action: actionobj
          };
        }
      }
      var refsection = {
        sections: {
          cites: {
            type: 'toolbar',
            labelMsg: 'cite-section-label',
            groups: {
              template: {
                tools: {
                  template: {
                    type: 'select',
                    labelMsg: 'cite-template-list',
                    list: temlist
                  }
                }
              },
              namedrefs: {
                labelMsg: 'cite-named-refs-label',
                tools: {
                  nrefs: {
                    type: 'button',
                    action: {
                      type: 'dialog',
                      module: 'cite-toolbar-namedrefs'
                    },
                    icon: '//youshou.wiki/images/thumb/b/be/Nuvola_clipboard_lined.svg/24px-Nuvola_clipboard_lined.svg.png',
                    section: 'cites',
                    group: 'namedrefs',
                    labelMsg: 'cite-named-refs-button'
                  }
                }
              },
              errorcheck: {
                labelMsg: 'cite-errorcheck-label',
                tools: {
                  echeck: {
                    type: 'button',
                    action: {
                      type: 'dialog',
                      module: 'cite-toolbar-errorcheck'
                    },
                    icon: '//youshou.wiki/images/a/a3/Nuvola_apps_korganizer-NO.png',
                    section: 'cites',
                    group: 'errorcheck',
                    labelMsg: 'cite-errorcheck-button'
                  }
                }
              }
            }
          }
        }
      };
      var defaultdialogs = {
        'cite-toolbar-errorcheck': {
          titleMsg: 'cite-errorcheck-label',
          id: 'citetoolbar-errorcheck',
          resizeme: false,
          init: function init() {},
          html: "<div id=\"cite-namedref-loading\"> <img src=\"https://youshou.wiki/images/d/de/Ajax-loader.gif\" /> &nbsp;".concat(mw.usability.getMsg('cite-loading'), "</div>"),
          dialog: {
            width: Math.round($(window).width() * 0.8),
            open: function open() {
              CiteTB.loadRefs();
            },
            buttons: {
              'cite-errorcheck-submit': function citeErrorcheckSubmit() {
                var errorchecks = $("input[name='cite-err-test']:checked");
                var errors = [];
                var _iterator = _createForOfIteratorHelper(errorchecks),
                  _step;
                try {
                  for (_iterator.s(); !(_step = _iterator.n()).done;) {
                    var errorcheck = _step.value;
                    errors = errors.concat(CiteTB.ErrorChecks[$(errorcheck).val()].run());
                  }
                } catch (err) {
                  _iterator.e(err);
                } finally {
                  _iterator.f();
                }
                CiteTB.displayErrors(errors);
                $(this).dialog('close');
              },
              'wikieditor-toolbar-tool-link-cancel': function wikieditorToolbarToolLinkCancel() {
                $(this).dialog('close');
              }
            }
          }
        },
        'cite-toolbar-namedrefs': {
          titleMsg: 'cite-named-refs-title',
          resizeme: false,
          id: 'citetoolbar-namedrefs',
          html: "<div id=\"cite-namedref-loading\"> <img src=\"//youshou.wiki/images/d/de/Ajax-loader.gif\" /> &nbsp;".concat(mw.usability.getMsg('cite-loading'), "</div>"),
          init: function init() {},
          dialog: {
            width: Math.round($(window).width() * 0.8),
            open: function open() {
              CiteTB.loadRefs();
            },
            buttons: {
              'cite-form-submit': function citeFormSubmit() {
                var refname = $('#cite-namedref-select').val();
                if (refname === '') {
                  return;
                }
                $(this).dialog('close');
                $.wikiEditor.modules.toolbar.fn.doAction($(this).data('context'), {
                  type: 'encapsulate',
                  options: {
                    post: CiteTB.getNamedRef(refname, true)
                  }
                }, $(this));
              },
              'wikieditor-toolbar-tool-link-cancel': function wikieditorToolbarToolLinkCancel() {
                $(this).dialog('close');
              }
            }
          }
        }
      };
      try {
        $target.wikiEditor('addDialog', defaultdialogs);
      } catch (_unused2) {
        // error occurred setting up wikieditor.
      }
      $('#citetoolbar-namedrefs').off('dialogopen');
      if (!CiteTB.getOption('modal')) {
        // $('#citetoolbar-namedrefs').dialog('option', 'modal', false);
        // $('#citetoolbar-errorcheck').dialog('option', 'modal', false);
        mw.util.addCSS('.ui-widget-overlay { display: none !important; }');
      }
      try {
        $target.wikiEditor('addToToolbar', refsection);
      } catch (_unused3) {
        // error occurred setting up wikieditor.
      }
    };

    // Load local data - messages, cite templates, etc.
    $(function () {
      mw.loader.load('/index.php?title=MediaWiki:Gadget-RefToolbarMessages.js&action=raw&ctype=text/javascript&maxage=86400&smaxage=86400');
    });

    // Setup the main object
    CiteTB.mainRefList = [];
    CiteTB.refsLoaded = false;

    // REF FUNCTIONS
    // Actually assemble a ref from user input
    CiteTB.getRef = function (inneronly, forinsert) {
      var i;
      var j;
      var g;
      var group;
      var template = CiteTB.getOpenTemplate();
      var templatename = template.templatename;
      var res = '';
      var refobj = {
        shorttag: false
      };
      if (!inneronly) {
        group = $("#cite-".concat(CiteTB.escStr(template.shortform), "-group")).val();
        var refname = $("#cite-".concat(CiteTB.escStr(template.shortform), "-name")).val();
        res += '<ref';
        if (refname) {
          refname = refname.trim();
          res += " name=".concat(CiteTB.getQuotedString(refname));
          refobj.refname = refname;
        }
        if (group) {
          group = group.trim();
          res += " group=".concat(CiteTB.getQuotedString(group));
          refobj.refgroup = group;
        }
        res += '>';
      }
      var content = "{{".concat(templatename);
      for (g in template.incrementables) {
        if (Object.prototype.hasOwnProperty.call(template.incrementables, g)) {
          group = template.incrementables[g];
          for (i = 1; i <= group.val; i++) {
            for (j = 0; j < group.fields.length; j++) {
              var fieldname = group.fields[j].field;
              var fieldid = fieldname.replace('<N>', i.toString());
              var field = $("#cite-".concat(CiteTB.escStr(template.shortform), "-").concat(fieldid)).val();
              if (field) {
                content += " |".concat(fieldid, "=");
                content += field.trim();
              }
            }
          }
        }
      }
      for (i = 0; i < template.basic.length; i++) {
        if (template.basic[i].increment_group) {
          continue;
        }
        var _fieldname = template.basic[i].field;
        var _field = $("#cite-".concat(CiteTB.escStr(template.shortform), "-").concat(_fieldname)).val();
        if (_field) {
          content += " |".concat(_fieldname, "=");
          content += _field.trim();
        }
      }
      if ($('#cite-form-status').val() !== 'closed') {
        for (i = 0; i < template.extra.length; i++) {
          if (template.extra[i].increment_group) {
            continue;
          }
          var _fieldname2 = template.extra[i].field;
          var _field2 = $("#cite-".concat(CiteTB.escStr(template.shortform), "-").concat(_fieldname2)).val();
          if (_field2) {
            content += " |".concat(_fieldname2, "=");
            content += _field2.trim();
          }
        }
      }
      content += '}}';
      res += content;
      refobj.content = content;
      if (!inneronly) {
        res += '</ref>';
      }
      if (forinsert) {
        CiteTB.mainRefList.push(refobj);
      }
      return res;
    };

    // Make a reference to a named ref
    CiteTB.getNamedRef = function (refname, forinsert) {
      if (forinsert) {
        CiteTB.mainRefList.push({
          shorttag: true,
          refname: refname
        });
      }
      return "<ref name=".concat(CiteTB.getQuotedString(refname), " />");
    };

    // Function to load the ref list
    CiteTB.loadRefs = function () {
      if (CiteTB.refsLoaded) {
        return;
      }
      CiteTB.getPageText(CiteTB.loadRefsInternal);
    };

    // Function that actually loads the list from the page text
    CiteTB.loadRefsInternal = function (text) {
      // What this does:             extract first name/group                                     extract second name/group                                          shorttag   inner content
      var refsregex = /< *ref(?: +(name|group) *= *(?:"([^"]*?)"|'([^']*?)'|([^ "'/>]*?)) *)? *(?: +(name|group) *= *(?:"([^"]*?)"|'([^']*?)'|([^ "'/>]*?)) *)? *(?:\/ *>|>([\n.]*?)< *\/ *ref *>)/gim;
      // This should work regardless of the quoting used for names/groups and for linebreaks in the inner content
      for (;;) {
        var ref = refsregex.exec(text);
        if (ref === null) {
          break;
        }
        var refobj = {};
        if (ref[9]) {
          // Content + short tag check
          // alert('"'+ref[9]+'"');
          refobj.content = ref[9];
          refobj.shorttag = false;
        } else {
          refobj.shorttag = true;
        }
        if (ref[1] !== '') {
          // First name/group
          if (ref[2]) {
            refobj["ref".concat(ref[1])] = ref[2];
          } else if (ref[3]) {
            refobj["ref".concat(ref[1])] = ref[3];
          } else {
            refobj["ref".concat(ref[1])] = ref[4];
          }
        }
        if (ref[5] !== '') {
          // Second name/group
          if (ref[6]) {
            refobj["ref".concat(ref[5])] = ref[6];
          } else if (ref[7]) {
            refobj["ref".concat(ref[5])] = ref[7];
          } else {
            refobj["ref".concat(ref[5])] = ref[8];
          }
        }
        CiteTB.mainRefList.push(refobj);
      }
      CiteTB.refsLoaded = true;
      CiteTB.setupErrorCheck();
      CiteTB.setupNamedRefs();
    };

    // AJAX FUNCTIONS
    // Parse some wikitext and hand it off to a callback function
    CiteTB.parse = function (text, callback) {
      $.post(mw.util.wikiScript('api'), {
        action: 'parse',
        title: mw.config.get('wgPageName'),
        text: text,
        prop: 'text',
        format: 'json'
      }, function (data) {
        var html = data.parse.text['*'];
        callback(html);
      }, 'json');
    };

    // Use the API to expand templates on some text
    CiteTB.expandtemplates = function (text, callback) {
      $.post(mw.util.wikiScript('api'), {
        action: 'expandtemplates',
        title: mw.config.get('wgPageName'),
        text: text,
        format: 'json'
      }, function (data) {
        var restext = data.expandtemplates['*'];
        callback(restext);
      }, 'json');
    };

    // Function to get the page text
    CiteTB.getPageText = function (callback) {
      var section = $("input[name='wpSection']").val();
      if (section !== '') {
        var postdata = {
          action: 'query',
          prop: 'revisions',
          rvprop: 'content',
          pageids: mw.config.get('wgArticleId'),
          format: 'json'
        };
        if (CiteTB.getOption('expandtemplates')) {
          postdata.rvexpandtemplates = '1';
        }
        $.get(mw.util.wikiScript('api'), postdata, function (data) {
          var pagetext = data.query.pages[mw.config.get('wgArticleId').toString()].revisions[0]['*'];
          callback(pagetext);
        }, 'json');
      } else {
        if (CiteTB.getOption('expandtemplates')) {
          CiteTB.expandtemplates($('#wpTextbox1').wikiEditor('getContents').text(), callback);
        } else {
          callback($('#wpTextbox1').wikiEditor('getContents').text());
        }
      }
    };

    // Safe version of decodeURIComponent() that doesn't throw exceptions.
    // If the native decodeURIComponent() threw an exception, the original string will be returned.
    CiteTB.safeDecodeURIComponent = function (s) {
      try {
        s = decodeURIComponent(s);
      } catch (_unused4) {}
      return s;
    };

    // Autofill a template from an ID (ISBN, DOI, PMID, URL)
    CiteTB.initAutofill = function () {
      var elemid = $(this).attr('id');
      var res = /^cite-auto-(.*?)-(.*)-(.*)$/.exec(elemid);
      var tem = res[1];
      var field = res[2];
      var autotype = res[3];
      var id = $("#cite-".concat(tem, "-").concat(field)).val();
      if (!id) {
        return false;
      }
      var url = '//citoid.qiuwen.net.cn/lookup.php?';
      // Citoid expects minimally encoded input, so do some speculative decoding here to avoid
      // 404 fetches. phabricator.wikimedia.org/T146539
      id = CiteTB.safeDecodeURIComponent(id);
      url += "".concat(autotype, "=").concat(encodeURIComponent(id));
      url += "&template=".concat(encodeURIComponent(tem));
      var s = document.createElement('script');
      s.setAttribute('src', url);
      s.setAttribute('type', 'text/javascript');
      document.querySelectorAll('head')[0].appendChild(s);
      return false;
    };

    // Callback for autofill
    // TODO: Autofill the URL, at least for DOI
    CiteTB.autoFill = function (data, template, type) {
      var cl = "cite-".concat(template, "-");
      var coauthors;
      $(".".concat(cl, "title")).val(data.title);
      // Fill in authors
      if (data.authors && data.authors.length > 0) {
        if ($(".".concat(cl, "last-incr-1")).length > 0) {
          var classes = $(".".concat(cl, "last-incr-1")).eq(0).attr('class').split(/\s+/);
          var group = false;
          var patt = /cite-[^-]*?-incr-(.*)/;
          var _iterator2 = _createForOfIteratorHelper(classes),
            _step2;
          try {
            for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
              var class_ = _step2.value;
              if (patt.test(class_)) {
                group = patt.exec(class_)[1];
                break;
              }
            }
          } catch (err) {
            _iterator2.e(err);
          } finally {
            _iterator2.f();
          }
          $(".".concat(cl, "last-incr-1")).val(data.authors[0][0]);
          $(".".concat(cl, "first-incr-1")).val(data.authors[0][1]);
          var _elemid = "#cite-incr-".concat(template, "-").concat(group);
          for (var _i2 = 2; _i2 < data.authors.length + 1; _i2++) {
            $(_elemid).trigger('click');
            $(".".concat(cl, "last-incr-").concat(_i2.toString())).val(data.authors[_i2 - 1][0]);
            $(".".concat(cl, "first-incr-").concat(_i2.toString())).val(data.authors[_i2 - 1][1]);
          }
        } else if ($(".".concat(cl, "author-incr-1")).length > 0) {
          var _classes = $(".".concat(cl, "author-incr-1")).eq(0).attr('class').split(/\s+/);
          var _group = false;
          var _patt = /cite-[^-]*?-incr-(.*)/;
          var _iterator3 = _createForOfIteratorHelper(_classes),
            _step3;
          try {
            for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
              var _class_ = _step3.value;
              if (_patt.test(_class_)) {
                _group = _patt.exec(_class_)[1];
                break;
              }
            }
          } catch (err) {
            _iterator3.e(err);
          } finally {
            _iterator3.f();
          }
          $(".".concat(cl, "author-incr-1")).val(data.authors[0].join(', '));
          elemid = "#cite-incr-".concat(template, "-").concat(_group);
          for (var _i4 = 2; _i4 < data.authors.length + 1; _i4++) {
            $(elemid).trigger('click');
            $(".".concat(cl, "author-incr-").concat(_i4.toString())).val(data.authors[_i4 - 1].join(', '));
          }
        } else if ($(".".concat(cl, "last1")).length > 0) {
          for (i = 0; data.authors && i < data.authors.length; i++) {
            if ($(".".concat(cl, "last").concat(i + 1)).length > 0) {
              $(".".concat(cl, "last").concat(i + 1)).val(data.authors[i][0]);
              $(".".concat(cl, "first").concat(i + 1)).val(data.authors[i][1]);
            } else {
              coauthors = [];
              for (j = i; j < data.authors.length; j++) {
                coauthors.push(data.authors[j].join(', '));
              }
              $(".".concat(cl, "coauthors")).val(coauthors.join('; '));
              break;
            }
          }
        } else if ($(".".concat(cl, "author1")).length > 0) {
          for (i = 0; data.authors && i < data.authors.length; i++) {
            if ($(".".concat(cl, "author").concat(i + 1)).length > 0) {
              $(".".concat(cl, "author").concat(i + 1)).val(data.authors[i].join(', '));
            } else {
              coauthors = [];
              for (j = i; j < data.authors.length; j++) {
                coauthors.push(data.authors[j].join(', '));
              }
              $(".".concat(cl, "coauthors")).val(coauthors.join('; '));
              break;
            }
          }
        } else {
          var authors = [];
          for (i = 0; data.authors && i < data.authors.length; i++) {
            authors.push(data.authors[i].join(', '));
          }
          $(".".concat(cl, "authors")).val(authors.join('; '));
        }
      }

      // Format partial dates of the format YYYY-MM, YYYY-MM-XX, or YYYY-MM-DD correctly
      if (data.date) {
        try {
          var DT = new Date(data.date);
          if (/^\d{4}-\d{2}(-xx)?$/i.test(data.date)) {
            data.date = data.date.replace('-XX', '');
            $(".".concat(cl, "date")).val(CiteTB.formatDate(DT, false, true));
          } else if (/^\d{4}-\d{2}-\d{2}?/i.test(data.date)) {
            $(".".concat(cl, "date")).val(CiteTB.formatDate(DT, true, true));
          } else {
            $(".".concat(cl, "date")).val(data.date);
          }
        } catch (_unused5) {}
      } else {
        $(".".concat(cl, "date")).val(data.date);
      }
      switch (type) {
        case 'pmid':
        case 'doi':
          {
            $(".".concat(cl, "journal")).val(data.journal);
            $(".".concat(cl, "volume")).val(data.volume);
            $(".".concat(cl, "issue")).val(data.issue);
            $(".".concat(cl, "pages")).val(data.pages);
            if (type === 'pmid' && data.doi) {
              $(".".concat(cl, "doi")).val(data.doi);
            }
            break;
          }
        case 'isbn':
          {
            $(".".concat(cl, "publisher")).val(data.publisher);
            $(".".concat(cl, "location")).val(data.location);
            $(".".concat(cl, "edition")).val(data.edition);
            break;
          }
        case 'url':
          {
            $(".".concat(cl, "journal")).val(data.journal);
            $(".".concat(cl, "volume")).val(data.volume);
            $(".".concat(cl, "issue")).val(data.issue);
            $(".".concat(cl, "pages")).val(data.pages);
            $(".".concat(cl, "publisher")).val(data.publisher);
            $(".".concat(cl, "edition")).val(data.edition);
            $(".".concat(cl, "isbn")).val(data.isbn);
            $(".".concat(cl, "issn")).val(data.issn);
            $(".".concat(cl, "doi")).val(data.doi);
            // "en-US" isn't a valid value for the language parameter
            if (data.language && data.language !== 'en-US' && data.language !== 'en-GB') {
              $(".".concat(cl, "language")).val(data.language);
            }
            $(".".concat(cl, "chapter")).val(data.chapter);
            break;
          }
        // No default
      }
    };

    // FORM DIALOG FUNCTIONS
    // Add new incrementable fields
    CiteTB.incrementFields = function () {
      var template = CiteTB.getOpenTemplate();
      var currentrow = $(this).parents('tr')[0];
      $(this).prev().css('width', '100%');
      $(this).detach();
      var elemid = $(this).attr('id');
      var res = /^cite-incr-(.*?)-(.*)$/.exec(elemid);
      var group = res[2];
      var increments = template.incrementables[group];
      var fields = increments.fields;
      template.incrementables[group].val += 1;
      var trs = template.makeFormInner(fields, false);
      trs.reverse();
      var _iterator4 = _createForOfIteratorHelper(trs),
        _step4;
      try {
        for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
          var tr = _step4.value;
          $(currentrow).after(tr);
        }
      } catch (err) {
        _iterator4.e(err);
      } finally {
        _iterator4.f();
      }
    };

    // fill the accessdate param with the current date
    CiteTB.fillAccessdate = function () {
      var elemid = $(this).attr('id');
      var res = /^cite-date-(.*?)-(.*)$/.exec(elemid);
      var id = res[1];
      var field = res[2];
      var DT = new Date();
      var datestr = CiteTB.formatDate(DT);
      $("#cite-".concat(id, "-").concat(field)).val(datestr);
      return false;
    };
    CiteTB.formatDate = function (DT, useday, usemonth) {
      if (typeof useday === 'undefined') {
        useday = true;
      }
      if (typeof usemonth === 'undefined') {
        usemonth = true;
      }
      var datestr = CiteTB.getOption('date format');
      var zmonth = '';
      var month = DT.getUTCMonth() + 1;
      if (month < 10) {
        zmonth = "0".concat(month.toString());
      } else {
        zmonth = month.toString();
      }
      month = month.toString();
      var zdate = '';
      var date = DT.getUTCDate();
      if (date < 10) {
        zdate = "0".concat(date.toString());
      } else {
        zdate = date.toString();
      }
      date = date.toString();
      if (useday) {
        datestr = datestr.replace('<date>', date);
        datestr = datestr.replace('<zdate>', zdate);
      } else {
        datestr = datestr.replace('<date>', '');
        datestr = datestr.replace('<zdate>', '');
      }
      if (usemonth) {
        datestr = datestr.replace('<month>', month);
        datestr = datestr.replace('<zmonth>', zmonth);
        datestr = datestr.replace('<monthname>', CiteTB.getOption('months')[DT.getUTCMonth()]);
      } else {
        datestr = datestr.replace('<month>', '');
        datestr = datestr.replace('<zmonth>', '');
        datestr = datestr.replace('<monthname>', '');
      }
      datestr = datestr.replace('<year>', DT.getUTCFullYear().toString());
      return datestr.replace(/^[ ,./-]*(.*?)[ ,./-]*$/g, '$1'); // Cleanup any dangling spaces or connectors that might result from omitting date/month
    };

    // Function called after the ref list is loaded, to actually set the contents of the named ref dialog
    // Until the list is loaded, its just a "Loading" placeholder
    CiteTB.setupNamedRefs = function () {
      var names = [];
      var i;
      for (i = 0; i < CiteTB.mainRefList.length; i++) {
        if (!CiteTB.mainRefList[i].shorttag && CiteTB.mainRefList[i].refname) {
          names.push(CiteTB.mainRefList[i]);
        }
      }
      var stuff = $('<div>');
      $('#citetoolbar-namedrefs').html(stuff);
      if (names.length === 0) {
        stuff.html(mw.usability.getMsg('cite-no-namedrefs'));
      } else {
        stuff.html(mw.usability.getMsg('cite-namedrefs-intro'));
        var select = $('<select>').attr('id', 'cite-namedref-select');
        select.append($('<option>').attr('value', '').text(mw.usability.getMsg('cite-named-refs-dropdown')));
        for (i = 0; i < names.length; i++) {
          select.append($('<option>').text(names[i].refname));
        }
        stuff.after(select);
        select.before('<br>');
        var prevlabel = $('<div>').attr({
          id: 'cite-nref-preview-label',
          style: 'display: none;'
        }).html(mw.usability.getMsg('cite-raw-preview'));
        select.after(prevlabel);
        prevlabel.before('<br><br>');
        prevlabel.after('<div id="cite-namedref-preview" style="padding: 0.5em; font-size: 110%" />');
        var parselabel = $('<span>').attr({
          id: 'cite-parsed-label',
          style: 'display: none;'
        }).html(mw.usability.getMsg('cite-parsed-label'));
        $('#cite-namedref-preview').after(parselabel);
        parselabel.after('<div id="cite-namedref-parsed" style="padding-bottom: 0.5em; font-size: 110%" />');
        var link = $('<a>').attr({
          href: '#',
          id: 'cite-nref-parse',
          style: 'margin: 0 1em 0 1em; display: none; color: darkblue'
        });
        link.html(mw.usability.getMsg('cite-form-parse'));
        $('#cite-namedref-parsed').after(link);
        $('#cite-namedref-select').on('change', CiteTB.namedRefSelectClick);
        $('#cite-nref-parse').on('click', CiteTB.nrefParseClick);
      }
    };

    // Function to get the errorcheck form HTML
    CiteTB.setupErrorCheck = function () {
      var form = $('<div>').attr('id', 'cite-errorcheck-heading').html(mw.usability.getMsg('cite-errorcheck-heading'));
      var ul = $('<ul>').attr('id', 'cite-errcheck-list');
      var test;
      for (var t in CiteTB.ErrorChecks) {
        if (Object.prototype.hasOwnProperty.call(CiteTB.ErrorChecks, t)) {
          test = CiteTB.ErrorChecks[t];
          ul.append(test.getRow());
        }
      }
      form.append(ul);
      $('#citetoolbar-errorcheck').html(form);
    };

    // Callback function for parsed preview
    CiteTB.fillNrefPreview = function (parsed) {
      $('#cite-parsed-label').show();
      $('#cite-namedref-parsed').html(parsed);
    };

    // Click handler for the named-ref parsed preview
    CiteTB.nrefParseClick = function () {
      var choice = $('#cite-namedref-select').val();
      if (choice === '') {
        $('#cite-parsed-label').hide();
        $('#cite-namedref-parsed').text('');
        return false;
      }
      $('#cite-nref-parse').hide();
      for (var _i6 = 0; _i6 < CiteTB.mainRefList.length; _i6++) {
        if (!CiteTB.mainRefList[_i6].shorttag && CiteTB.mainRefList[_i6].refname === choice) {
          CiteTB.parse(CiteTB.mainRefList[_i6].content, CiteTB.fillNrefPreview);
          return false;
        }
      }
    };

    // Click handler for the named-ref dropdown
    CiteTB.lastnamedrefchoice = '';
    CiteTB.namedRefSelectClick = function () {
      var choice = $('#cite-namedref-select').val();
      if (CiteTB.lastnamedrefchoice === choice) {
        return;
      }
      CiteTB.lastnamedrefchoice = choice;
      $('#cite-parsed-label').hide();
      $('#cite-namedref-parsed').text('');
      if (choice === '') {
        $('#cite-nref-preview-label').hide();
        $('#cite-namedref-preview').text('');
        $('#cite-nref-parse').hide();
        return;
      }
      for (var _i8 = 0; _i8 < CiteTB.mainRefList.length; _i8++) {
        if (!CiteTB.mainRefList[_i8].shorttag && CiteTB.mainRefList[_i8].refname === choice) {
          $('#cite-nref-preview-label').show();
          $('#cite-namedref-preview').text(CiteTB.mainRefList[_i8].content);
          if (CiteTB.getOption('autoparse')) {
            CiteTB.nrefParseClick();
          } else {
            $('#cite-nref-parse').show();
          }
        }
      }
    };

    // callback function for parsed preview
    CiteTB.fillTemplatePreview = function (text) {
      var template = CiteTB.getOpenTemplate();
      var div = $("#citetoolbar-".concat(CiteTB.escStr(template.shortform)));
      div.find('.cite-prev-parsed-label').show();
      div.find('.cite-preview-parsed').html(text);
    };

    // Click handler for template parsed preview
    CiteTB.prevParseClick = function () {
      var ref = CiteTB.getRef(true, false);
      var template = CiteTB.getOpenTemplate();
      var div = $("#citetoolbar-".concat(CiteTB.escStr(template.shortform)));
      div.find('.cite-prev-parse').hide();
      CiteTB.parse(ref, CiteTB.fillTemplatePreview);
    };

    // Show/hide the extra fields in the dialog box
    CiteTB.showHideExtra = function () {
      var template = CiteTB.getOpenTemplate();
      var div = $("#citetoolbar-".concat(CiteTB.escStr(template.shortform)));
      var setting = div.find('.cite-form-status').val();
      if (setting === 'closed') {
        div.find('.cite-form-status').val('open');
        div.find('.cite-extra-fields').show(1, function () {
          // jQuery adds "display: block", which screws things up
          div.find('.cite-extra-fields').css({
            width: '100%',
            'background-color': 'transparent'
          });
        });
      } else {
        div.find('.cite-form-status').val('closed');
        div.find('.cite-extra-fields').hide();
      }
    };

    // Resets form fields and previews
    // Resets form fields and previews
    CiteTB.resetForm = function () {
      var template = CiteTB.getOpenTemplate();
      var div = $("#citetoolbar-".concat(CiteTB.escStr(template.shortform)));
      div.html(template.getForm());
    };

    // STRING UTILITY FUNCTIONS
    // Returns a string quoted as necessary for name/group attributes
    CiteTB.getQuotedString = function (s) {
      var sq = /'/.test(s); // single quotes
      var dq = /"/.test(s); // double quotes
      if (!sq && !dq) {
        // Always quotes for non-latin alphabet
        return "\"".concat(s, "\"");
      } else if (!dq) {
        // Can use double quotes
        return "\"".concat(s, "\"");
      } else if (!sq) {
        // Can use single quotes
        return "'".concat(s, "'");
      }
      // Has double and single quotes
      s = s.replace(/"/g, "'");
      return "\"".concat(s, "\"");
    };

    // Fix up strings for output - capitalize first char, replace underscores with spaces
    CiteTB.fixStr = function (s) {
      s = s.slice(0, 1).toUpperCase() + s.slice(1);
      s = s.replace('_', ' ');
      return s;
    };

    // Escape spaces and quotes for use in HTML classes/ids
    CiteTB.escStr = function (s) {
      return s.replace(' ', '-').replace("'", "'").replace('"', '"');
    };

    // MISC FUNCTIONS
    // Determine which template form is open, and get the template object for it
    CiteTB.getOpenTemplate = function () {
      var dialogs = $('.ui-dialog-content.ui-widget-content:visible');
      var templatename = $(dialogs[0]).find('.cite-template').val();
      return CiteTB.Templates[templatename];
    };

    // Display the report for the error checks
    CiteTB.displayErrors = function (errors) {
      $('#cite-err-report').remove();
      var table = $('<table>').attr({
        id: 'cite-err-report',
        style: 'width: 100%; border: 1px solid #A9A9A9; background-color: #FFEFD5; padding: 0.25em; margin-top: 0.5em'
      });
      $('#editpage-copywarn').before(table);
      var tr;
      var tr1 = $('<tr>').css('width', '100%');
      var th1 = $('<th>').attr('style', 'width: 60%; font-size: 110%').html(mw.usability.getMsg('cite-err-report-heading'));
      var th2 = $('<th>').attr('style', 'text-align: right; width: 40%');
      var im = $('<img>').attr('src', '//tu.zhongwen.wiki/images/qiuwen/thumb/5/55/Gtk-stop.svg/20px-Gtk-stop.svg.png');
      im.attr('alt', mw.usability.getMsg('cite-err-report-close')).attr('title', mw.usability.getMsg('cite-err-report-close'));
      var ad = $('<a>').attr({
        id: 'cite-err-check-close',
        href: '#'
      });
      ad.append(im);
      th2.append(ad);
      tr1.append(th1).append(th2);
      table.append(tr1);
      $('#cite-err-check-close').on('click', function () {
        $('#cite-err-report').remove();
      });
      if (errors.length === 0) {
        tr = $('<tr>').css('width', '100%');
        var td = $('<td>').attr('style', 'text-align: center; margin: 1.5px;').html(mw.usability.getMsg('cite-err-report-empty'));
        tr.append(td);
        table.append(tr);
        return;
      }
      for (var e in errors) {
        if (Object.prototype.hasOwnProperty.call(errors, e)) {
          var err = errors[e];
          tr = $('<tr>').css('width', '100%');
          var td1 = $('<td>').css({
            border: '1px solid black',
            margin: '1.5px',
            width: '60%'
          }).html(err.err);
          var td2 = $('<td>').css({
            border: '1px solid black',
            margin: '1.5px',
            width: '40%'
          }).html(mw.usability.getMsg(err.msg));
          tr.append(td1).append(td2);
          table.append(tr);
        }
      }
    };
  }
  // End of code loaded only on edit
})(jQuery, mediaWiki);

/* </nowiki> */