MediaWiki:Gadget-addMe-v2.js

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
/**
* WARNING: GLOBAL GADGET FILE
* Compiled from source at https://gitlab.wikimedia.org/repos/commtech/add-me
* 
* Script:         AddMe.js
* Version:        0.1.1
* Author:         MusikAnimal
* License:        GPL-3.0-or-later
* Documentation:  [[meta:Meta:AddMe]]
* Source:         https://gitlab.wikimedia.org/repos/commtech/add-me
* 
* 
**/
"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
var _Dialog = _interopRequireDefault(require("./Dialog"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
// <nowiki>
/**
 * @class
 * @property {jQuery} $content
 * @property {mw.Api} api
 * @property {string} project Which key to use when loading the configuration and translations.
 * @property {Array.<Object>} config Config fetched from AddMe.configPage.
 * @property {Dialog} dialog
 */
var AddMe = /*#__PURE__*/function () {
  /**
   * @constructor
   * @param {jQuery} $content The content area as provided by the mediawiki.content hook.
   */
  function AddMe($content) {
    _classCallCheck(this, AddMe);
    if (!$content.find('.addme-button')) {
      return;
    }
    this.$content = $content;
    this.api = new mw.Api();
    this.project = null;
    this.config = {
      // Which page to post the comment to. If null or blank, it uses the current page.
      page: '',
      // The anchor of the section of the page to post the comment to.
      'section-anchor': null,
      // Maximum level of section to process; used to help prevent putting comments in the
      //   wrong place if there are multiple sections with the same title.
      'max-section-level': null,
      // Wikitext to prepend before the comment, such as a {{support}} template.
      'prepend-content': '* ',
      // Whether to skip checking if the user already commented on the page.
      'skip-dup-check': false,
      // Whether to restrict use of AddMe to logged-in users.
      'require-login': true,
      // Regular expression used to removed unwanted content from the comment
      //   (such as a {{support}} template).
      'remove-content-regex': null,
      // Edit summary to use.
      'edit-summary': '',
      // Where to link to when there are unrecoverable errors.
      'error-report-page': 'Meta talk:AddMe'
    };
    this.dialog = null;
  }

  /**
   * Add the click listener.
   */
  _createClass(AddMe, [{
    key: "addListeners",
    value: function addListeners() {
      var _this = this;
      this.$content.find('.addme-button').on('click', function (e) {
        _this.setInternalMessages();
        _this.project = e.target.dataset.addmeProject;
        if (!_this.project) {
          return _this.showAlert(_this.log('addme-error-button-project'));
        }
        _this.config.page = e.target.dataset.addmePage || _this.config.page || mw.config.get('wgPageName');
        // Use underscores since we'll be comparing against wgPageName again.
        _this.config.page = _this.config.page.replace(/\s/g, '_');

        // To prevent abuse, ensure the target page is a subpage of the current page.
        // Presumably the subpage is transcluded.
        if (e.target.dataset.addmePage && !_this.config.page.includes(mw.config.get('wgPageName') + '/') && _this.config.page !== mw.config.get('wgPageName')) {
          return _this.showAlert(_this.log('addme-error-subpage'));
        }
        _this.fetchConfig().then(_this.showDialog.bind(_this)).fail(_this.showAlert.bind(_this));

        // Lazy-load postEdit module (only shown on desktop).
        if (!OO.ui.isMobile()) {
          mw.loader.using('mediawiki.action.view.postEdit');
        }
      });
    }

    /**
     * Fetch the configuration and messages, then set the appropriate class properties.
     *
     * @return {jQuery.Deferred}
     */
  }, {
    key: "fetchConfig",
    value: function fetchConfig() {
      var _this2 = this;
      var dfd = $.Deferred();
      if (mw.messages.get('addme-submit') && this.config.page) {
        // Everything is already loaded.
        return dfd.resolve();
      }
      var langPageEn = "".concat(AddMe.messagesPage, "/en"),
        langPageLocal = "".concat(AddMe.messagesPage, "/").concat(mw.config.get('wgUserLanguage')),
        titles = [AddMe.configPage,
        // Always fetch English so that we have fallbacks for each message.
        // The payloads are small.
        langPageEn];
      if (mw.config.get('wgUserLanguage') !== 'en') {
        // Fetch the translation in the user's language, if not English.
        titles.push(langPageLocal);
      }
      this.api.get({
        action: 'query',
        prop: 'revisions',
        titles: titles,
        rvprop: 'content',
        rvslots: 'main',
        format: 'json',
        formatversion: 2
      }).then(function (resp) {
        var messagesLocal = {},
          messagesEn = {};
        resp.query.pages.forEach(function (page) {
          if (page.missing) {
            switch (page.title) {
              case AddMe.configPage:
                dfd.reject(_this2.log("Missing configuration page [[".concat(AddMe.configPage, "]]")));
                break;
              case langPageEn:
                dfd.reject(_this2.log("Missing base language page [[".concat(langPageEn, "]]")));
                break;
              case langPageLocal:
                // Don't reject in this case and instead log a warning to the console.
                _this2.log("Localization for '".concat(mw.config.get('wgUserLanguage'), "' missing at [[").concat(langPageLocal, "]]"), 'warn');
                break;
            }
          } else {
            var pageObj = page.revisions[0].slots.main;
            var parsedContent = _this2.parseJSON(page.title, pageObj.content);
            if (pageObj.contentmodel === 'json') {
              // We know it's the config page.
              _this2.config = Object.assign(_this2.config, parsedContent["default"] || {}, parsedContent[_this2.project]);
            } else if (page.title === langPageLocal && mw.config.get('wgUserLanguage') !== 'en') {
              messagesLocal = Object.assign(parsedContent.messages["default"] || {}, parsedContent.messages[_this2.project]);
            } else {
              messagesEn = Object.assign(parsedContent.messages["default"] || {}, parsedContent.messages[_this2.project]);
            }
          }
        });

        // Prefix all messages with 'addme-' so there's no clashing with MW messages.
        var messages = Object.assign({}, messagesEn, messagesLocal);
        Object.keys(messages).forEach(function (key) {
          delete Object.assign(messages, _defineProperty({}, "addme-".concat(key), messages[key]))[key];
        });
        mw.messages.set(messages);
        dfd.resolve();
      });
      return dfd;
    }

    /**
     * Add raw English error messages to mw.messages. These are fatal errors
     * not intended to be seen by users (i.e. AddMe was misconfigured), so
     * they are not setup for translation.
     */
  }, {
    key: "setInternalMessages",
    value: function setInternalMessages() {
      if (mw.messages.exists('addme-error-alert')) {
        // Already loaded;
        return;
      }

      // Add in configuration error messages that don't need to be translatable.
      mw.messages.set({
        'addme-error-alert': 'There was an error with the AddMe gadget: <i>$1</i>\n' + "Please report this issue at [[".concat(this.config['error-report-page'], "]]."),
        'addme-error-parse': 'Unable to parse the configuration page [[$1]]. ' + 'There may have been a recent change that contains invalid JSON.',
        'addme-error-button-project': "Button is missing the 'data-addme-project' attribute.",
        'addme-error-subpage': "The 'data-addme-page' attribute is not a subpage of the current page.",
        'addme-error-section-missing': 'The "$1" section is missing from [[$2]]. ' + 'Please correct this error or report this issue at [[$3]].'
      });
    }

    /**
     * The content model of the messages page is wikitext so that it can be used with
     * Extension:Translate. Consequently, it's easy to break things. This just does
     * a try/catch and indicates the likely culprit to the user.
     *
     * @param {string} title
     * @param {string} content
     * @return {Object}
     */
  }, {
    key: "parseJSON",
    value: function parseJSON(title, content) {
      try {
        // Remove HTML that's added for untranslated messages.
        content = content.replace(/<span lang="en".*?>(.*?)<\/span>/g, '$1');
        return JSON.parse(content);
      } catch (_unused) {
        this.showAlert('addme-error-parse', title);
      }
    }

    /**
     * Show the submission dialog.
     */
  }, {
    key: "showDialog",
    value: function showDialog() {
      var _this3 = this;
      if (this.config['require-login'] && !mw.config.get('wgUserName')) {
        OO.ui.alert(mw.msg('addme-error-login'));
        return;
      }

      // Get the OOUI window manager, which opens and closes the dialog.
      var windowManager = OO.ui.getWindowManager();

      // Instantiate and show the dialog.
      if (!this.dialog) {
        this.dialog = new _Dialog["default"](this);
        windowManager.addWindows([this.dialog]);
      }

      // Open the dialog and add focus to the textarea.
      windowManager.openWindow(this.dialog).opened.then(function () {
        return _this3.dialog.textarea.focus();
      });
    }

    /**
     * Submit the comment and watch status to the page.
     *
     * @param {string} comment
     * @param {boolean} watch
     * @return {jQuery.Deferred}
     */
  }, {
    key: "submit",
    value: function submit(comment, watch) {
      var dfd = $.Deferred();

      // Cleanup the comment.
      comment = comment.replace('~~~~', '');
      if (this.config['remove-content-regex']) {
        comment = comment.replace(new RegExp(this.config['remove-content-regex']), '');
      }
      if (/^(?:\*|#)/.test(this.config['prepend-content'])) {
        // Replace newlines with <p> tags, otherwise it will break the <ul> list.
        comment = comment.replace(/\n+/g, '<p>');
      }
      comment = "\n".concat(this.config['prepend-content']).concat(comment.trim(), " ~~~~");
      this.findSection().then(this.updateSection.bind(this, comment, watch))["catch"](function (message) {
        if (message.constructor.name === 'OoUiError') {
          message = message.message;
        }
        dfd.reject(new OO.ui.Error(message || mw.msg('addme-error-save')));
      }).then(dfd.resolve);
      return dfd;
    }

    /**
     * Purge the contents of the page. This is necessary when the comment
     * was added to a transcluded page.
     *
     * @return {jQuery.Deferred|jQuery.Promise}
     */
  }, {
    key: "purgePage",
    value: function purgePage() {
      if (this.config.page === mw.config.get('wgPageName')) {
        // We're on the same page as the comment is on, so no need to purge.
        return $.Deferred().resolve();
      }
      return this.api.post({
        action: 'purge',
        titles: mw.config.get('wgPageName')
      });
    }

    /**
     * Reload the content on the page with the newly added comment.
     * Some of this was copied from Extension:DiscussionTools / controller.js
     *
     * FIXME: This seems probably too heavy of an operation for the end of the Wishlist Survey
     *   which can have up to 50+ large subpages transcluded on the same page.
     *
     * @return {jQuery.Promise}
     */
  }, {
    key: "reloadContent",
    value: function reloadContent() {
      var _this4 = this;
      return this.api.get({
        action: 'parse',
        // HACK: we need 'useskin' so that reply links show (T266195)
        useskin: mw.config.get('skin'),
        mobileformat: OO.ui.isMobile(),
        uselang: mw.config.get('wgUserLanguage'),
        prop: ['text', 'revid', 'jsconfigvars'],
        page: mw.config.get('wgPageName'),
        // HACK: Always display reply links afterwards, ignoring preferences etc.
        dtenable: '1',
        formatversion: 2
      }).then(function (data) {
        // Actually replace the content.
        _this4.$content.find('.mw-parser-output').first().replaceWith(data.parse.text);
        mw.config.set(data.parse.jsconfigvars);

        // Update revision ID for other gadgets that rely on it being accurate.
        mw.config.set({
          wgCurRevisionId: data.parse.revid,
          wgRevisionId: data.parse.revid
        });

        // eslint-disable-next-line no-jquery/no-global-selector
        $('#t-permalink a, #coll-download-as-rl a').each(function () {
          var url = new URL(this.href);
          url.searchParams.set('oldid', data.parse.revid);
          $(this).attr('href', url.toString());
        });
        mw.hook('wikipage.content').fire(_this4.$content);
        _this4.addListeners();
        if (OO.ui.isMobile()) {
          mw.notify(mw.msg('addme-feedback'));
        } else {
          // postEdit is currently desktop only
          mw.hook('postEdit').fire({
            message: mw.msg('addme-feedback')
          });
        }
      }).fail(function () {
        // Comment was saved, but reloading failed. Redirect user to the (sub)page instead.
        window.location = mw.util.getUrl(_this4.config.page);
      });
    }

    /**
     * Add the comment to the given section.
     *
     * @param {string} comment
     * @param {boolean} watch
     * @param {Object} section
     * @param {string} timestamp
     * @return {jQuery.Promise}
     */
  }, {
    key: "updateSection",
    value: function updateSection(comment, watch, section, timestamp) {
      return this.api.postWithEditToken({
        action: 'edit',
        title: this.config.page,
        section: section.index,
        summary: this.config['edit-summary'],
        starttimestamp: timestamp,
        nocreate: true,
        watchlist: watch ? 'watch' : 'nochange',
        appendtext: comment
      });
    }

    /**
     * Fetch section headers from this.config.page, and locate the one we're trying to edit.
     * If no section header constraint is configured, we assume the final section.
     * If a section header is configured but not found, an error is shown to the user.
     *
     * @return {jQuery.Deferred<Object,string>} Deferred promise resolving with section object
     *   and the current server timestamp.
     */
  }, {
    key: "findSection",
    value: function findSection() {
      var _this5 = this;
      var dfd = $.Deferred();
      this.api.get({
        format: 'json',
        formatversion: 2,
        action: 'parse',
        prop: 'sections|wikitext',
        page: this.config.page,
        curtimestamp: true,
        // FIXME: may not work if the source language page is not '/en'?
        uselang: 'en'
      }).done(function (result) {
        var sections = result.parse.sections;
        // Locate the section we're trying to edit.
        var section;
        if (_this5.config['section-anchor']) {
          // eslint-disable-next-line no-shadow
          section = sections.find(function (section) {
            var withinMaxLevel = _this5.config['max-section-level'] ? section.toclevel <= _this5.config['max-section-level'] : true;
            return section.anchor === _this5.config['section-anchor'] && withinMaxLevel;
          });
          if (!section) {
            dfd.reject(new OO.ui.Error(mw.message('addme-error-section-missing', _this5.config['section-anchor'], _this5.config.page, _this5.config['error-report-page']).parseDom(), {
              recoverable: false
            }));
          }
        } else {
          // If no section was configured, fallback to using the last section.
          section = sections[sections.length - 1];
        }
        if (!_this5.config['skip-dup-check'] && !_this5.dialog.alreadyVoted && _this5.checkForDupComment(result.parse.wikitext)) {
          _this5.dialog.alreadyVoted = true;
          dfd.reject(new OO.ui.Error(mw.msg('addme-error-dup-comment'), {
            recoverable: true,
            warning: true
          }));
        }
        dfd.resolve(section, result.curtimestamp);
      })["catch"](function (response) {
        var logMsg = "There was an error when fetching section titles for [[".concat(_this5.config.page, "]]"),
          msg = 'error-save',
          recoverable = true;
        if (response === 'missingtitle') {
          logMsg = "The page [[".concat(_this5.config.page, "]] is missing.");
          msg = 'error-fatal';
          recoverable = false;
        }
        _this5.log(logMsg);
        dfd.reject(
        // Messages that can be used here:
        // * addme-error-save
        // * addme-error-fatal
        new OO.ui.Error(mw.msg("addme-".concat(msg), _this5.config['error-report-page']), {
          recoverable: recoverable
        }));
      });
      return dfd;
    }

    /**
     * Test if the user has already commented in the given wikitext.
     *
     * @param {string} wikitext
     * @return {boolean}
     */
  }, {
    key: "checkForDupComment",
    value: function checkForDupComment(wikitext) {
      var regEscape = function regEscape(str) {
        return str.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&');
      };
      var regexp = new RegExp(regEscape(this.config['prepend-content']) + '.*?' + regEscape(mw.config.get('wgUserName')) + '.*?\\(UTC\\)');
      return regexp.test(wikitext);
    }

    /**
     * Show an error to the user using an OOUI alert dialog.
     *
     * @param {string} key Message key (i.e. from this.setInternalMessages) or plain text.
     * @param {...string} params
     */
  }, {
    key: "showAlert",
    value: function showAlert(key) {
      var _mw2;
      var msg = key;
      for (var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
        params[_key - 1] = arguments[_key];
      }
      if (mw.messages.exists(key)) {
        var _mw;
        // Messages that can be used here:
        // * addme-error-alert
        // * addme-error-button-project
        // * addme-error-parse
        // * addme-error-section-missing
        // * addme-error-subpage
        msg = (_mw = mw).msg.apply(_mw, [key].concat(params));
      }
      OO.ui.alert((_mw2 = mw).message.apply(_mw2, ['addme-error-alert', msg].concat(params)).parseDom(), {
        title: 'Something went wrong'
      });
    }

    /**
     * Log an error to the console.
     *
     * @param {string} key Message key.
     * @param {string} level One of: 'info', 'warn', 'error' (default)
     * @return {string} The given message key.
     */
  }, {
    key: "log",
    value: function log(key) {
      var level = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'error';
      // Messages that can be used here:
      // * addme-error-button-project
      // * addme-error-fatal
      // * addme-error-save
      // * addme-error-subpage
      // eslint-disable-next-line no-console
      console[level]("[AddMe] ".concat(mw.messages.exists(key) ? mw.msg(key) : key));
      return key;
    }
  }]);
  return AddMe;
}();
/**
 * Entry point, called after the 'wikipage.content' hook is fired.
 *
 * @param {jQuery} $content
 */
_defineProperty(AddMe, "configPage", 'MediaWiki:Gadget-addMe-config.json');
_defineProperty(AddMe, "messagesPage", 'MediaWiki:Gadget-addMe-messages');
function init($content) {
  Promise.all([
  // Resource loader modules
  mw.loader.using(['oojs-ui', 'mediawiki.util', 'mediawiki.api', 'mediawiki.jqueryMsg']),
  // Page ready
  $.ready]).then(function () {
    var addMe = new AddMe($content);
    addMe.addListeners();

    // Remove listener so that AddMe is only instantiated once.
    mw.hook('wikipage.content').remove(init);
  });
}
mw.hook('wikipage.content').add(init);
// </nowiki>

},{"./Dialog":2}],2:[function(require,module,exports){
"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _get() { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get.bind(); } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(arguments.length < 3 ? target : receiver); } return desc.value; }; } return _get.apply(this, arguments); }
function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
/**
 * @class
 * @property {AddMe} addMe
 * @property {boolean} alreadyVoted
 */
var Dialog = /*#__PURE__*/function (_OO$ui$ProcessDialog) {
  _inherits(Dialog, _OO$ui$ProcessDialog);
  var _super = _createSuper(Dialog);
  /**
   * @param {AddMe} addMeContext
   * @constructor
   */
  function Dialog(addMeContext) {
    var _this;
    _classCallCheck(this, Dialog);
    _this = _super.call(this);
    _this.addMe = addMeContext;
    _this.alreadyVoted = false;

    // Messages that aren't available in the static context.
    Dialog.title = mw.msg('addme-title');
    Dialog.actions = [{
      action: 'submit',
      label: mw.msg('addme-submit'),
      flags: ['primary', 'progressive']
    }, {
      label: mw.msg('addme-cancel'),
      flags: 'safe'
    }];

    // Add properties needed by the ES5-based OOUI inheritance mechanism.
    // This roughly simulates OO.inheritClass()
    Dialog.parent = Dialog["super"] = OO.ui.ProcessDialog;
    OO.initClass(OO.ui.ProcessDialog);
    Dialog["static"] = Object.create(OO.ui.ProcessDialog["static"]);
    Object.keys(Dialog).forEach(function (key) {
      Dialog["static"][key] = Dialog[key];
    });
    return _this;
  }

  /**
   * @param {...*} args
   * @override
   */
  _createClass(Dialog, [{
    key: "initialize",
    value: function initialize() {
      var _get2;
      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }
      (_get2 = _get(_getPrototypeOf(Dialog.prototype), "initialize", this)).call.apply(_get2, [this].concat(args));
      this.editFieldset = new OO.ui.FieldsetLayout();
      this.content = new OO.ui.PanelLayout({
        padded: true,
        expanded: false
      });
      this.content.$element.append(this.editFieldset.$element);
      this.textarea = new OO.ui.MultilineTextInputWidget({
        placeholder: mw.msg('addme-placeholder-comment')
      });
      this.watchCheckbox = new OO.ui.CheckboxInputWidget({
        selected: false
      });
      var formElements = [new OO.ui.FieldLayout(this.textarea, {
        label: mw.msg('addme-description'),
        align: 'top'
      }), new OO.ui.FieldLayout(this.watchCheckbox, {
        label: mw.msg('addme-watch-page'),
        align: 'inline'
      })];
      this.editFieldset.addItems(formElements);
      var parsedBody = mw.message('addme-body').parseDom();
      this.content.$element.append("<p>".concat(parsedBody.html() || parsedBody.text(), "</p>"));
      this.$body.append(this.content.$element);
    }

    /**
     * @param {string} action
     * @override
     */
  }, {
    key: "getActionProcess",
    value: function getActionProcess(action) {
      var _this2 = this;
      return _get(_getPrototypeOf(Dialog.prototype), "getActionProcess", this).call(this, action).next(function () {
        if (action === 'submit') {
          return _this2.addMe.submit(_this2.textarea.getValue(), _this2.watchCheckbox.isSelected());
        }
        return _get(_getPrototypeOf(Dialog.prototype), "getActionProcess", _this2).call(_this2, action);
      }).next(function () {
        if (action === 'submit') {
          return _this2.addMe.purgePage().then(_this2.addMe.reloadContent.bind(_this2.addMe)).then(function () {
            _this2.close({
              action: action
            });
          });
        }
        return _get(_getPrototypeOf(Dialog.prototype), "getActionProcess", _this2).call(_this2, action);
      });
    }

    /**
     * @param {Object} data
     * @override
     */
  }, {
    key: "getSetupProcess",
    value: function getSetupProcess(data) {
      var _this3 = this;
      return _get(_getPrototypeOf(Dialog.prototype), "getSetupProcess", this).call(this, data).next(function () {
        _this3.textarea.setValue('');
        _this3.alreadyVoted = false;
      });
    }
  }]);
  return Dialog;
}(OO.ui.ProcessDialog);
_defineProperty(Dialog, "name", 'addmeDialog');
_defineProperty(Dialog, "size", 'medium');
module.exports = Dialog;

},{}]},{},[1]);