Jump to content

MediaWiki:Common.js: Difference between revisions

From ICANNWiki
Dustin Loup (talk | contribs)
Created page with "Any JavaScript here will be loaded for all users on every page load.: /** * jQuery makeCollapsible * * Dual licensed: * - CC BY 3.0 <http://creativecommons.org/licens..."
 
No edit summary
 
(99 intermediate revisions by 3 users not shown)
Line 1: Line 1:
/* Any JavaScript here will be loaded for all users on every page load. */
// Load jQuery UI using mw.loader
/**
mw.loader.using(['jquery.ui'], function() {
* jQuery makeCollapsible
    console.log("jQuery UI loaded.");
*
});
* Dual licensed:
* - CC BY 3.0 <http://creativecommons.org/licenses/by/3.0>
* - GPL2 <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>
*
* @class jQuery.plugin.makeCollapsible
*/
( function ( $, mw ) {


  /**
// Load WikiEditor and RefToolbar by default
  * Handler for a click on a collapsible toggler.
mw.loader.using(['ext.wikiEditor']).then(function() {
  *
    $(function() {
  * @private
        if (mw.config.get('wgAction') === 'edit' || mw.config.get('wgAction') === 'submit') {
  * @param {jQuery} $collapsible
            $('#wpTextbox1').wikiEditor();
  * @param {string} action The action this function will take ('expand' or 'collapse').
            console.log("WikiEditor auto-initialized.");
  * @param {jQuery|null} [$defaultToggle]
  * @param {Object|undefined} [options]
  */
  function toggleElement( $collapsible, action, $defaultToggle, options ) {
    var $collapsibleContent, $containers, hookCallback;
    options = options || {};


    // Validate parameters
            mw.loader.load('//en.wikipedia.org/w/index.php?title=MediaWiki:Gadget-refToolbar.js&action=raw&ctype=text/javascript');
            console.log("RefToolbar loaded.");
        }
    });
});


     // $collapsible must be an instance of jQuery
// Codex: Open all external links on a new window
    if ( !$collapsible.jquery ) {
mw.loader.using(['mediawiki.util']).then(function () {
      return;
     function openExternalLinks() {
        // General external links
        document.querySelectorAll('a.external').forEach(function (link) {
            link.setAttribute('target', '_blank');
            link.setAttribute('rel', 'noopener noreferrer');
        });
        // Social media links within templates
        document.querySelectorAll('div.external-social a, div.ntldstats a').forEach(function (link) {
            link.setAttribute('target', '_blank');
            link.setAttribute('rel', 'noopener noreferrer');
        });
     }
     }
     if ( action !== 'expand' && action !== 'collapse' ) {
     // Run on page load
      // action must be string with 'expand' or 'collapse'
     mw.hook('wikipage.content').add(openExternalLinks);
      return;
});
     }
    if ( $defaultToggle === undefined ) {
      $defaultToggle = null;
    }
    if ( $defaultToggle !== null && !$defaultToggle.jquery ) {
      // is optional (may be undefined), but if defined it must be an instance of jQuery.
      // If it's not, abort right away.
      // After this $defaultToggle is either null or a valid jQuery instance.
      return;
    }
 
    // Trigger a custom event to allow callers to hook to the collapsing/expanding,
    // allowing the module to be testable, and making it possible to
    // e.g. implement persistence via cookies
    $collapsible.trigger( action === 'expand' ? 'beforeExpand.mw-collapsible' : 'beforeCollapse.mw-collapsible' );
    hookCallback = function () {
      $collapsible.trigger( action === 'expand' ? 'afterExpand.mw-collapsible' : 'afterCollapse.mw-collapsible' );
    };
 
    // Handle different kinds of elements
 
    if ( !options.plainMode && $collapsible.is( 'table' ) ) {
      // Tables
      // If there is a caption, hide all rows; otherwise, only hide body rows
      if ( $collapsible.find( '> caption' ).length ) {
        $containers = $collapsible.find( '> * > tr' );
      } else {
        $containers = $collapsible.find( '> tbody > tr' );
      }
      if ( $defaultToggle ) {
        // Exclude table row containing togglelink
        $containers = $containers.not( $defaultToggle.closest( 'tr' ) );
      }
 
      if ( action === 'collapse' ) {
        // Hide all table rows of this table
        // Slide doesn't work with tables, but fade does as of jQuery 1.1.3
        // http://stackoverflow.com/questions/467336#920480
        if ( options.instantHide ) {
          $containers.hide();
          hookCallback();
        } else {
          $containers.stop( true, true ).fadeOut().promise().done( hookCallback );
        }
      } else {
        $containers.stop( true, true ).fadeIn().promise().done( hookCallback );
      }
 
    } else if ( !options.plainMode && ( $collapsible.is( 'ul' ) || $collapsible.is( 'ol' ) ) ) {
      // Lists
      $containers = $collapsible.find( '> li' );
      if ( $defaultToggle ) {
        // Exclude list-item containing togglelink
        $containers = $containers.not( $defaultToggle.parent() );
      }
 
      if ( action === 'collapse' ) {
        if ( options.instantHide ) {
          $containers.hide();
          hookCallback();
        } else {
          $containers.stop( true, true ).slideUp().promise().done( hookCallback );
        }
      } else {
        $containers.stop( true, true ).slideDown().promise().done( hookCallback );
      }
 
    } else {
      // Everything else: <div>, <p> etc.
      $collapsibleContent = $collapsible.find( '> .mw-collapsible-content' );


      // If a collapsible-content is defined, act on it
// Include a registration link in Minerva/mobile's hamburger menu for logged out users
       if ( !options.plainMode && $collapsibleContent.length ) {
mw.loader.using(['mediawiki.util'], function() {
         if ( action === 'collapse' ) {
    $(function() {
           if ( options.instantHide ) {
       if (mw.config.get('skin') === 'minerva' && mw.user.isAnon()) {
             $collapsibleContent.hide();
         var waitForPersonalMenu = function(callback) {
            hookCallback();
          var $menu = $('#p-personal');
           if ($menu.length) {
             callback($menu);
           } else {
           } else {
             $collapsibleContent.slideUp().promise().done( hookCallback );
             setTimeout(function() {
              waitForPersonalMenu(callback);
            }, 100);
           }
           }
         } else {
         };
           $collapsibleContent.slideDown().promise().done( hookCallback );
        waitForPersonalMenu(function($menu) {
         }
           var regUrl = mw.util.getUrl('Special:UserLogin', { type: 'signup' });
          // Get the message text and remove any curly braces
          var regText = mw.msg('createaccount').replace(/[{}]/g, '').trim();
          var $regItem = $('<li>')
            .addClass('toggle-list-item menu__item--register')
            .append(
              $('<a>')
                .addClass('toggle-list-item__anchor')
                .attr('href', regUrl)
                .append(
                  $('<span>')
                    .addClass('minerva-icon minerva-icon--register')
                )
                .append(
                  $('<span>')
                    .addClass('toggle-list-item__label')
                    .text(regText)
                )
            );
          $menu.append($regItem);
         });
      }
    });
  }); 


      // Otherwise assume this is a customcollapse with a remote toggle
// Codex: Shortcut for the "Purge" action for refreshing cache, named "Clear cache"
      // .. and there is no collapsible-content because the entire element should be toggled
mw.loader.using(['mediawiki.util']).then(function () {
      } else {
    function addPurgeLink() {
        if ( action === 'collapse' ) {
        if (!document.getElementById('ca-purge') && mw.config.get('wgIsArticle')) {
          if ( options.instantHide ) {
            mw.util.addPortletLink(
            $collapsible.hide();
                'p-cactions',
            hookCallback();
                mw.util.wikiScript() + '?' + new URLSearchParams({
          } else {
                    title: mw.config.get('wgPageName'),
            if ( $collapsible.is( 'tr' ) || $collapsible.is( 'td' ) || $collapsible.is( 'th' ) ) {
                    action: 'purge'
              $collapsible.fadeOut().promise().done( hookCallback );
                }).toString(),
            } else {
                mw.config.get('skin') === 'monobook' ? '*' : 'Clear cache',
              $collapsible.slideUp().promise().done( hookCallback );
                'ca-purge',
            }
                'Purge the server cache of this page?',
          }
                '*'
        } else {
             );
          if ( $collapsible.is( 'tr' ) || $collapsible.is( 'td' ) || $collapsible.is( 'th' ) ) {
            $collapsible.fadeIn().promise().done( hookCallback );
          } else {
             $collapsible.slideDown().promise().done( hookCallback );
          }
         }
         }
      }
     }
     }
  }
    mw.hook('wikipage.content').add(addPurgeLink);
});


  /**
// Codex: Modernized "Gadget-predefined-summaries"
  * Handle clicking/keypressing on the collapsible element toggle and other
// Lists common options below "Summary" to optimize editor experience
  * situations where a collapsible element is toggled (e.g. the initial
mw.loader.using(['mediawiki.util']).then(function () {
  * toggle for collapsed ones).
     'use strict';
  *
  * @private
  * @param {jQuery} $toggle the clickable toggle itself
  * @param {jQuery} $collapsible the collapsible element
  * @param {jQuery.Event|null} e either the event or null if unavailable
  * @param {Object|undefined} options
  */
  function togglingHandler( $toggle, $collapsible, e, options ) {
     var wasCollapsed, $textContainer, collapseText, expandText;


     if ( options === undefined ) {
     if (window.resumeDeluxe === undefined &&
      options = {};
        ['edit', 'submit'].includes(mw.config.get('wgAction')) &&
    }
        mw.util.getParamValue('section') !== 'new') {


    if ( e ) {
         var resumeDeluxe = {
      if (
            titles: ["grammar", "normalization", "categorization", "general fixes", "template fixes", "+ internal link(s)", "+ external link(s)"],
         e.type === 'click' &&
            inputs: ["grammar", "normalization", "categorization", "general fixes", "template fixes", "+ internal link(s)", "+ external link(s)"],
        options.linksPassthru &&
            addToSummary: function (str) {
        $.nodeName( e.target, 'a' ) &&
                var summaryField = document.getElementById('wpSummary');
        $( e.target ).attr( 'href' ) !== '#'
                if (summaryField) {
      ) {
                    summaryField.value = summaryField.value ? summaryField.value + '; ' + str : str;
        // Don't fire if a link with href !== '#' was clicked, if requested  (for premade togglers by default)
                }
        return;
                return false;
      } else if ( e.type === 'keypress' && e.which !== 13 && e.which !== 32 ) {
            }
        // Only handle keypresses on the "Enter" or "Space" keys
        };
        return;
      } else {
        e.preventDefault();
        e.stopPropagation();
      }
    }
 
    // This allows the element to be hidden on initial toggle without fiddling with the class
    if ( options.wasCollapsed !== undefined ) {
      wasCollapsed = options.wasCollapsed;
    } else {
      wasCollapsed = $collapsible.hasClass( 'mw-collapsed' );
    }
 
    // Toggle the state of the collapsible element (that is, expand or collapse)
    $collapsible.toggleClass( 'mw-collapsed', !wasCollapsed );


    // Toggle the mw-collapsible-toggle classes, if requested (for default and premade togglers by default)
         window.resumeDeluxe = resumeDeluxe;
    if ( options.toggleClasses ) {
      $toggle
        .toggleClass( 'mw-collapsible-toggle-collapsed', !wasCollapsed )
         .toggleClass( 'mw-collapsible-toggle-expanded', wasCollapsed );
    }


    // Toggle the text ("Show"/"Hide"), if requested (for default togglers by default)
        var DeluxeSummary = function() {
    if ( options.toggleText ) {
            var summaryLabel = document.getElementById('wpSummaryLabel');
      collapseText = options.toggleText.collapseText;
            var summaryField = document.getElementById('wpSummary');
      expandText = options.toggleText.expandText;


      $textContainer = $toggle.find( '> a' );
            if (summaryLabel && summaryField) {
      if ( !$textContainer.length ) {
                // Prevent duplicate bars by checking for an existing one
        $textContainer = $toggle;
                if (summaryLabel.querySelector('.predefined-summaries-bar')) {
      }
                    return;
      $textContainer.text( wasCollapsed ? collapseText : expandText );
                }
    }


    // And finally toggle the element state itself
                // Create container with a unique class name
    toggleElement( $collapsible, wasCollapsed ? 'expand' : 'collapse', $toggle, options );
                var container = document.createElement('span');
  }
                container.className = 'predefined-summaries-bar';
 
                container.innerHTML = '<b>Predefined summaries</b>: ';
  /**
  * Enable collapsible-functionality on all elements in the collection.
  *
  * - Will prevent binding twice to the same element.
  * - Initial state is expanded by default, this can be overridden by adding class
  *  "mw-collapsed" to the "mw-collapsible" element.
  * - Elements made collapsible have jQuery data "mw-made-collapsible" set to true.
  * - The inner content is wrapped in a "div.mw-collapsible-content" (except for tables and lists).
  *
  * @param {Object} [options]
  * @param {string} [options.collapseText] Text used for the toggler, when clicking it would
  *  collapse the element. Default: the 'data-collapsetext' attribute of the
  *  collapsible element or the content of 'collapsible-collapse' message.
  * @param {string} [options.expandText] Text used for the toggler, when clicking it would
  *  expand the element. Default: the 'data-expandtext' attribute of the
  *  collapsible element or the content of 'collapsible-expand' message.
  * @param {boolean} [options.collapsed] Whether to collapse immediately. By default
  *  collapse only if the elements has the 'mw-collapsible' class.
  * @param {jQuery} [options.$customTogglers] Elements to be used as togglers
  *  for this collapsible element. By default, if the collapsible element
  *  has an id attribute like 'mw-customcollapsible-XXX', elements with a
  *  *class* of 'mw-customtoggle-XXX' are made togglers for it.
  * @param {boolean} [options.plainMode=false] Whether to use a "plain mode" when making the
  *  element collapsible - that is, hide entire tables and lists (instead
  *  of hiding only all rows but first of tables, and hiding each list
  *  item separately for lists) and don't wrap other elements in
  *  div.mw-collapsible-content. May only be used with custom togglers.
  * @return {jQuery}
  * @chainable
  */
  $.fn.makeCollapsible = function ( options ) {
    if ( options === undefined ) {
      options = {};
    }


    return this.each( function () {
                resumeDeluxe.titles.forEach((title, index) => {
      var $collapsible, collapseText, expandText, $caption, $toggle, actionHandler, buildDefaultToggleLink,
                    if (index > 0) {
        premadeToggleHandler, $toggleLink, $firstItem, collapsibleId, $customTogglers, firstval;
                        container.appendChild(document.createTextNode(' / '));
                    }


      // Ensure class "mw-collapsible" is present in case .makeCollapsible()
                    var link = document.createElement('a');
      // is called on element(s) that don't have it yet.
                    link.href = '#';
      $collapsible = $( this ).addClass( 'mw-collapsible' );
                    link.className = 'sumLink';
                    link.title = 'Add to edit summary';
                    link.textContent = title;
                    link.addEventListener('click', function (event) {
                        event.preventDefault();
                        resumeDeluxe.addToSummary(resumeDeluxe.inputs[index]);
                    });


      // Return if it has been enabled already.
                    container.appendChild(link);
      if ( $collapsible.data( 'mw-made-collapsible' ) ) {
                });
        return;
      } else {
        $collapsible.data( 'mw-made-collapsible', true );
      }


      // Use custom text or default?
                container.appendChild(document.createElement('br'));
      collapseText = options.collapseText || $collapsible.attr( 'data-collapsetext' ) || mw.msg( 'collapsible-collapse' );
                summaryLabel.prepend(container);
      expandText = options.expandText || $collapsible.attr( 'data-expandtext' ) || mw.msg( 'collapsible-expand' );


      // Default click/keypress handler and toggle link to use when none is present
                // Adjust width as in original script
      actionHandler = function ( e, opts ) {
                summaryField.style.width = '95%';
        var defaultOpts = {
            }
          toggleClasses: true,
          toggleText: { collapseText: collapseText, expandText: expandText }
         };
         };
        opts = $.extend( defaultOpts, options, opts );
        togglingHandler( $( this ), $collapsible, e, opts );
      };
      // Default toggle link. Only build it when needed to avoid jQuery memory leaks (event data).
      buildDefaultToggleLink = function () {
        return $( '<a href="#"></a>' )
          .text( collapseText )
          .wrap( '<span class="mw-collapsible-toggle"></span>' )
            .parent()
            .prepend( '<span class="mw-collapsible-bracket">[</span>' )
            .append( '<span class="mw-collapsible-bracket">]</span>' )
            .on( 'click.mw-collapsible keypress.mw-collapsible', actionHandler );
      };


      // Default handler for clicking on premade toggles
        mw.hook('wikipage.content').add(DeluxeSummary);
      premadeToggleHandler = function ( e, opts ) {
    }
        var defaultOpts = { toggleClasses: true, linksPassthru: true };
});
        opts = $.extend( defaultOpts, options, opts );
        togglingHandler( $( this ), $collapsible, e, opts );
      };


      // Check if this element has a custom position for the toggle link
// Custom script targeting Lingo that performs two separate actions: 1) Disables the rendering of tooltips of a given acronym within the article that defines it (RFC on the Request For Comments article); 2) Disables Lingo entirely in arbitrarily defined Namespaces
      // (ie. outside the container or deeper inside the tree)
$(function() {
      if ( options.$customTogglers ) {
    // List namespaces where Lingo should be blocked (adjust as needed)
        $customTogglers = $( options.$customTogglers );
    var blockedNamespaces = ['Template', 'Category', 'Module'];
      } else {
    var currentNS = mw.config.get('wgCanonicalNamespace');
        collapsibleId = $collapsible.attr( 'id' ) || '';
   
        if ( collapsibleId.indexOf( 'mw-customcollapsible-' ) === 0 ) {
    if (blockedNamespaces.indexOf(currentNS) !== -1) {
          $customTogglers = $( '.' + collapsibleId.replace( 'mw-customcollapsible', 'mw-customtoggle' ) )
        // Remove any Lingo tooltip markup immediately
             .addClass( 'mw-customtoggle' );
        $('.mw-lingo-term').each(function() {
         }
             $(this).replaceWith($(this).text());
      }
        });
        console.log("Lingo processing is blocked in the '" + currentNS + "' namespace.");
         return; // Stop further processing
    }


      // Add event handlers to custom togglers or create our own ones
    // Decent enough script for Lingo not to render tooltips of an acronym on the page that defines it
      if ( $customTogglers && $customTogglers.length ) {
    var rawTitle = mw.config.get('wgTitle').replace(/_/g, ' ').trim();
        actionHandler = function ( e, opts ) {
    var acronym = null;
          var defaultOpts = {};
          opts = $.extend( defaultOpts, options, opts );
          togglingHandler( $( this ), $collapsible, e, opts );
        };


        $toggleLink = $customTogglers
    // Case 1: Title written as "Long Form (ACRONYM)"
          .on( 'click.mw-collapsible keypress.mw-collapsible', actionHandler )
    var titleAcronymMatch = rawTitle.match(/^(.+?)\s+\(([A-Z]{2,})\)$/);
          .prop( 'tabIndex', 0 );
    if (titleAcronymMatch) {
 
        acronym = titleAcronymMatch[2];
      } else {
        console.log("Using acronym from title parenthetical: " + acronym);
        // If this is not a custom case, do the default: wrap the
    }
        // contents and add the toggle link. Different elements are
    // Case 2: Title is exactly an acronym (all uppercase)
         // treated differently.
    else if (/^[A-Z]+$/.test(rawTitle)) {
         if ( $collapsible.is( 'table' ) ) {
         acronym = rawTitle;
 
         console.log("Using pure acronym from title: " + acronym);
          // If the table has a caption, collapse to the caption
    }
          // as opposed to the first row
    // Otherwise, compute fallback from title’s longform and compare with extracted acronym
          $caption = $collapsible.find( '> caption' );
    else {
          if ( $caption.length ) {
        // Remove any trailing parenthetical from title, e.g. "Request For Comments (foo)" becomes "Request For Comments"
             $toggle = $caption.find( '> .mw-collapsible-toggle' );
        var longForm = rawTitle.replace(/\s*\(.*\)\s*$/, '');
 
        var fallback = longForm.split(/\s+/).map(function(word) {
            // If there is no toggle link, add it to the end of the caption
             return word.charAt(0).toUpperCase();
            if ( !$toggle.length ) {
        }).join('');
              $toggleLink = buildDefaultToggleLink().appendTo( $caption );
       
        // Attempt to extract an acronym from the first paragraph
        var firstParagraph = $('#mw-content-text p').first().text();
        var parenMatch = firstParagraph.match(/\(([A-Z]{2,})\)/);
        if (parenMatch) {
            var extracted = parenMatch[1];
            console.log("Extracted acronym from first paragraph: " + extracted);
            if (extracted === fallback) {
                acronym = extracted;
                console.log("Acronym matches fallback computed from title: " + acronym);
             } else {
             } else {
              actionHandler = premadeToggleHandler;
                console.log("Extracted acronym (" + extracted + ") does not match computed fallback (" + fallback + "); aborting tooltip removal.");
              $toggleLink = $toggle.on( 'click.mw-collapsible keypress.mw-collapsible', actionHandler )
                 return;
                 .prop( 'tabIndex', 0 );
             }
             }
          } else {
         } else {
            // The toggle-link will be in one of the cells (td or th) of the first row
             console.log("No acronym found in first paragraph; aborting tooltip removal.");
            $firstItem = $collapsible.find( 'tr:first th, tr:first td' );
             return;
            $toggle = $firstItem.find( '> .mw-collapsible-toggle' );
 
            // If theres no toggle link, add it to the last cell
            if ( !$toggle.length ) {
              $toggleLink = buildDefaultToggleLink().prependTo( $firstItem.eq( -1 ) );
            } else {
              actionHandler = premadeToggleHandler;
              $toggleLink = $toggle.on( 'click.mw-collapsible keypress.mw-collapsible', actionHandler )
                .prop( 'tabIndex', 0 );
            }
          }
 
         } else if ( $collapsible.is( 'ul' ) || $collapsible.is( 'ol' ) ) {
          // The toggle-link will be in the first list-item
          $firstItem = $collapsible.find( 'li:first' );
          $toggle = $firstItem.find( '> .mw-collapsible-toggle' );
 
          // If theres no toggle link, add it
          if ( !$toggle.length ) {
            // Make sure the numeral order doesn't get messed up, force the first (soon to be second) item
            // to be "1". Except if the value-attribute is already used.
            // If no value was set WebKit returns "", Mozilla returns '-1', others return 0, null or undefined.
            firstval = $firstItem.prop( 'value' );
            if ( firstval === undefined || !firstval || firstval === '-1' || firstval === -1 ) {
              $firstItem.prop( 'value', '1' );
            }
            $toggleLink = buildDefaultToggleLink();
             $toggleLink.wrap( '<li class="mw-collapsible-toggle-li"></li>' ).parent().prependTo( $collapsible );
          } else {
            actionHandler = premadeToggleHandler;
            $toggleLink = $toggle.on( 'click.mw-collapsible keypress.mw-collapsible', actionHandler )
              .prop( 'tabIndex', 0 );
          }
 
        } else { // <div>, <p> etc.
 
          // The toggle-link will be the first child of the element
          $toggle = $collapsible.find( '> .mw-collapsible-toggle' );
 
          // If a direct child .content-wrapper does not exists, create it
          if ( !$collapsible.find( '> .mw-collapsible-content' ).length ) {
            $collapsible.wrapInner( '<div class="mw-collapsible-content"></div>' );
          }
 
          // If theres no toggle link, add it
          if ( !$toggle.length ) {
             $toggleLink = buildDefaultToggleLink().prependTo( $collapsible );
          } else {
            actionHandler = premadeToggleHandler;
            $toggleLink = $toggle.on( 'click.mw-collapsible keypress.mw-collapsible', actionHandler )
              .prop( 'tabIndex', 0 );
          }
         }
         }
      }
     }
 
      // Initial state
      if ( options.collapsed || $collapsible.hasClass( 'mw-collapsed' ) ) {
        // One toggler can hook to multiple elements, and one element can have
        // multiple togglers. This is the sanest way to handle that.
        actionHandler.call( $toggleLink.get( 0 ), null, { instantHide: true, wasCollapsed: false } );
      }
     } );
  };
 
  /**
  * @class jQuery
  * @mixins jQuery.plugin.makeCollapsible
  */


}( jQuery, mediaWiki ) );
    console.log("Assuming definition page for acronym: " + acronym);
    // Remove any Lingo tooltip markup for elements whose visible text exactly matches the acronym.
    var $matching = $('.mw-lingo-term').filter(function() {
        return $(this).text().trim() === acronym;
    });
    console.log("Found " + $matching.length + " element(s) with visible text '" + acronym + "'");
   
    $matching.each(function() {
        $(this).replaceWith($(this).text());
    });
   
    console.log("Finished processing Lingo tooltips for acronym: " + acronym);
});

Latest revision as of 18:10, 15 February 2025

// Load jQuery UI using mw.loader
mw.loader.using(['jquery.ui'], function() {
    console.log("jQuery UI loaded.");
});

// Load WikiEditor and RefToolbar by default
mw.loader.using(['ext.wikiEditor']).then(function() {
    $(function() {
        if (mw.config.get('wgAction') === 'edit' || mw.config.get('wgAction') === 'submit') {
            $('#wpTextbox1').wikiEditor();
            console.log("WikiEditor auto-initialized.");

            mw.loader.load('//en.wikipedia.org/w/index.php?title=MediaWiki:Gadget-refToolbar.js&action=raw&ctype=text/javascript');
            console.log("RefToolbar loaded.");
        }
    });
});

// Codex: Open all external links on a new window
mw.loader.using(['mediawiki.util']).then(function () {
    function openExternalLinks() {
        // General external links
        document.querySelectorAll('a.external').forEach(function (link) {
            link.setAttribute('target', '_blank');
            link.setAttribute('rel', 'noopener noreferrer');
        });
        // Social media links within templates
        document.querySelectorAll('div.external-social a, div.ntldstats a').forEach(function (link) {
            link.setAttribute('target', '_blank');
            link.setAttribute('rel', 'noopener noreferrer');
        });
    }
    // Run on page load
    mw.hook('wikipage.content').add(openExternalLinks);
});

// Include a registration link in Minerva/mobile's hamburger menu for logged out users
mw.loader.using(['mediawiki.util'], function() {
    $(function() {
      if (mw.config.get('skin') === 'minerva' && mw.user.isAnon()) {
        var waitForPersonalMenu = function(callback) {
          var $menu = $('#p-personal');
          if ($menu.length) {
            callback($menu);
          } else {
            setTimeout(function() {
              waitForPersonalMenu(callback);
            }, 100);
          }
        };
        waitForPersonalMenu(function($menu) {
          var regUrl = mw.util.getUrl('Special:UserLogin', { type: 'signup' });
          // Get the message text and remove any curly braces
          var regText = mw.msg('createaccount').replace(/[{}]/g, '').trim();
          var $regItem = $('<li>')
            .addClass('toggle-list-item menu__item--register')
            .append(
              $('<a>')
                .addClass('toggle-list-item__anchor')
                .attr('href', regUrl)
                .append(
                  $('<span>')
                    .addClass('minerva-icon minerva-icon--register')
                )
                .append(
                  $('<span>')
                    .addClass('toggle-list-item__label')
                    .text(regText)
                )
            );
          $menu.append($regItem);
        });
      }
    });
  });  

// Codex: Shortcut for the "Purge" action for refreshing cache, named "Clear cache"
mw.loader.using(['mediawiki.util']).then(function () {
    function addPurgeLink() {
        if (!document.getElementById('ca-purge') && mw.config.get('wgIsArticle')) {
            mw.util.addPortletLink(
                'p-cactions',
                mw.util.wikiScript() + '?' + new URLSearchParams({
                    title: mw.config.get('wgPageName'),
                    action: 'purge'
                }).toString(),
                mw.config.get('skin') === 'monobook' ? '*' : 'Clear cache',
                'ca-purge',
                'Purge the server cache of this page?',
                '*'
            );
        }
    }
    mw.hook('wikipage.content').add(addPurgeLink);
});

// Codex: Modernized "Gadget-predefined-summaries"
// Lists common options below "Summary" to optimize editor experience
mw.loader.using(['mediawiki.util']).then(function () {
    'use strict';

    if (window.resumeDeluxe === undefined &&
        ['edit', 'submit'].includes(mw.config.get('wgAction')) &&
        mw.util.getParamValue('section') !== 'new') {

        var resumeDeluxe = {
            titles: ["grammar", "normalization", "categorization", "general fixes", "template fixes", "+ internal link(s)", "+ external link(s)"],
            inputs: ["grammar", "normalization", "categorization", "general fixes", "template fixes", "+ internal link(s)", "+ external link(s)"],
            addToSummary: function (str) {
                var summaryField = document.getElementById('wpSummary');
                if (summaryField) {
                    summaryField.value = summaryField.value ? summaryField.value + '; ' + str : str;
                }
                return false;
            }
        };

        window.resumeDeluxe = resumeDeluxe;

        var DeluxeSummary = function() {
            var summaryLabel = document.getElementById('wpSummaryLabel');
            var summaryField = document.getElementById('wpSummary');

            if (summaryLabel && summaryField) {
                // Prevent duplicate bars by checking for an existing one
                if (summaryLabel.querySelector('.predefined-summaries-bar')) {
                    return;
                }

                // Create container with a unique class name
                var container = document.createElement('span');
                container.className = 'predefined-summaries-bar';
                container.innerHTML = '<b>Predefined summaries</b>: ';

                resumeDeluxe.titles.forEach((title, index) => {
                    if (index > 0) {
                        container.appendChild(document.createTextNode(' / '));
                    }

                    var link = document.createElement('a');
                    link.href = '#';
                    link.className = 'sumLink';
                    link.title = 'Add to edit summary';
                    link.textContent = title;
                    link.addEventListener('click', function (event) {
                        event.preventDefault();
                        resumeDeluxe.addToSummary(resumeDeluxe.inputs[index]);
                    });

                    container.appendChild(link);
                });

                container.appendChild(document.createElement('br'));
                summaryLabel.prepend(container);

                // Adjust width as in original script
                summaryField.style.width = '95%';
            }
        };

        mw.hook('wikipage.content').add(DeluxeSummary);
    }
});

// Custom script targeting Lingo that performs two separate actions: 1) Disables the rendering of tooltips of a given acronym within the article that defines it (RFC on the Request For Comments article); 2) Disables Lingo entirely in arbitrarily defined Namespaces
$(function() {
    // List namespaces where Lingo should be blocked (adjust as needed)
    var blockedNamespaces = ['Template', 'Category', 'Module'];
    var currentNS = mw.config.get('wgCanonicalNamespace');
    
    if (blockedNamespaces.indexOf(currentNS) !== -1) {
        // Remove any Lingo tooltip markup immediately
        $('.mw-lingo-term').each(function() {
            $(this).replaceWith($(this).text());
        });
        console.log("Lingo processing is blocked in the '" + currentNS + "' namespace.");
        return; // Stop further processing
    }

    // Decent enough script for Lingo not to render tooltips of an acronym on the page that defines it
    var rawTitle = mw.config.get('wgTitle').replace(/_/g, ' ').trim();
    var acronym = null;

    // Case 1: Title written as "Long Form (ACRONYM)"
    var titleAcronymMatch = rawTitle.match(/^(.+?)\s+\(([A-Z]{2,})\)$/);
    if (titleAcronymMatch) {
        acronym = titleAcronymMatch[2];
        console.log("Using acronym from title parenthetical: " + acronym);
    }
    // Case 2: Title is exactly an acronym (all uppercase)
    else if (/^[A-Z]+$/.test(rawTitle)) {
        acronym = rawTitle;
        console.log("Using pure acronym from title: " + acronym);
    }
    // Otherwise, compute fallback from title’s longform and compare with extracted acronym
    else {
        // Remove any trailing parenthetical from title, e.g. "Request For Comments (foo)" becomes "Request For Comments"
        var longForm = rawTitle.replace(/\s*\(.*\)\s*$/, '');
        var fallback = longForm.split(/\s+/).map(function(word) {
            return word.charAt(0).toUpperCase();
        }).join('');
        
        // Attempt to extract an acronym from the first paragraph
        var firstParagraph = $('#mw-content-text p').first().text();
        var parenMatch = firstParagraph.match(/\(([A-Z]{2,})\)/);
        if (parenMatch) {
            var extracted = parenMatch[1];
            console.log("Extracted acronym from first paragraph: " + extracted);
            if (extracted === fallback) {
                acronym = extracted;
                console.log("Acronym matches fallback computed from title: " + acronym);
            } else {
                console.log("Extracted acronym (" + extracted + ") does not match computed fallback (" + fallback + "); aborting tooltip removal.");
                return;
            }
        } else {
            console.log("No acronym found in first paragraph; aborting tooltip removal.");
            return;
        }
    }

    console.log("Assuming definition page for acronym: " + acronym);
    // Remove any Lingo tooltip markup for elements whose visible text exactly matches the acronym.
    var $matching = $('.mw-lingo-term').filter(function() {
        return $(this).text().trim() === acronym;
    });
    console.log("Found " + $matching.length + " element(s) with visible text '" + acronym + "'");
    
    $matching.each(function() {
        $(this).replaceWith($(this).text());
    });
    
    console.log("Finished processing Lingo tooltips for acronym: " + acronym);
});