Site Notice

hello, world

Difference between revisions of "MediaWiki:Js-InPageEdit-v2.js"

From Project-EPB Commons
([InPageEdit] 没有编辑摘要)
([InPageEdit] 没有编辑摘要)
Line 57: Line 57:
 
   var preference = JSON.parse(localStorage.getItem('InPageEditPreference'));
 
   var preference = JSON.parse(localStorage.getItem('InPageEditPreference'));
 
   var editPage = decodeURIComponent(option.page),
 
   var editPage = decodeURIComponent(option.page),
  editSection = option.section,
+
    editSection = option.section,
  titleSection = '',
+
    titleSection = '',
  editRevision = option.revision,
+
    editRevision = option.revision,
  titleRevision = '',
+
    titleRevision = '',
  editText,
+
    editText,
  editSummary = preference.editSummary,
+
    editSummary = preference.editSummary,
  editMinor = preference.editMinor,
+
    editMinor = preference.editMinor,
  editNotice = '',
+
    editNotice = '',
  outSideClose = preference.outSideClose,
+
    outSideClose = preference.outSideClose,
  jsonGet = {
+
    jsonGet = {
    action: 'parse',
+
      action: 'parse',
    page: editPage,
+
      page: editPage,
    prop: 'wikitext',
+
      prop: 'wikitext',
    format: 'json'
+
      format: 'json'
  },
+
    },
  jsonGetInfo = {
+
    jsonGetInfo = {
    action: 'query',
+
      action: 'query',
    titles: editPage,
+
      titles: editPage,
    prop: 'revisions|info',
+
      prop: 'revisions|info',
    rvprop: 'timestamp',
+
      rvprop: 'timestamp',
    format: 'json'
+
      format: 'json'
  },
+
    },
  jsonPost = {},
+
    jsonPost = {},
  basetimestamp,
+
    basetimestamp,
  date = new Date(),
+
    date = new Date(),
  timestamp = date.getTime(),
+
    timestamp = date.getTime(),
  now = date.toUTCString(); // 缓存时间戳
+
    now = date.toUTCString(); // 缓存时间戳
  
 
   if (editPage === undefined)
 
   if (editPage === undefined)
Line 102: Line 102:
 
     }
 
     }
 
   }
 
   }
   if (typeof(MyInPageEditPreference) !== 'undefined') {
+
   if (typeof (MyInPageEditPreference) !== 'undefined') {
     if (typeof(MyInPageEditPreference.editSummary) === 'string')
+
     if (typeof (MyInPageEditPreference.editSummary) === 'string')
 
       editSummary = MyInPageEditPreference.editSummary;
 
       editSummary = MyInPageEditPreference.editSummary;
     if (typeof(MyInPageEditPreference.editMinor) === 'boolean')
+
     if (typeof (MyInPageEditPreference.editMinor) === 'boolean')
 
       editMinor = MyInPageEditPreference.editMinor;
 
       editMinor = MyInPageEditPreference.editMinor;
     if (typeof(MyInPageEditPreference.outSideClose) === 'boolean')
+
     if (typeof (MyInPageEditPreference.outSideClose) === 'boolean')
 
       outSideClose = MyInPageEditPreference.outSideClose;
 
       outSideClose = MyInPageEditPreference.outSideClose;
 
   }
 
   }
Line 132: Line 132:
 
   ssi_modal.show({
 
   ssi_modal.show({
 
     title: '正在编辑:<u class="editPage">' + editPage + '</u>' + titleSection + titleRevision,
 
     title: '正在编辑:<u class="editPage">' + editPage + '</u>' + titleSection + titleRevision,
     content: '<textarea class="editArea" disabled="">正在加载……</textarea><label for="editSummary">摘要:</label><input id="editSummary" class="editSummary" placeholder="Edit via InPageEdit~"/><br/><input id="editMinor" class="editMinor" type="checkbox" style=""/><label for="editMinor">小编辑</label>',
+
     content: '<div class="ipe-progress" style="width:100%"><div class="progress-bar"></div></div><section class="editForm"><textarea class="editArea" disabled=""></textarea><label for="editSummary">摘要:</label><input id="editSummary" class="editSummary" placeholder="Edit via InPageEdit~"/><br/><input id="editMinor" class="editMinor" type="checkbox" style=""/><label for="editMinor">小编辑</label></section>',
 
     outSideClose: outSideClose,
 
     outSideClose: outSideClose,
 
     className: 'in-page-edit ipe-editor timestamp-' + timestamp,
 
     className: 'in-page-edit ipe-editor timestamp-' + timestamp,
Line 141: Line 141:
 
         content: '确定要关闭窗口吗?<br/>此处的编辑将会丢失!',
 
         content: '确定要关闭窗口吗?<br/>此处的编辑将会丢失!',
 
         okBtn: {
 
         okBtn: {
           className: 'btn btn-danger',
+
           className: 'btn btn-danger editForm',
 
           label: '确定'
 
           label: '确定'
 
         },
 
         },
 
         cancelBtn: {
 
         cancelBtn: {
           className: 'btn btn-secondary',
+
           className: 'btn btn-secondary editForm',
 
           label: '取消'
 
           label: '取消'
 
         }
 
         }
 
       },
 
       },
 
         function (result) {
 
         function (result) {
        if (result === true) {
+
          if (result === true) {
          $(window).unbind('beforeunload');
+
            $(window).unbind('beforeunload');
          modal.options.keepContent = false;
+
            modal.options.keepContent = false;
          modal.options.beforeClose = '';
+
            modal.options.beforeClose = '';
          modal.close();
+
            modal.close();
          ssi_modal.notify('error', {
+
            ssi_modal.notify('error', {
            className: 'in-page-edit',
+
              className: 'in-page-edit',
            position: 'right top',
+
              position: 'right top',
            title: '取消',
+
              title: '取消',
            content: "编辑被取消"
+
              content: "编辑被取消"
          })
+
            })
        }
+
          }
      });
+
        });
 
       return false;
 
       return false;
 
     },
 
     },
 
     buttons: [{
 
     buttons: [{
        label: '预览',
+
      label: '预览',
        className: 'btn btn-secondary',
+
      className: 'btn btn-secondary',
        method: function () {
+
      method: function () {
          var text = $('.editArea').val();
+
        var text = $('.editArea').val();
          requestPreview(text)
+
        requestPreview(text)
        }
+
      }
      }, {
+
    }, {
        label: '发布',
+
      label: '发布',
        className: 'btn btn-primary',
+
      className: 'btn btn-primary',
        method: function () {
+
      method: function () {
          ssi_modal.confirm({
+
        ssi_modal.confirm({
            className: 'in-page-edit confirmbox',
+
          className: 'in-page-edit confirmbox',
            content: '是否发布',
+
          content: '是否发布',
            okBtn: {
+
          okBtn: {
              className: 'btn btn-primary',
+
            className: 'btn btn-primary',
              label: '确定'
+
            label: '确定'
            },
+
          },
            cancelBtn: {
+
          cancelBtn: {
              className: 'btn btn-secondary',
+
            className: 'btn btn-secondary',
              label: '取消'
+
            label: '取消'
            },
 
 
           },
 
           },
            function (result) {
+
        },
 +
          function (result) {
 
             if (result) {
 
             if (result) {
 
               var text = $('.ipe-editor.timestamp-' + timestamp + ' .editArea').val(),
 
               var text = $('.ipe-editor.timestamp-' + timestamp + ' .editArea').val(),
              minor = $('.ipe-editor.timestamp-' + timestamp + ' .editMinor').prop('checked'),
+
                minor = $('.ipe-editor.timestamp-' + timestamp + ' .editMinor').prop('checked'),
              section = option.section,
+
                section = option.section,
              summary = $('.ipe-editor.timestamp-' + timestamp + ' .editSummary').val();
+
                summary = $('.ipe-editor.timestamp-' + timestamp + ' .editSummary').val();
 
               postArticle({
 
               postArticle({
 
                 text: text,
 
                 text: text,
Line 203: Line 203:
 
             }
 
             }
 
           })
 
           })
        }
 
 
       }
 
       }
 +
    }
 
     ]
 
     ]
 
   });
 
   });
 
   // 获取页面代码
 
   // 获取页面代码
 +
  $('.ipe-editor.timestamp-' + timestamp + ' .editForm').hide();
 
   new mw.Api().get(jsonGet).then(function (data) {
 
   new mw.Api().get(jsonGet).then(function (data) {
 
     console.timeEnd('[InPageEdit] Get page content');
 
     console.timeEnd('[InPageEdit] Get page content');
Line 217: Line 218:
 
       console.error('[InPageEdit]警告:无法获取页面内容');
 
       console.error('[InPageEdit]警告:无法获取页面内容');
 
     }
 
     }
 +
    $('.ipe-editor.timestamp-' + timestamp + ' .ipe-progress').hide();
 +
    $('.ipe-editor.timestamp-' + timestamp + ' .editForm').fadeIn(500);
 
     $('.ipe-editor.timestamp-' + timestamp + ' .editArea').val(editText).attr('disabled', false);
 
     $('.ipe-editor.timestamp-' + timestamp + ' .editArea').val(editText).attr('disabled', false);
 
   }).fail(function (data) {
 
   }).fail(function (data) {
Line 222: Line 225:
 
     editText = '<!-- 警告:无法获取页面内容 -->';
 
     editText = '<!-- 警告:无法获取页面内容 -->';
 
     console.error('[InPageEdit]警告:无法获取页面内容');
 
     console.error('[InPageEdit]警告:无法获取页面内容');
 +
    $('.ipe-editor.timestamp-' + timestamp + ' .ipe-progress').hide();
 +
    $('.ipe-editor.timestamp-' + timestamp + ' .editForm').fadeIn(500);
 
     $('.ipe-editor.timestamp-' + timestamp + ' .editArea').val(editText).attr('disabled', false);
 
     $('.ipe-editor.timestamp-' + timestamp + ' .editArea').val(editText).attr('disabled', false);
 
   });
 
   });
Line 228: Line 233:
 
     $('.ipe-editor.timestamp-' + timestamp + ' .editMinor').attr('checked', 'checked');
 
     $('.ipe-editor.timestamp-' + timestamp + ' .editMinor').attr('checked', 'checked');
 
   }
 
   }
   $('.ipe-editor.timestamp-' + timestamp + ' .editSummary').val(editSummary.replace(/\$section/ig,$($.parseHTML(titleSection)).text()).replace(/\$oldid/ig, $($.parseHTML(titleRevision)).text()));
+
   $('.ipe-editor.timestamp-' + timestamp + ' .editSummary').val(editSummary.replace(/\$section/ig, $($.parseHTML(titleSection)).text()).replace(/\$oldid/ig, $($.parseHTML(titleRevision)).text()));
  
 
   // 获取页面最后编辑时间戳
 
   // 获取页面最后编辑时间戳
   new mw.Api().get(jsonGetInfo).then(function(data){
+
   new mw.Api().get(jsonGetInfo).then(function (data) {
 
     if (data && data.query && data.query.pages) {
 
     if (data && data.query && data.query.pages) {
 
       var info = data.query.pages;
 
       var info = data.query.pages;
Line 295: Line 300:
 
   // 发布编辑模块
 
   // 发布编辑模块
 
   function postArticle(pValue) {
 
   function postArticle(pValue) {
 +
    InPageEdit.progress('正在发布编辑...');
 
     jsonPost = {
 
     jsonPost = {
 
       action: 'edit',
 
       action: 'edit',
Line 314: Line 320:
 
     console.table(jsonPost);
 
     console.table(jsonPost);
 
     new mw.Api().post(jsonPost).then(function (data) {
 
     new mw.Api().post(jsonPost).then(function (data) {
 +
      InPageEdit.progress(false);
 
       $(window).unbind('beforeunload');
 
       $(window).unbind('beforeunload');
 
       ssi_modal.notify('success', {
 
       ssi_modal.notify('success', {
Line 327: Line 334:
 
       }
 
       }
 
     }).fail(function (errorCode, feedback, errorThrown) {
 
     }).fail(function (errorCode, feedback, errorThrown) {
       ssi_modal.notify('error',{
+
      InPageEdit.progress(false);
 +
       ssi_modal.notify('error', {
 
         className: 'in-page-edit',
 
         className: 'in-page-edit',
 
         position: 'right top',
 
         position: 'right top',
Line 351: Line 359:
 
     errorformat: 'plaintext'
 
     errorformat: 'plaintext'
 
   },
 
   },
  summary = '快速重定向 → [[:$1]] //使用API进行的操作,请核查本次编辑',
+
    summary = '快速重定向 → [[:$1]] //使用API进行的操作,请核查本次编辑',
  text = '#REDIRECT [[:$1]]',
+
    text = '#REDIRECT [[:$1]]',
  question,
+
    question,
  target;
+
    target;
 
   switch (type) {
 
   switch (type) {
  case 'to':
+
    case 'to':
    json.title = mw.config.get('wgPageName');
+
      json.title = mw.config.get('wgPageName');
    question = '您要将 <b>' + mw.config.get('wgPageName') + '</b> 重定向到哪个页面?';
+
      question = '您要将 <b>' + mw.config.get('wgPageName') + '</b> 重定向到哪个页面?';
    break;
+
      break;
  case 'from':
+
    case 'from':
    question = '您要将哪个页面重定向到 <b>' + mw.config.get('wgPageName') + '</b>?';
+
      question = '您要将哪个页面重定向到 <b>' + mw.config.get('wgPageName') + '</b>?';
    json.text = text.replace('$1', mw.config.get('wgPageName'));
+
      json.text = text.replace('$1', mw.config.get('wgPageName'));
    json.summary = summary.replace('$1', mw.config.get('wgPageName'));
+
      json.summary = summary.replace('$1', mw.config.get('wgPageName'));
    break;
+
      break;
 
   }
 
   }
 
   ssi_modal.show({
 
   ssi_modal.show({
Line 372: Line 380:
 
     content: question + '<br><input id="redirect-page" style="width:80%;margin: 0 10%;" onclick="$(this).css(\'box-shadow\',\'\')"/>',
 
     content: question + '<br><input id="redirect-page" style="width:80%;margin: 0 10%;" onclick="$(this).css(\'box-shadow\',\'\')"/>',
 
     buttons: [{
 
     buttons: [{
        label: '确定',
+
      label: '确定',
        className: 'btn btn-primary',
+
      className: 'btn btn-primary',
        method: function () {
+
      method: function () {
          var input = $('#redirect-page').val();
+
        var input = $('#redirect-page').val();
          if (input === '' || input === mw.config.get('wgPageName')) {
+
        if (input === '' || input === mw.config.get('wgPageName')) {
            $('#redirect-page').css('box-shadow', '0 0 4px red');
+
          $('#redirect-page').css('box-shadow', '0 0 4px red');
          } else {
+
        } else {
            switch (type) {
+
          switch (type) {
 
             case 'to':
 
             case 'to':
 
               json.summary = summary.replace('$1', input);
 
               json.summary = summary.replace('$1', input);
Line 387: Line 395:
 
               json.title = input;
 
               json.title = input;
 
               break;
 
               break;
            }
+
          }
  
            new mw.Api().post(json).done(function () {
+
          new mw.Api().post(json).done(function () {
              ssi_modal.notify('success', {
+
            ssi_modal.notify('success', {
                className: 'in-page-edit',
+
              className: 'in-page-edit',
                content: '已创建重定向!<br/>正在刷新页面……',
+
              content: '已创建重定向!<br/>正在刷新页面……',
                title: '成功'
+
              title: '成功'
              });
 
              window.location.reload();
 
 
             });
 
             });
           }
+
            window.location.reload();
 +
           });
 
         }
 
         }
 
       }
 
       }
 +
    }
 
     ]
 
     ]
 
   });
 
   });
Line 418: Line 426:
 
   }
 
   }
 
   var page = mw.config.get('wgPageName'),
 
   var page = mw.config.get('wgPageName'),
  reasonType,
+
    reasonType,
  reason = '不再需要的页面';
+
    reason = '不再需要的页面';
  
 
   ssi_modal.show({
 
   ssi_modal.show({
Line 443: Line 451:
 
   }
 
   }
 
   var from = mw.config.get('wgPageName'),
 
   var from = mw.config.get('wgPageName'),
  to,
+
    to,
  reason = '重命名页面 → [[:$1]] //使用API进行的操作,请核查本次编辑',
+
    reason = '重命名页面 → [[:$1]] //使用API进行的操作,请核查本次编辑',
  movetalk,
+
    movetalk,
  movesubpages,
+
    movesubpages,
  noredirect,
+
    noredirect,
  ignorewarnings;
+
    ignorewarnings;
  
 
   ssi_modal.show({
 
   ssi_modal.show({
Line 461: Line 469:
 
InPageEdit.preference = function () {
 
InPageEdit.preference = function () {
 
   var settings = JSON.parse(localStorage.getItem('InPageEditPreference')),
 
   var settings = JSON.parse(localStorage.getItem('InPageEditPreference')),
  minor = settings.editMinor,
+
    minor = settings.editMinor,
  summary = settings.editSummary,
+
    summary = settings.editSummary,
  outSideClose = settings.outSideClose;
+
    outSideClose = settings.outSideClose;
  
 
   ssi_modal.show({
 
   ssi_modal.show({
Line 471: Line 479:
 
     className: 'in-page-edit ipe-preference',
 
     className: 'in-page-edit ipe-preference',
 
     buttons: [{
 
     buttons: [{
        label: '重置',
+
      label: '重置',
        className: 'btn btn-danger',
+
      className: 'btn btn-danger',
        method: function () {
+
      method: function () {
          $('#InPageEditSettingBox #ipeSetoutSideClose').prop('checked', true);
+
        $('#InPageEditSettingBox #ipeSetoutSideClose').prop('checked', true);
          $('#InPageEditSettingBox #ipeSetMinor').prop('checked', false);
+
        $('#InPageEditSettingBox #ipeSetMinor').prop('checked', false);
          $('#InPageEditSettingBox #ipeSetSummary').val('[InPageEdit] 没有编辑摘要 $section$oldid');
+
        $('#InPageEditSettingBox #ipeSetSummary').val('[InPageEdit] 没有编辑摘要 $section$oldid');
        }
+
      }
      }, {
+
    }, {
        label: '保存',
+
      label: '保存',
        className: 'btn btn-primary',
+
      className: 'btn btn-primary',
        method: function (a, modal) {
+
      method: function (a, modal) {
          localStorage.setItem('InPageEditPreference', JSON.stringify({
+
        localStorage.setItem('InPageEditPreference', JSON.stringify({
              outSideClose: $('#InPageEditSettingBox #ipeSetoutSideClose').prop('checked'),
+
          outSideClose: $('#InPageEditSettingBox #ipeSetoutSideClose').prop('checked'),
              editMinor: $('#InPageEditSettingBox #ipeSetMinor').prop('checked'),
+
          editMinor: $('#InPageEditSettingBox #ipeSetMinor').prop('checked'),
              editSummary: $('#InPageEditSettingBox #ipeSetSummary').val()
+
          editSummary: $('#InPageEditSettingBox #ipeSetSummary').val()
            }));
+
        }));
  
          modal.close();
+
        modal.close();
        }
 
 
       }
 
       }
 +
    }
 
     ]
 
     ]
 
   });
 
   });
Line 502: Line 510:
 
     });
 
     });
 
     $('#ipeSaveLocal input').val('var MyInPageEditPreference = ' + JSON.stringify({
 
     $('#ipeSaveLocal input').val('var MyInPageEditPreference = ' + JSON.stringify({
        outSideClose: $('#InPageEditSettingBox #ipeSetoutSideClose').prop('checked'),
+
      outSideClose: $('#InPageEditSettingBox #ipeSetoutSideClose').prop('checked'),
        editMinor: $('#InPageEditSettingBox #ipeSetMinor').prop('checked'),
+
      editMinor: $('#InPageEditSettingBox #ipeSetMinor').prop('checked'),
        editSummary: $('#InPageEditSettingBox #ipeSetSummary').val()
+
      editSummary: $('#InPageEditSettingBox #ipeSetSummary').val()
      }) + ';');
+
    }) + ';');
 
   });
 
   });
 
   $('#ipeUninstall').click(function () {
 
   $('#ipeUninstall').click(function () {
Line 514: Line 522:
 
       content: '插件目前处于不断开发的阶段,很多功能并不完善,可能没有达到您的预期,肥肠抱歉!由衷希望您可以等待插件继续被开发、完善,并希望您可以为我提供宝贵的建议!<br>插件在安装时会同时保存一些cookie,如果您使用的是手机那么将非常难以删除,因此我提供了这个可以清理残余项的卸载功能。<br><span style="font-size:small"><b>注意</b>:本功能尚处于测试阶段,使用正则表达式简单粗暴地从您的个人js页识别并删除插件相关的代码,有可能会卸载失败,建议按照插件说明页手动删除插件。</span>',
 
       content: '插件目前处于不断开发的阶段,很多功能并不完善,可能没有达到您的预期,肥肠抱歉!由衷希望您可以等待插件继续被开发、完善,并希望您可以为我提供宝贵的建议!<br>插件在安装时会同时保存一些cookie,如果您使用的是手机那么将非常难以删除,因此我提供了这个可以清理残余项的卸载功能。<br><span style="font-size:small"><b>注意</b>:本功能尚处于测试阶段,使用正则表达式简单粗暴地从您的个人js页识别并删除插件相关的代码,有可能会卸载失败,建议按照插件说明页手动删除插件。</span>',
 
       buttons: [{
 
       buttons: [{
          label: '废话少说,残忍卸载',
+
        label: '废话少说,残忍卸载',
          className: 'btn btn-danger',
+
        className: 'btn btn-danger',
          enableAfter: 5,
+
        enableAfter: 5,
          method: function () {
+
        method: function () {
            mw.loader.load('https://common.wjghj.cn/js/InPageEdit-v2.js/uninstall');
+
          mw.loader.load('https://common.wjghj.cn/js/InPageEdit-v2.js/uninstall');
          }
+
        }
        }, {
+
      }, {
          label: '算了,我暂时不卸载了',
+
        label: '算了,我暂时不卸载了',
          className: 'btn btn-primary',
+
        className: 'btn btn-primary',
          method: function (event, modal) {
+
        method: function (event, modal) {
            modal.close();
+
          modal.close();
          }
 
 
         }
 
         }
 +
      }
 
       ]
 
       ]
 
     });
 
     });
Line 537: Line 545:
 
   }
 
   }
  
   if (typeof(MyInPageEditPreference) !== 'undefined') {
+
   if (typeof (MyInPageEditPreference) !== 'undefined') {
 
     $('.ipe-preference .ssi-buttons .ssi-modalBtn').attr('disabled', '');
 
     $('.ipe-preference .ssi-buttons .ssi-modalBtn').attr('disabled', '');
     if (typeof(MyInPageEditPreference.editMinor) === 'boolean') {
+
     if (typeof (MyInPageEditPreference.editMinor) === 'boolean') {
 
       $('#InPageEditSettingBox #ipeSetMinor').prop('checked', MyInPageEditPreference.editMinor).attr('disabled', '');
 
       $('#InPageEditSettingBox #ipeSetMinor').prop('checked', MyInPageEditPreference.editMinor).attr('disabled', '');
 
     }
 
     }
     if (typeof(MyInPageEditPreference.outSideClose) === 'boolean') {
+
     if (typeof (MyInPageEditPreference.outSideClose) === 'boolean') {
 
       $('#InPageEditSettingBox #ipeSetoutSideClose').prop('checked', MyInPageEditPreference.outSideClose).attr('disabled', '');
 
       $('#InPageEditSettingBox #ipeSetoutSideClose').prop('checked', MyInPageEditPreference.outSideClose).attr('disabled', '');
 
     }
 
     }
     if (typeof(MyInPageEditPreference.editSummary) === 'string') {
+
     if (typeof (MyInPageEditPreference.editSummary) === 'string') {
 
       $('#InPageEditSettingBox #ipeSetSummary').attr('disabled', '').val(MyInPageEditPreference.editSummary);
 
       $('#InPageEditSettingBox #ipeSetSummary').attr('disabled', '').val(MyInPageEditPreference.editSummary);
 
     }
 
     }
Line 565: Line 573:
 
     e.preventDefault();
 
     e.preventDefault();
 
     var $this = $(this),
 
     var $this = $(this),
    href = $this.attr('href'),
+
      href = $this.attr('href'),
    diff = mw.util.getParamValue('diff', href),
+
      diff = mw.util.getParamValue('diff', href),
    curid = mw.util.getParamValue('curid', href),
+
      curid = mw.util.getParamValue('curid', href),
    oldid = mw.util.getParamValue('oldid', href),
+
      oldid = mw.util.getParamValue('oldid', href),
    pagename = mw.util.getParamValue('title', href);
+
      pagename = mw.util.getParamValue('title', href);
 
     ssi_modal.show({
 
     ssi_modal.show({
 
       sizeClass: 'large',
 
       sizeClass: 'large',
Line 576: Line 584:
 
       fitScreen: true,
 
       fitScreen: true,
 
       title: '比较差异:<u>' + pagename + '</u>',
 
       title: '比较差异:<u>' + pagename + '</u>',
       content: '<section id="ipe-diff-table" style="text-align:center;height:400px;font-size:30px;line-height:400px">不要着急,龟速加载中~</section>',
+
       content: '<section id="ipe-diff-table"><div class="ipe-progress" style="width:100%"><div class="progress-bar"></div></div></section>',
 
       buttons: [{
 
       buttons: [{
          className: 'btn btn-secondary',
+
        className: 'btn btn-secondary',
          label: '转到原始比较页面',
+
        label: '转到原始比较页面',
          method: function () {
+
        method: function () {
            location.href = href
+
          location.href = href
          }
 
 
         }
 
         }
 +
      }
 
       ]
 
       ]
 
     });
 
     });
 +
    $('#ipe-diff-table .ipe-progress').css('margin-top','calc(' + $('#ipe-diff-table').parent().css('height') + ' / 2)');
 
     $.ajax({
 
     $.ajax({
 
       url: href,
 
       url: href,
Line 592: Line 601:
 
       },
 
       },
 
       success: function (data) {
 
       success: function (data) {
         $('#ipe-diff-table').attr('style', '').html(data);
+
         $('#ipe-diff-table').html(data);
 
         InPageEdit.articleLink($('#ipe-diff-table .mw-diff-edit a'));
 
         InPageEdit.articleLink($('#ipe-diff-table .mw-diff-edit a'));
 
       }
 
       }
Line 607: Line 616:
 
       return;
 
       return;
 
     var url = $(this).attr('href'),
 
     var url = $(this).attr('href'),
    title = mw.util.getParamValue('title', url),
+
      title = mw.util.getParamValue('title', url),
    section = mw.util.getParamValue('section', url),
+
      section = mw.util.getParamValue('section', url),
    revision = mw.util.getParamValue('oldid', url);
+
      revision = mw.util.getParamValue('oldid', url);
  
 
     // 不是本地编辑链接
 
     // 不是本地编辑链接
Line 639: Line 648:
 
             'class': 'in-page-edit-article-link'
 
             'class': 'in-page-edit-article-link'
 
           })
 
           })
          .text('快速编辑')
+
            .text('快速编辑')
          .click(function () {
+
            .click(function () {
            if (revision !== null) {
+
              if (revision !== null) {
              InPageEdit.edit({
+
                InPageEdit.edit({
                page: title,
+
                  page: title,
                revision: revision
+
                  revision: revision
              });
+
                });
            } else {
+
              } else {
              InPageEdit.edit({
+
                InPageEdit.edit({
                page: title,
+
                  page: title,
                section: section
+
                  section: section
              });
+
                });
            }
+
              }
          }),
+
            }),
 
           $('<span>', {
 
           $('<span>', {
 
             'class': 'in-page-edit-article-link-bracket'
 
             'class': 'in-page-edit-article-link-bracket'
 
           })
 
           })
          .text(']')));
+
            .text(']')));
 
     }
 
     }
 
   });
 
   });
 +
}
 +
/** 载入中模块 **/
 +
InPageEdit.progress = function (title) {
 +
  if (title === false) {
 +
    if ( $('.in-page-edit.loadingbox').length >0 ) ssi_modal.close();
 +
  } else {
 +
    if (typeof (title) === 'undefined') {
 +
      title = '加载中...'
 +
    }
 +
    ssi_modal.show({
 +
      title: title,
 +
      content: '<div class="ipe-progress" style="width:100%"><div class="progress-bar"></div></div>',
 +
      className: 'in-page-edit confirmbox loadingbox',
 +
      sizeClass: 'dialog',
 +
      closeIcon: false,
 +
      outSideClose: false
 +
    });
 +
  }
 
}
 
}
 
/** 常见错误集 **/
 
/** 常见错误集 **/
 
InPageEdit.error = function (code) {
 
InPageEdit.error = function (code) {
 
   var errorTitle = '发生未知错误',
 
   var errorTitle = '发生未知错误',
      errorContent = '错误代码为:'+code+'<br height:"0.5em"/>常见的错误代码请查看<a href="https://www.mediawiki.org/wiki/API:Edit#Possible_errors" target="_blank">这里</a>。大多数情况下刷新页面可以解决问题';
+
    errorContent = '错误代码为:' + code + '<br height:"0.5em"/>常见的错误代码请查看<a href="https://www.mediawiki.org/wiki/API:Edit#Possible_errors" target="_blank">这里</a>。大多数情况下刷新页面可以解决问题';
 
   switch (code) {
 
   switch (code) {
 
     case 'editconflict':
 
     case 'editconflict':
Line 697: Line 724:
 
       label: '作者我X你X!',
 
       label: '作者我X你X!',
 
       className: 'btn btn-danger',
 
       className: 'btn btn-danger',
       method: function(a,modal) {window.open('https://blog.wjghj.cn/index.php/contact')}
+
       method: function (a, modal) { window.open('https://blog.wjghj.cn/index.php/contact') }
     },{
+
     }, {
 
       label: '好的',
 
       label: '好的',
 
       className: 'btn btn-primary',
 
       className: 'btn btn-primary',
       method: function(a,modal) {modal.close()}
+
       method: function (a, modal) { modal.close() }
 
     }]
 
     }]
 
   });
 
   });
Line 709: Line 736:
 
$(function () {
 
$(function () {
 
   var wgUserRights,
 
   var wgUserRights,
  user = mw.config.get('wgUserName');
+
    user = mw.config.get('wgUserName');
 
   new mw.Api().get({
 
   new mw.Api().get({
 
     action: 'query',
 
     action: 'query',
Line 789: Line 816:
 
   $('#ipe-edit-toolbox .ipe-toolbox-btn').click(function () {
 
   $('#ipe-edit-toolbox .ipe-toolbox-btn').click(function () {
 
     switch ($(this).attr('id')) {
 
     switch ($(this).attr('id')) {
    case 'toolbox-toggle':
+
      case 'toolbox-toggle':
      break;
+
        break;
    case 'edit-btn':
+
      case 'edit-btn':
      InPageEdit.edit({
+
        InPageEdit.edit({
        page: mw.config.get('wgPageName'),
+
          page: mw.config.get('wgPageName'),
        revision: mw.config.get('wgRevisionId')
+
          revision: mw.config.get('wgRevisionId')
      });
+
        });
      break;
+
        break;
    case 'redirectfrom-btn':
+
      case 'redirectfrom-btn':
      InPageEdit.redirect('from');
+
        InPageEdit.redirect('from');
      break;
+
        break;
    case 'redirectto-btn':
+
      case 'redirectto-btn':
      InPageEdit.redirect('to');
+
        InPageEdit.redirect('to');
      break;
+
        break;
    case 'preference-btn':
+
      case 'preference-btn':
      InPageEdit.preference();
+
        InPageEdit.preference();
      break;
+
        break;
    case 'deletepage-btn':
+
      case 'deletepage-btn':
      InPageEdit.deletepage();
+
        InPageEdit.deletepage();
      break;
+
        break;
    case 'renamepage-btn':
+
      case 'renamepage-btn':
      InPageEdit.renamepage();
+
        InPageEdit.renamepage();
      break;
+
        break;
    case 'about-btn':
+
      case 'about-btn':
      mw.loader.load('https://common.wjghj.cn/js/InPageEdit-v2.js/about');
+
        mw.loader.load('https://common.wjghj.cn/js/InPageEdit-v2.js/about');
      break;
+
        break;
    default:
+
      default:
      ssi_modal.notify('info', {
+
        ssi_modal.notify('info', {
        className: 'in-page-edit',
+
          className: 'in-page-edit',
        title: '暂未推出',
+
          title: '暂未推出',
        content: '抱歉,这个功能还在开发中~'
+
          content: '抱歉,这个功能还在开发中~'
      });
+
        });
 
     }
 
     }
 
   });
 
   });

Revision as of 20:42, 21 November 2019

/**
 *『Wjghj Project Static』
 * This _JavaScript_ code is from https://common.wjghj.cn
 * GNU GENERAL PUBLIC LICENSE 3.0
 *
 * MediaWiki JS Plugin: In Page Edit
 * Version: See version-info file
 * Author: 机智的小鱼君
 * Url:
 ** https://github.com/Dragon-Fish/wjghj-wiki/edit/master/Gadgets/in-page-edit
 ** https://common.wjghj.cn/wiki/InPageEdit-v2
 * Logs:
 ** https://github.com/Dragon-Fish/wjghj-wiki/blob/master/Gadgets/in-page-edit/version-info.md
 ** https://common.wjghj.cn/wiki/InPageEdit-v2/version-info
 **/

if (InPageEdit) throw '[InPageEdit] 已经有一个IPE插件在执行了';
// 创建全局函数
var InPageEdit = {};

/** 导入模态框插件 **/
mw.loader.load('https://cdn.bootcss.com/ssi-modal/1.0.27/js/ssi-modal.min.js');
mw.loader.load('https://cdn.bootcss.com/ssi-modal/1.0.27/styles/ssi-modal.min.css', 'text/css');

/** 获取版本信息 **/
mw.loader.load('https://common.wjghj.cn/js/InPageEdit-v2.js/version-info');

/** 样式表 **/
// 皮肤
InPageEdit.skin = function() {
  if (typeof(InPageEditSkin) === 'undefined') {
    var InPageEditSkin = 'ooui';
  }
  var skin = InPageEditSkin.toLowerCase().replace('/\s/g','-');
  switch (skin) {
    case 'wds':
    case 'wikia-design-system':
      mw.loader.load('https://common.wjghj.cn/css/InPageEdit-v2/skin/wds','text/css');
    break;
    default:
      console.warn('%c[InPageEdit] Invalid skin name. Use %cOOJS-UI','color:#f33','color:#f33;font-weight:bold');
    case 'ooui':
    case 'oojs-ui':
      mw.loader.load('https://common.wjghj.cn/css/InPageEdit-v2/skin/ooui','text/css');
    break;
  }
}
// Material icons
mw.loader.load('https://cdn.bootcss.com/material-design-icons/3.0.1/iconfont/material-icons.min.css', 'text/css');

/** InPageEdit主框架 **/
/** 快速编辑模块 **/
InPageEdit.edit = function (option) {
  // 变量
  if (option === undefined)
    option = {};
  var preference = JSON.parse(localStorage.getItem('InPageEditPreference'));
  var editPage = decodeURIComponent(option.page),
    editSection = option.section,
    titleSection = '',
    editRevision = option.revision,
    titleRevision = '',
    editText,
    editSummary = preference.editSummary,
    editMinor = preference.editMinor,
    editNotice = '',
    outSideClose = preference.outSideClose,
    jsonGet = {
      action: 'parse',
      page: editPage,
      prop: 'wikitext',
      format: 'json'
    },
    jsonGetInfo = {
      action: 'query',
      titles: editPage,
      prop: 'revisions|info',
      rvprop: 'timestamp',
      format: 'json'
    },
    jsonPost = {},
    basetimestamp,
    date = new Date(),
    timestamp = date.getTime(),
    now = date.toUTCString(); // 缓存时间戳

  if (editPage === undefined)
    return;
  if (editRevision !== undefined && editRevision !== '' && editRevision !== mw.config.get('wgCurRevisionId')) {
    ssi_modal.notify('warning', {
      className: 'in-page-edit',
      content: '您正在编辑页面的历史版本。',
      title: '提示'
    });
    delete jsonGet.page;
    jsonGet.oldid = editRevision;
    titleRevision = '<span style="font-size:small;">(历史版本:' + editRevision + ')</span>'
  } else {
    if (editSection !== undefined && editSection !== '' && editSection !== null) {
      jsonGet.section = editSection;
      titleSection = '(第' + editSection + '部分)';
    }
  }
  if (typeof (MyInPageEditPreference) !== 'undefined') {
    if (typeof (MyInPageEditPreference.editSummary) === 'string')
      editSummary = MyInPageEditPreference.editSummary;
    if (typeof (MyInPageEditPreference.editMinor) === 'boolean')
      editMinor = MyInPageEditPreference.editMinor;
    if (typeof (MyInPageEditPreference.outSideClose) === 'boolean')
      outSideClose = MyInPageEditPreference.outSideClose;
  }

  // Debug
  console.time('[InPageEdit] Get page content');
  console.info('%c[InPageEdit] Edit function running with params: ', 'color:purple');
  console.table({
    'editPage': editPage,
    'editSection': editSection,
    'titleSection': titleSection,
    'editRevision': editRevision,
    'titleRevision': titleRevision,
    'editSummary': editSummary,
    'editMinor': editMinor,
    'now': now
  });
  // 绑定事件,在尝试离开页面时提示
  $(window).bind('beforeunload', function () {
    return '您输入的内容尚未保存,确定离开此页面吗?';
  });

  // 显示主窗口
  ssi_modal.show({
    title: '正在编辑:<u class="editPage">' + editPage + '</u>' + titleSection + titleRevision,
    content: '<div class="ipe-progress" style="width:100%"><div class="progress-bar"></div></div><section class="editForm"><textarea class="editArea" disabled=""></textarea><label for="editSummary">摘要:</label><input id="editSummary" class="editSummary" placeholder="Edit via InPageEdit~"/><br/><input id="editMinor" class="editMinor" type="checkbox" style=""/><label for="editMinor">小编辑</label></section>',
    outSideClose: outSideClose,
    className: 'in-page-edit ipe-editor timestamp-' + timestamp,
    beforeClose: function (modal) {
      ssi_modal.confirm({
        className: 'in-page-edit confirmbox',
        position: 'top center',
        content: '确定要关闭窗口吗?<br/>此处的编辑将会丢失!',
        okBtn: {
          className: 'btn btn-danger editForm',
          label: '确定'
        },
        cancelBtn: {
          className: 'btn btn-secondary editForm',
          label: '取消'
        }
      },
        function (result) {
          if (result === true) {
            $(window).unbind('beforeunload');
            modal.options.keepContent = false;
            modal.options.beforeClose = '';
            modal.close();
            ssi_modal.notify('error', {
              className: 'in-page-edit',
              position: 'right top',
              title: '取消',
              content: "编辑被取消"
            })
          }
        });
      return false;
    },
    buttons: [{
      label: '预览',
      className: 'btn btn-secondary',
      method: function () {
        var text = $('.editArea').val();
        requestPreview(text)
      }
    }, {
      label: '发布',
      className: 'btn btn-primary',
      method: function () {
        ssi_modal.confirm({
          className: 'in-page-edit confirmbox',
          content: '是否发布',
          okBtn: {
            className: 'btn btn-primary',
            label: '确定'
          },
          cancelBtn: {
            className: 'btn btn-secondary',
            label: '取消'
          },
        },
          function (result) {
            if (result) {
              var text = $('.ipe-editor.timestamp-' + timestamp + ' .editArea').val(),
                minor = $('.ipe-editor.timestamp-' + timestamp + ' .editMinor').prop('checked'),
                section = option.section,
                summary = $('.ipe-editor.timestamp-' + timestamp + ' .editSummary').val();
              postArticle({
                text: text,
                page: editPage,
                minor: minor,
                section: section,
                summary: summary
              });
            }
          })
      }
    }
    ]
  });
  // 获取页面代码
  $('.ipe-editor.timestamp-' + timestamp + ' .editForm').hide();
  new mw.Api().get(jsonGet).then(function (data) {
    console.timeEnd('[InPageEdit] Get page content');
    if (data.error === undefined) {
      editText = data.parse.wikitext['*']
    } else {
      console.timeEnd('[InPageEdit] Get page content');
      editText = '<!-- 警告:无法获取页面内容 -->';
      console.error('[InPageEdit]警告:无法获取页面内容');
    }
    $('.ipe-editor.timestamp-' + timestamp + ' .ipe-progress').hide();
    $('.ipe-editor.timestamp-' + timestamp + ' .editForm').fadeIn(500);
    $('.ipe-editor.timestamp-' + timestamp + ' .editArea').val(editText).attr('disabled', false);
  }).fail(function (data) {
    console.timeEnd('[InPageEdit] Get page content');
    editText = '<!-- 警告:无法获取页面内容 -->';
    console.error('[InPageEdit]警告:无法获取页面内容');
    $('.ipe-editor.timestamp-' + timestamp + ' .ipe-progress').hide();
    $('.ipe-editor.timestamp-' + timestamp + ' .editForm').fadeIn(500);
    $('.ipe-editor.timestamp-' + timestamp + ' .editArea').val(editText).attr('disabled', false);
  });
  // 设定状态
  if (editMinor) {
    $('.ipe-editor.timestamp-' + timestamp + ' .editMinor').attr('checked', 'checked');
  }
  $('.ipe-editor.timestamp-' + timestamp + ' .editSummary').val(editSummary.replace(/\$section/ig, $($.parseHTML(titleSection)).text()).replace(/\$oldid/ig, $($.parseHTML(titleRevision)).text()));

  // 获取页面最后编辑时间戳
  new mw.Api().get(jsonGetInfo).then(function (data) {
    if (data && data.query && data.query.pages) {
      var info = data.query.pages;
      for (var key in info) {
        if (key !== '-1') {
          if (info[key].touched) {
            basetimestamp = info[key].touched;
          }
        }
      }
    }
    if (!basetimestamp) {
      basetimestamp = now;
    }
  });

  // 获取编辑提示
  new mw.Api().get({
    action: 'query',
    meta: 'allmessages',
    ammessages: 'Editnotice-' + mw.config.get('wgNamespaceNumber'),
    amlang: mw.config.get('wgUserLanguage') || mw.config.get('wgContentLanguage')
  }).then(function (data) {
    editNotice = data.query.allmessages[0]['*'];
    new mw.Api().post({
      action: 'parse',
      preview: true,
      text: editNotice
    }).then(function (data) {
      editNotice = '<div class="edit-notice" style="display:none">' + data.parse.text['*'] + '</div>';
      $('.ipe-editor.timestamp-' + timestamp + ' .editArea').before(editNotice);
      $('.ipe-editor.timestamp-' + timestamp + ' .edit-notice').show(400);
    });
  });

  // 预览模块
  function requestPreview(text) {
    var timestamp2 = new Date().getTime();
    console.time('[InPageEdit] Request preview');
    ssi_modal.show({
      className: 'in-page-edit previewbox',
      content: '<section id="InPageEditPreview" data-timestamp="' + timestamp2 + '">正在读取预览……</section>',
      title: '预览'
    });
    new mw.Api().post({
      action: "parse",
      title: editPage,
      text: text,
      prop: "text",
      preview: true,
      format: "json"
    }).then(function (data) {
      console.timeEnd('[InPageEdit] Request preview');
      var content = data.parse.text['*'];
      $('#InPageEditPreview[data-timestamp="' + timestamp2 + '"]').html(content);
    }).fail(function () {
      console.timeEnd('[InPageEdit] Request preview');
      console.warn('[InPageEdit] 预览失败');
      $('#InPageEditPreview[data-timestamp="' + timestamp2 + '"]').html('获取预览时发生错误!');
    });
  }

  // 发布编辑模块
  function postArticle(pValue) {
    InPageEdit.progress('正在发布编辑...');
    jsonPost = {
      action: 'edit',
      basetimestamp: basetimestamp,
      starttimestamp: now,
      text: pValue.text,
      title: pValue.page,
      token: mw.user.tokens.get('editToken'),
      minor: pValue.minor,
      summary: pValue.summary,
      errorformat: 'plaintext'
    }
    if (pValue.section !== undefined && pValue.section !== '' && pValue.section !== null) {
      jsonPost.section = pValue.section;
      delete jsonPost.basetimestamp;
    }
    // Debug
    console.info('[InPageEdit] Submitting with params: ');
    console.table(jsonPost);
    new mw.Api().post(jsonPost).then(function (data) {
      InPageEdit.progress(false);
      $(window).unbind('beforeunload');
      ssi_modal.notify('success', {
        className: 'in-page-edit',
        position: 'right top',
        title: '成功',
        content: '成功,正在刷新页面。'
      });
      if (pValue.page === mw.config.get('wgPageName')) {
        window.location = mw.config.get('wgArticlePath').replace('$1', pValue.page);
      } else {
        window.location.reload();
      }
    }).fail(function (errorCode, feedback, errorThrown) {
      InPageEdit.progress(false);
      ssi_modal.notify('error', {
        className: 'in-page-edit',
        position: 'right top',
        closeAfter: {
          time: 15
        },
        title: '警告',
        content: '发布编辑时发生错误:<br/><span style="font-size:amall">' + errorThrown.errors[0]['*'] + '(<code>' + errorThrown.errors[0]['code'] + '</code>)</span>'
      });
      console.error('[InPageEdit] Submit failed: \nCode: ' + errorThrown.errors[0]['code'] + '\nDescription: ' + errorThrown.errors[0]['*']);
      InPageEdit.error(errorThrown.errors[0]['code']);
    });
  }

}

/** 快速重定向模块 **/
InPageEdit.redirect = function (type) {
  var json = {
    action: 'edit',
    minor: JSON.parse(localStorage.getItem('InPageEditPreference')).editMinor,
    token: mw.user.tokens.get('editToken'),
    errorformat: 'plaintext'
  },
    summary = '快速重定向 → [[:$1]] //使用API进行的操作,请核查本次编辑',
    text = '#REDIRECT [[:$1]]',
    question,
    target;
  switch (type) {
    case 'to':
      json.title = mw.config.get('wgPageName');
      question = '您要将 <b>' + mw.config.get('wgPageName') + '</b> 重定向到哪个页面?';
      break;
    case 'from':
      question = '您要将哪个页面重定向到 <b>' + mw.config.get('wgPageName') + '</b>?';
      json.text = text.replace('$1', mw.config.get('wgPageName'));
      json.summary = summary.replace('$1', mw.config.get('wgPageName'));
      break;
  }
  ssi_modal.show({
    className: 'in-page-edit quick-redirect confirmbox',
    sizeClass: 'dialog',
    title: '快速重定向',
    content: question + '<br><input id="redirect-page" style="width:80%;margin: 0 10%;" onclick="$(this).css(\'box-shadow\',\'\')"/>',
    buttons: [{
      label: '确定',
      className: 'btn btn-primary',
      method: function () {
        var input = $('#redirect-page').val();
        if (input === '' || input === mw.config.get('wgPageName')) {
          $('#redirect-page').css('box-shadow', '0 0 4px red');
        } else {
          switch (type) {
            case 'to':
              json.summary = summary.replace('$1', input);
              json.text = text.replace('$1', input);
              break;
            case 'from':
              json.title = input;
              break;
          }

          new mw.Api().post(json).done(function () {
            ssi_modal.notify('success', {
              className: 'in-page-edit',
              content: '已创建重定向!<br/>正在刷新页面……',
              title: '成功'
            });
            window.location.reload();
          });
        }
      }
    }
    ]
  });
}

/** 删除页面模块 **/
InPageEdit.deletepage = function () {
  if (!hasRight('delete')) {
    ssi_modal.dialog({
      title: '权限不足',
      content: '抱歉,您没有删除页面(<code>delete</code>)的权限。',
      className: 'in-page-edit quick-deletepage confirmbox',
      okBtn: {
        className: 'btn btn-primary'
      }
    });
    return;
  }
  var page = mw.config.get('wgPageName'),
    reasonType,
    reason = '不再需要的页面';

  ssi_modal.show({
    className: 'in-page-edit quick-delete confirmbox',
    sizeClass: 'dialog',
    title: '删除页面',
    content: '<b style="color:#b00">本功能暂未实装</b><section id="InPageEditDeletepage">您要将 <b>' + page + '</b> 删除的理由?<br/><select id="reasonType" style="width: 23%;padding: 2px;margin: 2px;"><option value="其他">其他</option></select><input id="reason" style="width: 73%;padding: 2px;margin: 2px;" value="' + reason + '"><br/><input id="confirm" type="checkbox"/><label for="confirm">确定删除</label></section>'
  });
}

/** 重命名模块 **/
InPageEdit.renamepage = function () {
  if (!hasRight('move')) {
    ssi_modal.dialog({
      title: '权限不足',
      content: '抱歉,您没有移动页面(<code>move</code>)的权限。',
      className: 'in-page-edit quick-renamepage confirmbox',
      okBtn: {
        className: 'btn btn-primary'
      }
    });
    return;
  }
  var from = mw.config.get('wgPageName'),
    to,
    reason = '重命名页面 → [[:$1]] //使用API进行的操作,请核查本次编辑',
    movetalk,
    movesubpages,
    noredirect,
    ignorewarnings;

  ssi_modal.show({
    className: 'in-page-edit quick-rename confirmbox',
    sizeClass: 'dialog',
    title: '重命名页面',
    content: '<b style="color:#b00">本功能暂未实装</b><section id="InPageEditRename"><label id="moveTo">您要将 <b>' + from + '</b> 重命名为?<br/><input style="width:90%"></label><br/><input type="checkbox" id="movetalk" checked="checked"/><label for="movetalk">同时移动讨论页(若存在)</label><br/><input id="movesubpages" type="checkbox" checked="checked"/><label for="movesubpages">同时移动子页面(若存在)</label><br/><input id="noredirect" type="checkbox"/><label for="noredirect">不在本页面创建到新页面的重定向</label><br/><input id="ignorewarnings"type="checkbox"/><label for="ignorewarnings">忽视所有警告</label><br/><label id="reason">编辑摘要(<code>$1</code>将替换为新页面名)<br/><input style="width:90%" value="' + reason + '"/></label></section>'
  });
}

/** 个人设置模块 **/
InPageEdit.preference = function () {
  var settings = JSON.parse(localStorage.getItem('InPageEditPreference')),
    minor = settings.editMinor,
    summary = settings.editSummary,
    outSideClose = settings.outSideClose;

  ssi_modal.show({
    title: 'InPageEdit偏好设定',
    content: '<section id="InPageEditSettingBox"><b>InPageEdit编辑器</b><br><input id="ipeSetoutSideClose" type="checkbox"/> <label for="ipeSetoutSideClose">点击编辑窗口外侧关闭编辑窗口</label><br><input id="ipeSetMinor" type="checkbox"/> <label for="ipeSetMinor">默认标记所有编辑为小编辑</label><br><b>摘要</b><br><label>默认编辑摘要(<code>$section</code>将被替换为“第x部分”;<code>$oldid</code>将替换为“历史版本:版本号”)<input id="ipeSetSummary" value="' + summary + '" style="width:100%"/></label><br><b>卸载InPageEdit-v2</b><br><button class="btn btn-danger" id="ipeUninstall">卸载InPageEdit</button><hr><span style="font-size:10px;line-height:5px">您可以在这里保存InPageEdit-v2的个人偏好。<br><b>注意</b>:这些设置保存在您的浏览器本地,这意味着你必须在不同的设备上分别保存设置。<a href="javascript:;" id="ipeSaveLocalShow">永久保存</a>(不推荐)</span></section>',
    sizeClass: 'dialog',
    className: 'in-page-edit ipe-preference',
    buttons: [{
      label: '重置',
      className: 'btn btn-danger',
      method: function () {
        $('#InPageEditSettingBox #ipeSetoutSideClose').prop('checked', true);
        $('#InPageEditSettingBox #ipeSetMinor').prop('checked', false);
        $('#InPageEditSettingBox #ipeSetSummary').val('[InPageEdit] 没有编辑摘要 $section$oldid');
      }
    }, {
      label: '保存',
      className: 'btn btn-primary',
      method: function (a, modal) {
        localStorage.setItem('InPageEditPreference', JSON.stringify({
          outSideClose: $('#InPageEditSettingBox #ipeSetoutSideClose').prop('checked'),
          editMinor: $('#InPageEditSettingBox #ipeSetMinor').prop('checked'),
          editSummary: $('#InPageEditSettingBox #ipeSetSummary').val()
        }));

        modal.close();
      }
    }
    ]
  });
  $('#ipeSaveLocalShow').click(function () {
    ssi_modal.dialog({
      className: 'in-page-edit confirmbox',
      content: '<section id="ipeSaveLocal"><b>不推荐这种做法</b><br>在您个人js页调用本插件的代码的上方添加以下代码:<br><input style="width:100%" readonly="readonly" onclick="$(this).select()"/><br/>注意:虽然这样做免去了更换设备时需要重新进行设置的麻烦,但我们没有参数纠错功能,您必须自行确认json设定是否正确。</section>',
      okBtn: {
        className: 'btn btn-primary'
      }
    });
    $('#ipeSaveLocal input').val('var MyInPageEditPreference = ' + JSON.stringify({
      outSideClose: $('#InPageEditSettingBox #ipeSetoutSideClose').prop('checked'),
      editMinor: $('#InPageEditSettingBox #ipeSetMinor').prop('checked'),
      editSummary: $('#InPageEditSettingBox #ipeSetSummary').val()
    }) + ';');
  });
  $('#ipeUninstall').click(function () {
    ssi_modal.show({
      className: 'in-page-edit',
      sizeClass: 'dialog',
      title: '卸载InPageEdit-v2',
      content: '插件目前处于不断开发的阶段,很多功能并不完善,可能没有达到您的预期,肥肠抱歉!由衷希望您可以等待插件继续被开发、完善,并希望您可以为我提供宝贵的建议!<br>插件在安装时会同时保存一些cookie,如果您使用的是手机那么将非常难以删除,因此我提供了这个可以清理残余项的卸载功能。<br><span style="font-size:small"><b>注意</b>:本功能尚处于测试阶段,使用正则表达式简单粗暴地从您的个人js页识别并删除插件相关的代码,有可能会卸载失败,建议按照插件说明页手动删除插件。</span>',
      buttons: [{
        label: '废话少说,残忍卸载',
        className: 'btn btn-danger',
        enableAfter: 5,
        method: function () {
          mw.loader.load('https://common.wjghj.cn/js/InPageEdit-v2.js/uninstall');
        }
      }, {
        label: '算了,我暂时不卸载了',
        className: 'btn btn-primary',
        method: function (event, modal) {
          modal.close();
        }
      }
      ]
    });
  });
  if (outSideClose) {
    $('#InPageEditSettingBox #ipeSetoutSideClose').prop('checked', true);
  }
  if (minor) {
    $('#InPageEditSettingBox #ipeSetMinor').prop('checked', true);
  }

  if (typeof (MyInPageEditPreference) !== 'undefined') {
    $('.ipe-preference .ssi-buttons .ssi-modalBtn').attr('disabled', '');
    if (typeof (MyInPageEditPreference.editMinor) === 'boolean') {
      $('#InPageEditSettingBox #ipeSetMinor').prop('checked', MyInPageEditPreference.editMinor).attr('disabled', '');
    }
    if (typeof (MyInPageEditPreference.outSideClose) === 'boolean') {
      $('#InPageEditSettingBox #ipeSetoutSideClose').prop('checked', MyInPageEditPreference.outSideClose).attr('disabled', '');
    }
    if (typeof (MyInPageEditPreference.editSummary) === 'string') {
      $('#InPageEditSettingBox #ipeSetSummary').attr('disabled', '').val(MyInPageEditPreference.editSummary);
    }
    ssi_modal.dialog({
      content: '您使用自己的个人js保存了设定参数,请浏览<a href="' + mw.config.get('wgArticlePath').replace('$1', 'Special:Mypage/common.js') + '">您的个人js页</a>修改。<br>我们不推荐保存静态的设定,虽然这样做免去了更换设备时需要重新进行设置的麻烦,但因为暂时没有参数纠错功能,您必须自行确认json设定是否正确。',
      className: 'in-page-edit confirmbox',
      okBtn: {
        className: 'btn btn-primary'
      }
    });
  }
}

/** 快速页面差异模块 **/
InPageEdit.viewDiff = function () {
  // 加载样式表
  mw.loader.load(mw.config.get('wgScriptPath') + '/load.php?modules=mediawiki.legacy.shared|mediawiki.diff.styles&only=styles', 'text/css')
  $('.mw-changeslist-groupdiff, .mw-changeslist-diff, .mw-changeslist-diff-cur, .mw-history-histlinks a').click(function (e) {
    e.preventDefault();
    var $this = $(this),
      href = $this.attr('href'),
      diff = mw.util.getParamValue('diff', href),
      curid = mw.util.getParamValue('curid', href),
      oldid = mw.util.getParamValue('oldid', href),
      pagename = mw.util.getParamValue('title', href);
    ssi_modal.show({
      sizeClass: 'large',
      className: 'in-page-edit',
      fixedHeight: true,
      fitScreen: true,
      title: '比较差异:<u>' + pagename + '</u>',
      content: '<section id="ipe-diff-table"><div class="ipe-progress" style="width:100%"><div class="progress-bar"></div></div></section>',
      buttons: [{
        className: 'btn btn-secondary',
        label: '转到原始比较页面',
        method: function () {
          location.href = href
        }
      }
      ]
    });
    $('#ipe-diff-table .ipe-progress').css('margin-top','calc(' + $('#ipe-diff-table').parent().css('height') + ' / 2)');
    $.ajax({
      url: href,
      data: {
        action: 'render'
      },
      success: function (data) {
        $('#ipe-diff-table').html(data);
        InPageEdit.articleLink($('#ipe-diff-table .mw-diff-edit a'));
      }
    });
  });
}

/** 获取段落编辑以及编辑链接 **/
InPageEdit.articleLink = function (element) {
  if (element === undefined)
    element = $('#mw-content-text a:not(.new)');
  element.each(function (i) {
    if ($(this).attr('href') === undefined)
      return;
    var url = $(this).attr('href'),
      title = mw.util.getParamValue('title', url),
      section = mw.util.getParamValue('section', url),
      revision = mw.util.getParamValue('oldid', url);

    // 不是本地编辑链接
    if (url.split('/')['2'] !== location.href.split('/')['2'] && url.substr(0, 1) !== '/')
      return;

    // 不是 index.php?title=FOO 形式的url
    if (title === null) {
      var splitStr = mw.config.get('wgArticlePath').replace('$1', '');
      if (splitStr === '/') {
        splitStr = mw.config.get('wgServer').substring(mw.config.get('wgServer').length - 4) + '/';
      }
      title = url.split(splitStr).pop().split('?')['0'];
    }

    if (mw.util.getParamValue('action', url) === 'edit' && title !== undefined && section !== 'new') {
      $(this).after(
        $('<span>', {
          'class': 'in-page-edit-article-link-group'
        }).append(
          $('<span>', {
            'class': 'in-page-edit-article-link-pipe'
          }).text('|'),
          $('<span>', {
            'class': 'in-page-edit-article-link-bracket'
          }).text('['),
          $('<a>', {
            'href': 'javascript:void(0)',
            'class': 'in-page-edit-article-link'
          })
            .text('快速编辑')
            .click(function () {
              if (revision !== null) {
                InPageEdit.edit({
                  page: title,
                  revision: revision
                });
              } else {
                InPageEdit.edit({
                  page: title,
                  section: section
                });
              }
            }),
          $('<span>', {
            'class': 'in-page-edit-article-link-bracket'
          })
            .text(']')));
    }
  });
}
/** 载入中模块 **/
InPageEdit.progress = function (title) {
  if (title === false) {
    if ( $('.in-page-edit.loadingbox').length >0 ) ssi_modal.close();
  } else {
    if (typeof (title) === 'undefined') {
      title = '加载中...'
    }
    ssi_modal.show({
      title: title,
      content: '<div class="ipe-progress" style="width:100%"><div class="progress-bar"></div></div>',
      className: 'in-page-edit confirmbox loadingbox',
      sizeClass: 'dialog',
      closeIcon: false,
      outSideClose: false
    });
  }
}
/** 常见错误集 **/
InPageEdit.error = function (code) {
  var errorTitle = '发生未知错误',
    errorContent = '错误代码为:' + code + '<br height:"0.5em"/>常见的错误代码请查看<a href="https://www.mediawiki.org/wiki/API:Edit#Possible_errors" target="_blank">这里</a>。大多数情况下刷新页面可以解决问题';
  switch (code) {
    case 'editconflict':
      errorTitle = '检测到编辑冲突';
      errorContent = '在您打开编辑窗口到保存的期间,有用户修改了页面的内容,建议您现在复制您的编辑内容,重新打开编辑窗口检查并再次提交您的内容';
      break;
    case 'badtoken':
      errorTitle = '编辑令牌错误';
      errorContent = '对不起,重获取token的方案正在开发中……';
      break;
    case 'pagedeleted':
      errorTitle = '页面已被删除';
      errorContent = '在您保存页面时该页面已被删除,请备份您的编辑内容并检查删除日志,确认具体情况';
      break;
    case 'protectedpage':
    case 'protectednamespace-interface':
      errorTitle = '无权编辑页面';
      errorContent = '该页面已被保护以防止编辑和其他操作,请在讨论页提交编辑申请或联系wiki管理员';
      break;
    case 'ratelimited':
      errorTitle = '触发频率保护';
      errorContent = '您的提交频率触发了保护性上限,请稍候再试';
      break;
  }
  errorContent = errorContent + '<hr/><span style="font-size:small;line-height: 4px;">若此问题多次出现,请复制编辑内容并使用MediaWiki原生编辑页面发布您的编辑。若您愿意,请提供控制台的错误代码片段或者截图给作者,谢谢!</span>';

  ssi_modal.show({
    sizeClass: 'dialog',
    className: 'in-page-edit confirmbox',
    title: errorTitle,
    content: errorContent,
    buttons: [{
      label: '作者我X你X!',
      className: 'btn btn-danger',
      method: function (a, modal) { window.open('https://blog.wjghj.cn/index.php/contact') }
    }, {
      label: '好的',
      className: 'btn btn-primary',
      method: function (a, modal) { modal.close() }
    }]
  });
}

/** 获取用户权限信息 **/
$(function () {
  var wgUserRights,
    user = mw.config.get('wgUserName');
  new mw.Api().get({
    action: 'query',
    list: 'users',
    usprop: 'rights',
    ususers: user
  }).done(function (data) {
    wgUserRights = data.query.users[0]['rights'];
    $('body').attr('data-rights', wgUserRights);
  });
});
function hasRight(right) {
  if ($('body').attr('data-rights').indexOf(right) > -1) {
    return true;
  } else {
    return false;
  }
}
/** 初始化 **/
$(function () {
  // 由于兼容性问题,阻止Fandom平台
  if (mw.config.get('skin') === 'oasis') {
    new BannerNotification('注意,当前版本InPageEdit扩展在Fandom平台有严重兼容性问题。<br/>目前不建议在Fandom使用,后续的支持计划请暂定于Fandom社区统一计划(UCP)完成后。', 'warn').show();
    $('.ssi-stack').remove();
    console.error('%c[InPageEdit] 警告:暂不支持的平台。', 'color:darkred;font-size:1.2em;font-weight:bold');
    return;
  }
  /** 加载皮肤 **/
  InPageEdit.skin();
  /** 额外的模块 **/
  // 快速页面差异模块
  InPageEdit.viewDiff();
  /** Toolbox模块 **/
  // 检测是否为文章页
  if (mw.config.get('wgIsArticle') === false) {
    console.warn('%c[InPageEdit] 不是文章页面,插件已暂停执行。', 'color:orange;font-size:1.2em;font-weight:bold');
    return;
  }

  // 读取设定
  if (localStorage.getItem('InPageEditPreference') === null) {
    // 没有保存任何设置
    var ipePreference = {};
    ipePreference.outSideClose = true;
    ipePreference.editMinor = false;
    ipePreference.editSummary = '[InPageEdit] 没有编辑摘要 $section$oldid';
    localStorage.setItem('InPageEditPreference', JSON.stringify(ipePreference));
  }

  // ipe工具盒
  $('body').append(
    '<div id="ipe-edit-toolbox">' +

    // group1 上方的一列按钮
    '<div class="btn-group">' +
    '<div class="btn-tip-group"><div class="btn-tip">快速编辑</div><div id="edit-btn" class="ipe-toolbox-btn material-icons">edit</div></div>' +
    '<div class="btn-tip-group"><div class="btn-tip">重定向至此</div><div id="redirectfrom-btn" class="ipe-toolbox-btn material-icons">flight_land</div></div>' +
    '<div class="btn-tip-group"><div class="btn-tip">重定向到</div><div id="redirectto-btn" class="ipe-toolbox-btn material-icons">flight_takeoff</div></div>' +
    '<div class="btn-tip-group"><div class="btn-tip">自定义设置</div><div id="preference-btn" class="ipe-toolbox-btn material-icons">settings</div></div>' +
    '</div>' +

    // group2 左边的一排按钮
    '<div class="btn-group group2"><div style="display: flex;">' +
    '<div class="btn-tip-group"><div class="btn-tip">删除本页面</div><div id="deletepage-btn" class="ipe-toolbox-btn material-icons">delete_forever</div></div>' +
    '<div class="btn-tip-group"><div class="btn-tip">重命名页面</div><div id="renamepage-btn" class="ipe-toolbox-btn material-icons">format_italic</div></div>' +
    '<div class="btn-tip-group"><div class="btn-tip">关于&帮助</div><div id="about-btn" class="ipe-toolbox-btn material-icons">help_outline</div></div>' +
    '</div></div>' +

    '<div class="ipe-toolbox-btn material-icons" id="toolbox-toggle">add</div>' +
    '</div>');
  $('#ipe-edit-toolbox #toolbox-toggle').click(function () {
    $('#ipe-edit-toolbox #toolbox-toggle').toggleClass('opened');
    $('#ipe-edit-toolbox .btn-group').toggle(100);
  });
  $('body > *:not(#ipe-edit-toolbox)').click(function () {
    $('#ipe-edit-toolbox #toolbox-toggle').removeClass('opened');
    $('#ipe-edit-toolbox .btn-group').hide(100);
  });
  $('#ipe-edit-toolbox .ipe-toolbox-btn').click(function () {
    switch ($(this).attr('id')) {
      case 'toolbox-toggle':
        break;
      case 'edit-btn':
        InPageEdit.edit({
          page: mw.config.get('wgPageName'),
          revision: mw.config.get('wgRevisionId')
        });
        break;
      case 'redirectfrom-btn':
        InPageEdit.redirect('from');
        break;
      case 'redirectto-btn':
        InPageEdit.redirect('to');
        break;
      case 'preference-btn':
        InPageEdit.preference();
        break;
      case 'deletepage-btn':
        InPageEdit.deletepage();
        break;
      case 'renamepage-btn':
        InPageEdit.renamepage();
        break;
      case 'about-btn':
        mw.loader.load('https://common.wjghj.cn/js/InPageEdit-v2.js/about');
        break;
      default:
        ssi_modal.notify('info', {
          className: 'in-page-edit',
          title: '暂未推出',
          content: '抱歉,这个功能还在开发中~'
        });
    }
  });
  // 加载段落编辑模块
  InPageEdit.articleLink();
  // 花里胡哨的加载提示
  console.info('%c[InPageEdit] 加载完毕,です~ ', 'color:green;font-size:1.2em;font-weight:bold');
});