MediaWiki:Common.js

From FloraWiki - le wiki sur la Flore Suisse
Revision as of 23:49, 12 August 2017 by Andreas Plank (Talk | contribs) (fix toggling: based on('afterExpand.mw-collapsible') or on('afterCollapse.mw-collapsible') from jquery.makeCollapsible.js)

Jump to: navigation, search

Note: After saving, 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: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Clear the cache in Tools → Preferences
/*
 * @requires: MediaWiki:JKey.js
 * @requires: MediaWiki:JKeyWikiEditorHelp.js
 * @requires: MediaWiki:JKeyRenderLanguageTaggedText2wgUserLanguage.js
 * @requires: MediaWiki:Mw-customcollapsible.js
 * @requires: MediaWiki:Ui-custom-show-on-select.js
*/

/*global jQuery, document, screen, window, location, navigator, unescape, Image, clearTimeout, addOnloadHook, importScript, setTimeout, appendCSS, mw */ 
/* = settings for JSLint */
/* should go into mw.config: wgPageName, wgServer, wgScript, wgAction, wgCanonicalNamespace */
"use strict"; // set ECMAScript 5 Strict Mode

/**
 * @description: helper function to escape jQuery IDs
 * @param {string} myid HTML ID
 * @returns {@exp;myid@call;replace|String}
 */ 
function jqueryEscapeId(myid) {
  if(myid.substr(0, 1) === "#"){
    return myid.replace(/(:|\.)/g,'\\$1');
  } else {
    return '#' + myid.replace(/(:|\.)/g,'\\$1');
  }
}

/**
 * @namespace resource string dictionary
 * 
 * Note: Commons uses collapse/expand ▲/▼, but this looks better in strict box
 * layouts that in the free-wrapping key statements
 * 
 * Nomenclature proposal: if an extra plugin is used, strings can be designated as
 * “plugin_toolTipSomthing” otherwise just “toolTipSomthing” (global string). So it’s more clear if
 * somebody wants to deactivate a plugin and remove strings from the resource dictionary.
 * @augments $
 * @type object
 */
$.jI18n = {
  en: {
    CollapseBox_captionCollapse :        " (show less) ",
    CollapseBox_captionExpand :          " (more...) ",
    CollapseBox_toolTipCollapse :        "(click to hide information below)",
    CollapseBox_toolTipExpand :          "(click to show more information below)",
    // see MediaWiki:jKey.js
    jKey_expandAll :              "Show all extras",
    jKey_iconOverview  :          "http://upload.wikimedia.org/wikipedia/commons/thumb/2/22/View-pause_Gion_simple.svg/20px-View-pause_Gion_simple.svg.png",
    jKey_iconResume  :            "http://upload.wikimedia.org/wikipedia/commons/thumb/4/49/View-playback_Gion_simple.svg/20px-View-playback_Gion_simple.svg.png",
    jKey_iconStart1st  :          "http://upload.wikimedia.org/wikipedia/commons/thumb/4/49/View-playback_Gion_simple.svg/20px-View-playback_Gion_simple.svg.png",
    jKey_iconStartNew  :          "http://upload.wikimedia.org/wikipedia/commons/thumb/0/05/View-refresh_Gion_simple.svg/20px-View-refresh_Gion_simple.svg.png"
  },
  fr: {
    CollapseBox_captionCollapse :        " (afficher moins) ",
    CollapseBox_captionExpand :          " (plus...) ",
    CollapseBox_toolTipCollapse :        "(cliquez pour masquer les informations ci-dessous)",
    CollapseBox_toolTipExpand :          "(cliquez pour afficher plus d’informations ci-dessous)",
    // see MediaWiki:jKey.js
    jKey_expandAll :              "Afficher tout les figurants"
  },
  de: {
    CollapseBox_captionCollapse :        " (weniger anzeigen) ",
    CollapseBox_captionExpand :          " (mehr...) ",
    CollapseBox_toolTipCollapse :        "(klicken um Zusatzinformationen zu verbergen)",
    CollapseBox_toolTipExpand :          "(klicken um Zusatzinformationen anzuzeigen)",
    jKey_expandAll :              "Alle Zusatzinformationen zeigen"
  },
  it: {
    CollapseBox_captionCollapse :        " (mostra di meno) ",
    CollapseBox_captionExpand :          " (più...) ",
    jKey_expandAll :              "Mostra tutti informazione" //REVISE
  }
};


/**
 * @description Get resource string (text, image URLs) for a given language, based on a string-key
 *  If no resource is defined in a given language for a resource key, the resource for "en" will be returned,
 *  if this is missing as well an error message.
 * @augments $
 * @requires mw.config for getting global variables
 * @param {string} resourceKey key for the resource
 * @returns {String}
 */
$.resource = function (resourceKey) {
    var lang = mw.config.get('wgUserLanguage').split("-")[0]; // language: "pt-BR", "de-formal", etc.
    return ($.jI18n[lang] && $.jI18n[lang][resourceKey] ?
      $.jI18n[lang][resourceKey] :
      ($.jI18n.en[resourceKey]) ? $.jI18n.en[resourceKey] : "MISSING RESOURCE: no $.jI18n.en." + resourceKey + " defined.");
 };
/**
 * @description Create html string for link with image and/or text content
 * @requires $.resource()
 * @param {string} txtResourceKey resource keys (multilingual {@link $.resource()}
 * @param {html} txtContent displayed content of a link
 * @param {url} href
 * @param {string} attributes string of combined other attributes of link element; must use ' as inner quotes, and \" inside event functions
 * @returns {@exp;txtResourceKey@pro;length|String|@exp;txtContent@pro;length@exp;txtResourceKey@pro;length}
 */
$.linkBuilder = function (txtResourceKey, txtContent, href, attributes) {
  return (txtResourceKey.length ? "<a "
    + " href='" + href + "' " 
    + " " + (attributes.length ? attributes : "") + ">"
    + $.resource(txtResourceKey)
    + "</a>" : (txtContent.length ? "<a "
      + " href='" + href + "' "
      + " " + (attributes.length ? attributes : "") + ">"
      + txtContent + 
      "</a>" : "")
  );
};
/**
 * 
 * @param {string} imgResourceKey resource key {@link $.resource()}
 * @param {string} txtResourceKey resource key {@link $.resource()}
 * @param {string} attributes HTML
 * @requires: $.linkBuilder
 * @returns {String}
 */
$.imglinkBuilder = function (imgResourceKey, txtResourceKey, attributes) {
  return (imgResourceKey.length ? "<a "
    + " href='#'" + (attributes.length ? " " + attributes : "") + "><img src='" + $.resource(imgResourceKey) + "' /></a>&nbsp;" : "")
    + $.linkBuilder(txtResourceKey, "", "#", attributes);
};
/**
 * @description return a random integer
 * @param {integer} min
 * @param {integer} max
 * @returns {@exp;@call;parseInt}
 */
$.random = function (min, max) { // NO CHECKS: if(min>max) {return -1;}  if(min==max) {return min;}
  return (min + parseInt(Math.random() * (max - min + 1), 10));
};

/**
 * @description collapse all collapsible key tables on wiki page
 * using the MediaWiki mw-customtoggle mechanism on all CSS class of
 * class="decisiontree"
 * Toggle all
 * 
 * $('.decisiontree').each (function (i, element) { $(element).find('.mw-customtoggle.is-collapsed').trigger('click') });
 * $('.decisiontree').each (function (i, element) { $(element).find('.mw-customtoggle').not('.is-collapsed').trigger('click') });
 * @requires MediaWiki:JKey.js
 * @param {boolean} shallExpandThisKey
 * @param {selector} caller
 * @returns {undefined}
 */
$.toggleAllCollapsible = function (shallExpandThisKey, caller) {
  var $decisionTree = $(caller).closest(".decisiontree");
  // debug log messages
  if ($decisionTree.length) {
    if(shallExpandThisKey) {
      $decisionTree.each (function (i, element) {
        $(element).find('.mw-customtoggle.is-collapsed').trigger('click');
      });
      
    } else {
      $decisionTree.each (function (i, element) {
        $(element).find('.mw-customtoggle').not('.is-collapsed').trigger('click');
      });
    }
  }
};// $.toggleAllCollapsible()

/**
 * @description: collapsible parts: div and tr → Template:Hidden
 *   may be fused later with toggleCollapse
 *   main difference: $.initCollapsebox() uses a switcher defined by the Wikitemplate
 *   and is not using a javascript resource title.
 *   * the only advanced feature it has: collpsible table rows
 *   * otherwise use http://www.mediawiki.org/wiki/RL/DM#jQuery.makeCollapsible
 * @requires $.resources()
 * @requires $.jl18n.en.CollapseBox_toolTipExpand, $.jl18n.en.CollapseBox_toolTipCollapse
 * @returns {Boolean}
 */
$.initCollapsebox = function () {
  /* is nested in: div.collapsebox
                    └ div.switcher
                    └ div.collapsecontent */
  var hasSwitcher = $("div.switcher .show, div.switcher .hide");
  if(hasSwitcher.length){
    $.each(hasSwitcher, function(index){// add tooltip
      hasSwitcher[index].title = hasSwitcher[index].className === "show"? $.resource("CollapseBox_toolTipExpand") : $.resource("CollapseBox_toolTipCollapse");
    });
    $("div.collapsebox div.switcher").on('click',
      function() {
        $(this).nextAll("div.collapsecontent:first").slideToggle(250);
        /* $(this).toggle() does not work in live as toggle is a bind()
            therefore toggle must be bound to a different DOM element */
        $(this).find(".show, .hide").toggle();
      });
    /* is in a table: tr.collapsebox
                        └ div.switcher
                      tr.collapsecontent */
    $("tr.collapsebox div.switcher").on('click',
      function() {
        $(this).closest("tr.collapsebox").nextAll("tr.collapsecontent:first").toggle();
        $(this).find(".show, .hide").toggle();
      });
    // TODO is a better generic check possible?
    if (mw.config.get('wgPageName') === "Spezial:Suche") {
      if (!$(".mw-search-results").length) {
        // open box with additional search possibilities
        $(".switcher .show").trigger('click');
      }
    }
    return true;
  }
  return false;
}// END $.initCollapsebox()

// jKey Source
importScript("MediaWiki:JKey.js");

/**
 * Add a placeholder message and checks on Special:Contact
 * 
 * Due to e-mail configurations all non @mfn-berlin.de addresses fail to work 
 * as from-address on Special:Contact. This functions adds a placeholder and checks the
 * user’s input
 * @requires extension:ContactPage
 * @requires mw.config
 * @requires jQuery
 */
function prepareSpecialContact4Info() {
  var placeholderMessage = "", warningMessageDoesNotWork = "";
  switch (mw.config.get( 'wgCanonicalSpecialPageName' )) {
    case "Contact": // is a Special:Contact page regardless of language
      switch (mw.config.get('wgPageName')) {
        case "Special:Contact":
        case "Spécial:Contact":
          placeholderMessage = 'Leave it empty or add e-mail in message (mfn-berlin.de works only)';
          warningMessageDoesNotWork = 'Only mfn-berlin.de addresses do work. Leave it empty please and add your address in the message. Thank you.';
          break;
        case "Spezial:Kontakt":
          placeholderMessage = 'E-Mail in Nachricht dazu oder leer lassen (nur mfn-berlin.de geht)';
          warningMessageDoesNotWork = 'Nur mfn-berlin.de Adressen können verarbeitet werden. Bitte leer lassen oder E-Mail im Text angeben. Danke.';
          break;
        default:
          placeholderMessage = 'Leave it empty or add e-mail in message (mfn-berlin.de works only)';
          warningMessageDoesNotWork = 'Only mfn-berlin.de addresses do work. Leave it empty please and add your address in the message. Thank you.';
          break;
      }
      // check input
      if (!$('input[name="wpFromAddress"]').val() || $('input[name="wpFromAddress"]').val().match(/.*@mfn-berlin.de/)) {
        $('input[name="wpFromAddress"]')
          .css({'background-color': '', 'cursor': ''})
          .attr({'title': ''});
      } else {
        $('input[name="wpFromAddress"]')
          .css({'background-color': 'orange', 'cursor': 'help'})
          .attr({'title': warningMessageDoesNotWork});
      }
      $('input[name="wpFromAddress"]').on('focusout', function () {
        if (!$(this).val() || $(this).val().match(/.*@mfn-berlin.de/)) {
          $(this).css({'background-color': '', 'cursor': 'help'}).attr({'title': warningMessageDoesNotWork});
        } else {
          $(this).css({'background-color': 'orange', 'cursor': 'help'}).attr({'title': warningMessageDoesNotWork});
        }
      });
      $('input[name="wpFromAddress"]').attr({'placeholder': placeholderMessage});
      
    break;
  }// switch is a contact page
}// end prepareSpecialContact4Info()

if (mw.config.get('wgAction') == "edit" || mw.config.get('wgAction') == "submit" ) {
    importScript("MediaWiki:JKeyWikiEditorHelp.js"); // load help for the wikiEditor
    importScript("MediaWiki:WikiEditor-insert-Zitat.js");// Wizard to insert template:Zitat
    importScript("MediaWiki:WikiEditor-insert-file-with-preview.js");// Wizard to insert file showing a preview
}
// click-text modifications for mw-customcollapsible triggering from outside of mw-collapsible
importScript("MediaWiki:Mw-customcollapsible.js");
importScript("MediaWiki:Ui-custom-show-on-select.js");

// attempted BUG fix mw.Title, should be loaded normally
if (typeof mw.Title==='undefined') {
  mw.loader.load( 'mediawiki.Title' ); // seems not loaded on any page
}
$(document).ready(function() {
  if(mw.config.get( 'wgAction' )==="view") {
    if($(".decisiontree").length != 0) {
      importScript('MediaWiki:JKeyRenderLanguageTaggedText2wgUserLanguage.js');
    }
  }
  $.initCollapsebox(); //collapsible parts
  prepareSpecialContact4Info();
}); // end $(document).ready()