ميدياويكي:Gadget-GRequestsUI.js

ملاحظة: بعد الحفظ، قد يلزمك إفراغ الكاش لرؤية التغييرات (إفراغ الكاش الآن).

/*
  إضافة مُقدم الطلبات (GRequestsUI)
  الإضافة ضمن مسابقة الأرز 4 للإسهام التقني
*/
var GRequestsUI = {};
var mwConfig = mw.config.get(['wgUserLanguage', 'wgScript', 'wgUserName']);

GRequestsUI.applyWidgetValues = function(text) {
  return text.replace(/\${(.*?)}/g, function(match, key) {
    return key in GRequestsUI.widgets && GRequestsUI.widgets[key].value !== undefined ?
      GRequestsUI.widgets[key].value :
      match;
  });
};
GRequestsUI.validateRequiredInputs = function() {
  for (let key in GRequestsUI.widgets) {
    if (GRequestsUI.widgets.hasOwnProperty(key)) {
      let widget = GRequestsUI.widgets[key];
      if (widget.required !== undefined) {
        if (widget.required) {
          if (widget.value.trim().length === 0) {
            return new OO.ui.Error('يجب ملء المدخلات المطلوبة');
          }
        }
      }
    }
  }
  return 100;
};
GRequestsUI.openProcessDialog = function() {
  let windowManager = new OO.ui.WindowManager();
  let dialog = new GRequestsUI.ProcessDialog();

  $('body').append(windowManager.$element);
  windowManager.addWindows([dialog]);
  windowManager.openWindow(dialog);
};

GRequestsUI.initProcessDialog = function(title, page, panel, text, summary) {
  function MyProcessDialog(config) {
    MyProcessDialog.parent.call(this, config);
  }
  OO.inheritClass(MyProcessDialog, OO.ui.ProcessDialog);
  MyProcessDialog.static.title = title;
  MyProcessDialog.static.size = 'full';
  MyProcessDialog.static.name = 'GRequestsUIDialog';
  MyProcessDialog.static.actions = [
    { label: 'طلب', flags: 'primary', action: 'run' },
    { label: 'إلغاء', flags: 'safe', action: 'close' }
          ];

  MyProcessDialog.prototype.initialize = function() {
    MyProcessDialog.parent.prototype.initialize.apply(this, arguments);
    this.$body.append(panel.$element);
  };
  MyProcessDialog.prototype.getActionProcess = function(action) {
    var dialog = this;
    if (action) {
      if (action === 'run') {
        return new OO.ui.Process(function() {
          return GRequestsUI.validateRequiredInputs();
        }).next(function() {
          return GRequestsUI.savePage(page, GRequestsUI.applyWidgetValues(text), GRequestsUI.applyWidgetValues(summary)).then(function() {
            dialog.close();
            mw.notify('تم إضافة الطلب بنجاح، سيتم توجيهك لصفحة الطلب خلال ثواني...');
            setTimeout(function() {
              window.location = `/wiki/${page}`;
            }, 1500);
          });
        });
      }
      if (action === 'close') {
        dialog.close();
      }
    }
    return MyProcessDialog.parent.prototype.getActionProcess.call(this, action);
  };

  GRequestsUI.ProcessDialog = MyProcessDialog;
};
GRequestsUI.getPage = function(title) {
  let deferred = $.Deferred();
  GRequestsUI.api.get({
    action: 'query',
    prop: 'revisions',
    titles: title,
    rvprop: 'content',
    formatversion: 2
  }).then(function(response) {
    if (response.query.pages[0].missing) {
      deferred.reject(`الصفحة ${title} غير موجودة.`);
    } else {
      deferred.resolve(response.query.pages[0].revisions[0].content);
    }
  }, function(_, error) {
    deferred.reject(GRequestsUI.api.getErrorMessage(error));
  });
  return deferred.promise();
};

GRequestsUI.savePage = function(title, text, summary) {
  let deferred = $.Deferred();
  GRequestsUI.api.postWithEditToken({
    action: 'edit',
    title: title,
    appendtext: `\n${text}`,
    summary: summary
  }).then(function() {
    deferred.resolve();
  }, function(_, error) {
    deferred.reject([new OO.ui.Error(GRequestsUI.api.getErrorMessage(error))]);
  });
  return deferred.promise();
};


GRequestsUI.init = function() {
  this.config = {};
  this.config.api = {
    parameters: {
      errorformat: 'html',
      errorlang: mwConfig.wgUserLanguage,
      errorsuselocal: true
    }
  };
  this.widgets = {};
  this.InputValues = {};
  this.api = new mw.Api(this.config.api);

};

$('.btnrequestui').on('click', function() {
  let pre = $(this).data('pre');
  let title = $(this).data('title');
  let page = $(this).data('page');
  let elementData = $(this).data();

  try {
    mw.loader.using(['oojs-ui-core', 'oojs-ui-windows'], function() {
    
      GRequestsUI.init();
    
      $.each(elementData, function(key, value) {
        if (key.startsWith("input")) {
          GRequestsUI.InputValues[key.replace(/^input/, '').toLowerCase()] = value;
        }
      });
      $.when($.getJSON(`${mwConfig.wgScript}?action=raw&ctype=application/json&title=${pre}`)).then(function(data) {
    
        let panel = new OO.ui.PanelLayout({
          padded: true,
          expanded: false
        });
        let widgets = data.widgets;
        let text = data.text;
        let summary = data.summary;
        widgets.forEach(function(widget) {
          let WidgetClass = window;
          widget.class.split('.').forEach(function(key) {
            if (WidgetClass && WidgetClass[key]) {
              WidgetClass = WidgetClass[key];
            } else {
              WidgetClass = undefined;
            }
          });
    
          let label;
          if (widget.config.hasOwnProperty('label')) {
            label = widget.config.label;
            delete widget.config.label;
          }
          if (widget.config.hasOwnProperty('value')) {
            widget.config.value = widget.config.value.replace('__USERNAME__', mwConfig.wgUserName);
          } else {
            widget.config.value = '';
          }
          if (GRequestsUI.InputValues.hasOwnProperty(widget.name)) {
            widget.config.value = GRequestsUI.InputValues[widget.name];
          }
          GRequestsUI.widgets[widget.name] = new WidgetClass(widget.config);
    
          const layout = new OO.ui.FieldLayout(GRequestsUI.widgets[widget.name], label ? { label } : {});
    
          panel.$element.append(layout.$element, '<br>');
    
        });
        GRequestsUI.initProcessDialog(title, page, panel, text, summary);
        GRequestsUI.openProcessDialog();
      });
    });
  } catch (e) {
    mw.notify('عذرا، حدث خطأ غير متوقع في إضافة مقدم الطلبات، يرجى المحاولة مرة أخرى لاحقًا.', {type:'error'});
    console.error(e);
  }
  
});