MediaWiki:Common.js

Revision as of 23:51, 21 November 2018 by JP (talk | contribs)

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: Go to Menu → Settings (Opera → Preferences on a Mac) and then to Privacy & security → Clear browsing data → Cached images and files.
// Local script url
mw.loader.load( '/index.php?title=MediaWiki:SortTableFilter.js&action=raw&ctype=text/javascript' );

// Local script url
mw.loader.load( '/index.php?title=MediaWiki:sortabletable.js&action=raw&ctype=text/javascript' );

///////////////////////
// Table Filter/Sort //
///////////////////////
/**
 * @description Table Filter/Sort
 * TODO ?replace by jQuery plugin datatable?
 *
 * @requires $.resource()
 * @requires $.jI18n.en
 * @returns {undefined}
 */
window.initTableFilterSort = function (){ // see MediaWiki:SortTableFilter.js
/* Note: problem is auto-inserted <tbody></tbody> by the browser: must be removed and
   replaced by thead + tbody. jQuery.unwrap() was not successful */
   // add possibly more classes from http://www.javascripttoolbox.com/lib/table/documentation.php
  // Note: only applies to non-nested tables
  var jAutotables = $('table.table-autosort, table.table-autofilter, table-autostripe,table-sorted-asc,table-sorted-desc, table-filtered');
  if (jAutotables.length) {
    // Note: in MediaWiki:SortTableFilter.js 'SortTableFilter_InputFilterTitle' was not recognized
    $.extend(true, $.jI18n, {
      en: {
        SortTableFilter_AutoSortTitle : 'Click to sort',
        SortTableFilter_FilterAllLabel: 'Filter: All',
        SortTableFilter_InputFilterTitle: 'Filter text (case sensitive, uses reg. expressions)'
      },
      de: {
        SortTableFilter_AutoSortTitle : 'Zum Sortieren klicken',
        SortTableFilter_FilterAllLabel: 'Zeige: alle',
        SortTableFilter_InputFilterTitle: 'Text filtern (GROß/klein!, nutzt reg. Ausdrücke)'
      }
    });
    // get sortable/filterable here already otherwise multiple th-filters
    $.getScript(mw.config.get( 'wgServer' ) + mw.config.get( 'wgScript' ) + '?title=MediaWiki:SortTableFilter.js&action=raw&ctype=text/javascript',
      function(){return true;});
    // modify tables to introduce thead structure
    jAutotables.each(function(index){ //TODO simplify code? if()…
      // There may or may not be a tbody around tr. NOTE: $.unwrap() does not work here!
      // Memo: find('tr th') finds th, .parent() retrieves tr! .wrapAll will wrap inside DOM, not in return value! .detach() returns detached
      // OK in FF 3.6 and IE 7-8, not in IE6 (like the old code)
      // FURTHER WORK: Ideally, all normal tr td should remain in a tbody.
      var jThis = $(this),
        jThead = jThis.find('tr th').parent().detach(),
        jTfoot = jThis.find('tr[class=tfoot] td').parent().detach(),// remove it from the DOM
        jTbody = jThis.find('tbody:first');
      if (jTbody.length===0) {
        jThis.children().wrapAll('<tbody/>');
        jTbody = jThis.find('tbody:first');
      }
      jTbody.before($('<thead/>').append(jThead));
      if (jTfoot.length) {
        jTbody.after($('<tfoot/>').append(jTfoot));
      }
      // th with class="input" gives an input field instead of selections
      $(this).find('th[class=input]').append('<input name="filter" title="'+$.resource('SortTableFilter_InputFilterTitle')+'" size="8" onkeyup="Table.filter(this,this)">');
    });// end each()
  } // END if any autotable
};

/**
 * @description: Collapse the TOC using id="toc-autocollapse"
 * @returns {undefined}
 */
window.initTOCautocollapse = function () {
  if ($('#toc-autocollapse').length) {
    $('#togglelink').click();
  }
};// end initTOCautocollapse()

/**
 * 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
 */
window.prepareSpecialContact4Info = function () {
  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()


///////////////////////
// specific to  http://offene-naturfuehrer.de
// Page-specific scripts:
switch (mw.config.get( 'wgPageName' )) { // Minimize the pages on which the code will be loaded
  // vielleicht später auch woanders, d.h. als vorgewählte Suche auf Taxaseiten beispielsweise?
  case 'Datenquellen':
  case 'Hilfe:Datenquellen':
  case 'Online-Überprüfung_von_Bestimmungen':
  case 'Hilfe:Online-Überprüfung_von_Bestimmungen':
  case 'Tipps_zur_Bildersuche':
  case 'Hilfe:Tipps_zur_Bildersuche':

  case 'Spezial:Suche':
    mw.loader.load( '/w/index.php?title=MediaWiki:SearchTools.js&action=raw&ctype=text/javascript' );
    break;
  case 'Hilfe:Nummerierungen_im_jKey_abändern_(Lead_Nummern)':
    mw.loader.load( '/w/index.php?title=MediaWiki:JKeyRenumberingTool.js&action=raw&ctype=text/javascript' );
    break;
  case 'Hilfe:Konvertierung_geschachtelt-eingerückter_Schlüssel_in_das_ON-Format':
  case 'Testseite':
    mw.loader.load( '/w/index.php?title=MediaWiki:JKeyTextToLeadTemplateTool.js&action=raw&ctype=text/javascript' );;
    break;
}

// Page-specific scripts more flexible:
if (mw.config.get('wgPageName').match(/^Basismerkmale_für/i)
    || mw.config.get('wgPageName').match(/^Vorlage:Character_State/i)
    || mw.config.get('wgPageName').match(/^Vorlage:Character_Definition/i)
) {
  mw.loader.load( '/w/index.php?title=MediaWiki:ToolGetRandomId.js&action=raw&ctype=text/javascript' );;
}

/*
  See also https://www.mediawiki.org/w/index.php?title=ResourceLoader/Legacy_JavaScript&oldid=2090764
  When document is completely loaded
 */
jQuery(document).ready(function($) {
  reference_footnote_tooltips();
  initImageZooming();
  initTargetHighlighting(); // page-internal jumps
  initmoveTOC(); // TOC CSS position fixed or static
  initTOCautocollapse(); // auto collapse on #toc-autocollapse e.g. Template:Artinformation BiolFlor
  prepareSpecialContact4Info(); // check from-Email at Special:Contact
  // specific to  http://offene-naturfuehrer.de
    initTableFilterSort(); // tests internally whether table with corresponding classes exist
    mw.loader.load( mw.config.get('wgScript') + '?title=MediaWiki:AddNewOpenMediaFileVersion.js&action=raw&ctype=text/javascript' );;// namespace specific button on top to upload file at OpenMedia
  if(mw.config.get( 'wgAction' )==='view') {
    if($('.decisiontree').length !== 0) {
      mw.loader.load( mw.config.get('wgScript') + '?title=MediaWiki:JKeyRenderLanguageTaggedText2wgUserLanguage.js&action=raw&ctype=text/javascript' );;
    }
  }
  switch(mw.config.get( 'wgAction' )) {
    case 'edit':
    case 'view':
    /* case 'submit': does not work somehow in MW. 1.20.7 */
    init_character_ui_tabs();
  }
  // page specific
  if(mw.config.get( 'wgAction' )==='formedit'
  || mw.config.get( 'wgCanonicalSpecialPageName' )==='FormEdit'){
   // initConfirmDeleteSubform();
    markHiddenFormFields();
    initUiTabsInForms();
  }
  initCluetips();
  // specific to  http://offene-naturfuehrer.de
  initCollapseBox(); //collapsible parts
}); // end $(document).ready()
// </syntaxhighlight>
/**
 * Footenote tooltips from <references>
 * @description Footnotes as unformatted tooltip - from it.wikipedia.org under same license
 * Note (2015-12-21 14:19:20): Use of 'addOnloadHook' is deprecated. Use jQuery instead.
 * @returns {undefined}
 */
window.reference_footnote_tooltips = function () {
  var sups = document.getElementsByTagName('sup');
  for (var i=0; i < sups.length; i++) {
    var note_id = sups[i].childNodes[0].href;
    if (note_id && (note_id.indexOf('#') !== -1)) {
      note_id = document.getElementById(note_id.substr(note_id.indexOf('#')+1));
      if (note_id) {
        if (document.all) {
          sups[i].title = note_id.innerText;
          sups[i].childNodes[0].title = note_id.innerText;
        } else {
          sups[i].title = note_id.textContent;
        }
      }
    }
  }
};
/**
 * @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: {
    ClueTip_newWindow :              '(New Window …)',
    ClueTip_toolTipClose  :          'Click to close',
    ClueTip_toolTipNewWindow :       '(click to open content in a new window or tab)',
    ClueTip_toolTipNoContentLoadable:'<i>No content could be loaded</i>',
    CollapseBox_captionCollapse :        '&nbsp;(show less)&nbsp;',
    CollapseBox_captionExpand :          '&nbsp;(more...)&nbsp;',
    CollapseBox_toolTipCollapse :        '(click to hide information below)',
    CollapseBox_toolTipExpand :          '(click to show more information below)',
    HeadingLink_toolTipHeadingLink:      'Click to show (permanent) link to this headline', // MediaWiki:Gadget-HeadingLink
    HeadingLink_toolTipHeadingLinkHelp:  '(1) Normal link to this head line or (2) the permanent link with version number:',// MediaWiki:Gadget-HeadingLink
    ImageZoom1st_iconCloseWindow :        'https://upload.wikimedia.org/wikipedia/commons/8/87/Close_icon_default.jpg',
    ImageZoom1st_iconCloseWindowHover :   'https://upload.wikimedia.org/wikipedia/commons/d/d0/Close_icon_hover.jpg',
    ImageZoom1st_imageMetadataLink :      '(Information about Creator, License and Copyright)',
    ImageZoom1st_toolTipImageZooming :    'Images can be enlarged by clicking on it',
    ImageZoom1st_zoomNotPossible :        '(This image can not be further enlarged)',
    // see MediaWiki:Jquery.zoomImage.js
    ImageZoom2nd_iconMagnifier: 'https://species-id.net/o/media/f/f7/Iviewer.zoom_in.gif',
    ImageZoom2nd_iconMagnifierHover: 'https://species-id.net/o/media/5/5c/Iviewer.zoom_out.gif',
    ImageZoom2nd_iconLoader:  'https://upload.wikimedia.org/wikipedia/commons/d/de/Ajax-loader.gif',
    ImageZoom2nd_toolTipLoad :  '(click to load largest available image; this may take considerable time to load)',
    ImageZoom2nd_textZoomOrig:  'Zooming facility',
    MoveTOC_toolTipFloatleft : 'floating on the left side',
    MoveTOC_toolTipFloatright: 'floating on the right side',
    MoveTOC_toolTipNavigatePagetop : 'Top of page',
    MoveTOC_toolTipUnfloat: 'back to default position',
    // see MediaWiki:jKey.js
    jKey_expandAll :              'Show all extras',
    jKey_iconOverview  :          'https://upload.wikimedia.org/wikipedia/commons/thumb/2/22/View-pause_Gion_simple.svg/20px-View-pause_Gion_simple.svg.png',
    jKey_iconResume  :            'https://upload.wikimedia.org/wikipedia/commons/thumb/4/49/View-playback_Gion_simple.svg/20px-View-playback_Gion_simple.svg.png',
    jKey_iconStart1st  :          'https://upload.wikimedia.org/wikipedia/commons/thumb/4/49/View-playback_Gion_simple.svg/20px-View-playback_Gion_simple.svg.png',
    jKey_iconStartNew  :          'https://upload.wikimedia.org/wikipedia/commons/thumb/0/05/View-refresh_Gion_simple.svg/20px-View-refresh_Gion_simple.svg.png'
  },
  de: {
    ClueTip_newWindow :              '(Neues Fenster …)',
    ClueTip_toolTipClose  :          'Zum Schließen klicken',
    ClueTip_toolTipNewWindow :       '(klicken um Inhalt in neuem Fenster oder Reiter zu öffnen)',
    ClueTip_toolTipNoContentLoadable:'<i>Leider konnte der Inhalt nicht geladen werden.</i>',
    CollapseBox_captionCollapse :        '&nbsp;(weniger anzeigen)&nbsp;',
    CollapseBox_captionExpand :          '&nbsp;(mehr...)&nbsp;',
    CollapseBox_toolTipCollapse :        '(klicken um Zusatzinformationen zu verbergen)',
    CollapseBox_toolTipExpand :          '(klicken um Zusatzinformationen anzuzeigen)',
    HeadingLink_toolTipHeadingLink:      'Klicken um (permanenten) Link dieser Überschrift anzuzeigen',// MediaWiki:Gadget-HeadingLink
    HeadingLink_toolTipHeadingLinkHelp:  '(1) Link zu dieser Überschrift oder (2) Link mit Versionsnummer:',// MediaWiki:Gadget-HeadingLink
    ImageZoom1st_imageMetadataLink :      '(Informationen zu Autor, Lizenz und Copyright)',
    ImageZoom1st_toolTipImageZooming :    'Bilder können durch Anklicken vergrößert betrachtet werden',
    ImageZoom1st_zoomNotPossible :        '(Dieses Bild kann nicht weiter vergrößert werden)',
    // see MediaWiki:zoomImage.js
    ImageZoom2nd_toolTipLoad :  '(klicken um Originalbild nachzuladen; bei großen Bildern kann dies u. U. langsam sein)',
    ImageZoom2nd_textZoomOrig:  'Vergrößerungsfunktion',
    MoveTOC_toolTipFloatleft : 'Links schwebend',
    MoveTOC_toolTipFloatright: 'Rechts schwebend',
    MoveTOC_toolTipNavigatePagetop : 'Zum Seitenanfang',
    MoveTOC_toolTipUnfloat: 'Zurück zur Normalposition',
    jKey_expandAll :              'Alle Zusatzinformationen zeigen'
  },
  it: {
    ClueTip_toolTipClose  :          'Clicca per chiudere',
    CollapseBox_captionCollapse :        '&nbsp;(mostra di meno)&nbsp;',
    CollapseBox_captionExpand :          '&nbsp;(più...)&nbsp;',
    ImageZoom1st_imageMetadataLink   :    '(Informazione sull’Autore, Licenza e Copyright)',
    ImageZoom1st_toolTipImageZooming :    'Le immagini possono essere ingrandite cliccandoci sopra',
    ImageZoom1st_zoomNotPossible :        '(Al momento non è possibilie ingrandire questa immagine)', // TODO translation see en version
    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
 * @requiers: $.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));
};