MediaWiki:Common.js: Difference between revisions

no edit summary
No edit summary
No edit summary
 
(54 intermediate revisions by 2 users not shown)
Line 1: Line 1:
//Final working Common.js
mw.loader.load('//wiki.ekatrafoundation.org/index.php?title=User:Gurwinder/Edittool.js&action=raw&ctype=text/javascript');
'MediaWiki:InterWikiTransclusion.js'
// Turn <span class="mw-charinsert">foo</span> into a button that inserts "foo"
// into the edit box:
$( function () {
    $( 'span.mw-charinsert' ).wrap( function () {
        var text = this.title || this.textContent;
        var parts = text.split( '+' );
        if ( text === '+' ) parts = [ text ];
        var front = decodeURIComponent( parts[0] || '' );
        var back  = decodeURIComponent( parts[1] || '' );
        return $( '<button>' ).click( function () {
            insertTags( front, back, '' );
            return false;
        } );
    } );
} );
$( function(){
$( function(){
if (window.matchMedia("(max-width: 768px)").matches) {
if( mw.config.get("skin") !== "minerva" ){
const currWikiUrl = new URL(window.location.href);
currWikiUrl.searchParams.set('mobileaction', 'toggle_view_mobile');
window.location.replace(currWikiUrl);
}
} else {
if(  mw.config.get("skin") !== "vector" ){
const currWikiUrl = new URL(window.location.href);
currWikiUrl.searchParams.set('mobileaction', 'toggle_view_desktop');
window.location.replace(currWikiUrl);
}
}
if( mw.config.get('wgIsMainPage') ){
if( mw.config.get('wgIsMainPage') ){
$('#firstHeading').remove();
$('#firstHeading').remove();
var mainpageLeft = $(".mainpage-left");
var mainpageRight = $(".mainpage-right");
mainpageLeft.css("position", "relative");
mainpageRight.css("position", "relative");
function animateLeft(){
mainpageRight.animate({'left': '15px'}, 1000, function(){
mainpageRight.animate( {"left": "0px" }, 1000, animateLeft() );
});
}
animateLeft();
function animateRight(){
mainpageLeft.animate({'left': '-15px'}, 1000, function(){
mainpageLeft.animate( {"left": "0px" }, 1000, animateRight() );
});
}
animateRight();
}
}
Line 19: Line 76:
mw.loader.load( '/index.php?title=MediaWiki:OCR.js&action=raw&ctype=text/javascript');
mw.loader.load( '/index.php?title=MediaWiki:OCR.js&action=raw&ctype=text/javascript');
mw.loader.load( '/index.php?title=MediaWiki:PoemButtons.js&action=raw&ctype=text/javascript');
}
if( $(".wikiaudioplayer").length ){
mw.loader.load( '/index.php?title=MediaWiki:Green-audio-player.min.css&action=raw&ctype=text/css', 'text/css');
$.when(
    mw.loader.getScript( 'https://wiki.ekatrafoundation.org/index.php?title=MediaWiki:Green-audio-player.min.js&action=raw&ctype=text/javascript' )
)
.then(
    function () {
GreenAudioPlayer.init({
    selector: '.wikiaudioplayer',
    stopOthersOnPlay: true
});
$( ".wikiaudioplayer > audio").css("display", "none");
    },
    function ( e ) {
        mw.log.error( e.message );
    }
);
}
}


Line 88: Line 165:
} );
} );
});
// Long list into col
$( document ).ready( function(){
var longList = $("#longList").addClass("grid_row"),
dlElements = longList.children().filter("dl"),
dlElementsLength = dlElements.length;
var list1 = [],
list2 = [];
var count = 0;
dlElements.each( function(index, ele){
if( count < dlElementsLength/2 ){
list1.push(ele);
list1.push( $(ele).next() );
} else {
list2.push(ele);
list2.push( $(ele).next() );
}
count = count + 1;
});
longList.empty();
var leftDiv = $("<div/>").addClass("grid_col");
list1.forEach( function(value, index){
leftDiv.append(value);
});
var rightDiv = $("<div/>").addClass("grid_col");
list2.forEach( function(value, index){
rightDiv.append(value);
});
longList.append(leftDiv, rightDiv );
});
});
Line 135: Line 251:
var leftDiv = $("<div/>").addClass("grid_col");
var leftDiv = $("<div/>").addClass("grid_col");
var rightDiv = $("<div/>").addClass("grid_col");
var rightDiv = $("<div/>").addClass("grid_col");
divide2cols.find("dl").each(function() {
var parentHieght = divide2cols.height()/2;
if ( $(this).offset().top > (divide2cols.height()/2) ) {
divide2cols.children().filter("dl").each(function() {
console.log( $(this).offset().top , parentHieght );
if ( $(this).offset().top > parentHieght ) {
rightDiv.append( $(this), $(this).next() );
rightDiv.append( $(this), $(this).next() );
} else {
} else {
Line 461: Line 579:
msg('label-tooltip'),
msg('label-tooltip'),
null,
null,
mw.user.isAnon() ? '#pt-createaccount' : '#pt-userpage'
(mw.user.isAnon === true) ? '#pt-createaccount' : '#pt-userpage'
);
);
menu = $('<div>').addClass('mw-numerakri-menu').append(createSelector())[0];
menu = $('<div>').addClass('mw-numerakri-menu').append(createSelector())[0];
Line 473: Line 591:
});
});
}());
}());
/* Any JavaScript here will be loaded for all users on every page load. */
self.ws_messages = {
'iwtrans':'Its text comes from',
'iwtrans2':'Its text comes from other sub-domains.',
'optlist':'Display options',
'hide_page_numbers':'Hide page links',
'show_page_numbers':'Show page links',
'layout':'Layout',
'author':'Author',
'translator':'Translator',
'editor':'Editor',
'publisher':'Publisher',
'place':'Place',
'volume':'Volume',
'school':'School',
'book':'Book',
'collection':'Collection',
'journal':'Journal or magazine',
'phdthesis':'Thesis, report',
'dictionary':'Dictionary',
'progress':'Progress',
'progress_T':'Done',
'progress_V':'To be validated',
'progress_C':'To be proofread',
'progress_MS':'Ready for Match & Split',
'progress_OCR':'Needs an OCR text layer',
'progress_L':'Source file is incorrect (missing pages, unordered pages, etc)',
'page_namespace_name':      'Page',
'page_trascluded_in':      'Page trascluded in:',
'text_number':              'Text',
'compare_with':  'Comparison with:',
'compare_texts': 'Compare texts'
};
//$.getScript( '//wiki.ekatrafoundation.org/index.php?title=MediaWiki:Base.js&action=raw&ctype=text/javascript' )
//.done( function() {
// importScript('MediaWiki:InterWikiTransclusion.js');
// importScript('MediaWiki:TranscludedIn.js');
// importScript('MediaWiki:Compare.js');
//} );
$.getScript('//wiki.ekatrafoundation.org/index.php?title=MediaWiki:Base.js&action=raw&ctype=text/javascript')
.done(function () {
    mw.loader.load('//wiki.ekatrafoundation.org/index.php?title=MediaWiki:InterWikiTransclusion.js&action=raw&ctype=text/javascript');
    mw.loader.load('//wiki.ekatrafoundation.org/index.php?title=MediaWiki:TranscludedIn.js&action=raw&ctype=text/javascript');
    mw.loader.load('//wiki.ekatrafoundation.org/index.php?title=MediaWiki:Compare.js&action=raw&ctype=text/javascript');
});
/* Footnotes as tooltip - from it.wikipedia.org - request by Candalua */
$( function ()
{
sups = document.getElementsByTagName("sup");
for (i=0; i<sups.length; i++)
{
  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;
      }
  }
}
});
// Add links to Wikidata in the toolbar where [[Module:Interwiki]] is used
$("#t-wikibase").insertBefore($("#p-tb li").last()).removeAttr("style");
// Code to switch sizes for {{Tscore resizable}}
$( function ()
{
el = document.getElementsByClassName("prp-page-content");
if (el.length) {
maxwidth = el[0].clientWidth;
} else {
maxwidth = document.getElementById("mw-content-text").clientWidth;
}
screslistslist = document.getElementsByClassName("score-resizable-container");
scressizelist = [];
for (i = 0; i < screslistslist.length; i++) {
//maxwidth = screslistslist[i].parentNode.clientWidth;
screslist = screslistslist[i].getElementsByClassName("score-resizable");
fitwidth = 0;
fitelement = -1;
for (j = 0; j < screslist.length; j++) {
s = screslist[j].className.match(/score-resizable-size-\d+/);
scressizelist[j] = parseInt(s[0].match(/\d+/), 10);
//find largest score that has width < parent width
if (scressizelist[j] > fitwidth && scressizelist[j] <= maxwidth) {
fitwidth = scressizelist[j];
fitelement = j;
}
}
if (fitelement < 0) {
fitelement = 0;
}
for (j = 0; j < screslist.length; j++) {
if (j != fitelement) {
screslist[j].style.display = "none";
}
}
screslist[fitelement].style.display = "block";
}
});
if (mw.user.isAnon) { // Check if the user is anonymous
    $(function () {
        $('.ext-wikisource-download-button').hide(); // Hide the button for anonymous users
    });
}
$(document).ready(function() {
    // Get the page title
    var pageTitle = mw.config.get('wgTitle');
    // Encode the title and replace spaces with '%20'
    var encodedTitle = encodeURIComponent(pageTitle).replace(/%20/g, '%20'); // Correctly handle spaces
    // Create the download button
    var downloadButton = $('<a>')
        .attr('href', 'https://wiki.ekatrafoundation.org/images/epub/' + encodedTitle + '.epub')
        .attr('download', '') // Suggests to download the file rather than opening it
        .text('Download EPUB')
        .css({
            'display': 'inline-block',
            'padding': '8px 16px',
            'background-color': '#4CAF50',
            'color': '#ffffff',
            'text-align': 'center',
            'border-radius': '4px',
            'text-decoration': 'none',
            'margin-top': '10px'
        });
    // Add the button to the page content
    $('#bodyContent').append(downloadButton);
});
$(document).ready(function() {
    // Get the page title from the MediaWiki configuration
    var pageTitle = mw.config.get('wgTitle');
   
    // Check if the page title contains a forward slash
    if (pageTitle.indexOf('/') === -1) {
        // Show the download button if it's a top-level page
        $('a[href*="/find_epub.php"]').show();
    } else {
        // Hide the download button if it's a subpage
        $('a[href*="/find_epub.php"]').hide();
    }
});
$(document).ready(function() {
    var $element = $('#editpage-specialchars');
    var isDragging = false;
    var startX, startY, initialX, initialY;
    $element.on('mousedown', function(e) {
        isDragging = true;
        startX = e.clientX;
        startY = e.clientY;
        initialX = $element.offset().left;
        initialY = $element.offset().top;
        $element.addClass('dragging');
    });
    $(document).on('mousemove', function(e) {
        if (isDragging) {
            var dx = e.clientX - startX;
            var dy = e.clientY - startY;
            $element.css({
                top: initialY + dy + 'px',
                left: initialX + dx + 'px'
            });
        }
    });
    $(document).on('mouseup', function() {
        if (isDragging) {
            isDragging = false;
            $element.removeClass('dragging');
        }
    });
});
// Table sorting functions for all devices
function initMobileSorting() {
    console.log('Initializing table sorting for all devices...');
   
    var tables = document.querySelectorAll('.wikitable, table.sortable');
    console.log('Found tables:', tables.length);
   
    $(tables).each(function(index, table) {
        setupTableSorting($(table), index);
    });
}
function setupTableSorting($table, tableIndex) {
    var $headers = $table.find('th');
   
    if ($headers.length === 0) return;
   
    console.log('Setting up table', tableIndex, 'with', $headers.length, 'headers');
   
    $table.off('click.tablesort');
   
    $headers.each(function() {
        var $header = $(this);
       
        $header.css({
            'cursor': 'pointer',
            'user-select': 'none',
            'background-color': '#f8f9fa',
            'border-bottom': '2px solid #a2a9b1',
            'position': 'relative'
        });
       
        $header.find('.sort-arrow').remove();
        $header.append('<span class="sort-arrow" style="margin-left: 5px; color: #666; font-size: 12px;">⇅</span>');
    });
   
    $table.on('click.tablesort', 'th', function(e) {
        e.preventDefault();
        e.stopPropagation();
       
        var $clickedHeader = $(this);
        var columnIndex = $clickedHeader.index();
       
        var $allHeaders = $table.find('th');
        var $dataRows = $table.find('tbody tr');
       
        if ($dataRows.length === 0) {
            $dataRows = $table.find('tr').not($table.find('tr').first());
        }
       
        if ($dataRows.length === 0) return;
       
        var currentSortClass = $clickedHeader.hasClass('sort-asc') ? 'asc' :
                              $clickedHeader.hasClass('sort-desc') ? 'desc' : 'none';
        var newSortDirection = currentSortClass === 'asc' ? 'desc' : 'asc';
       
        $allHeaders.removeClass('sort-asc sort-desc');
        $allHeaders.find('.sort-arrow').text('⇅').css('color', '#666');
       
        $clickedHeader.addClass('sort-' + newSortDirection);
        var arrow = newSortDirection === 'asc' ? '⇑' : '⇓';
        $clickedHeader.find('.sort-arrow').text(arrow).css('color', '#000');
       
        var rowsArray = $dataRows.toArray();
       
        rowsArray.sort(function(rowA, rowB) {
            var $cellA = $(rowA).find('td').eq(columnIndex);
            var $cellB = $(rowB).find('td').eq(columnIndex);
           
            if ($cellA.length === 0 || $cellB.length === 0) return 0;
           
            var textA = $cellA.text().trim();
            var textB = $cellB.text().trim();
           
            var numA = parseFloat(textA.replace(/[,$%\s]/g, ''));
            var numB = parseFloat(textB.replace(/[,$%\s]/g, ''));
           
            var result;
            if (!isNaN(numA) && !isNaN(numB)) {
                result = numA - numB;
            } else {
                result = textA.localeCompare(textB);
            }
           
            return newSortDirection === 'desc' ? -result : result;
        });
       
        var $tbody = $table.find('tbody');
        if ($tbody.length > 0) {
            $tbody.empty().append(rowsArray);
        } else {
            $table.find('tr').not($table.find('tr').first()).remove();
            $table.append(rowsArray);
        }
       
        setTimeout(function() {
            setupTableSorting($table, tableIndex);
        }, 10);
    });
}
// Initialize table sorting on page load
$(document).ready(function() {
    initMobileSorting();
   
    mw.hook('wikipage.content').add(function() {
        initMobileSorting();
    });
});