MediaWiki:Common.js: Difference between revisions

8,564 bytes added ,  06:12, 17 December 2025
Undo revision 104883 by Gurwinder (talk)
No edit summary
(Undo revision 104883 by Gurwinder (talk))
Tag: Undo
 
(36 intermediate revisions by 2 users not shown)
Line 1: Line 1:
mw.loader.load('//wiki.ekatrafoundation.org/index.php?title=User:Gurwinder/Edittool.js&action=raw&ctype=text/javascript');
// 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(){
Line 4: Line 21:
if( mw.config.get("skin") !== "minerva" ){
if( mw.config.get("skin") !== "minerva" ){
const currWikiUrl = new URL(window.location.href);
const currWikiUrl = new URL(window.location.href);
currWikiUrl.searchParams.set('useskin', 'minerva');
currWikiUrl.searchParams.set('mobileaction', 'toggle_view_mobile');
window.location.replace(currWikiUrl);
window.location.replace(currWikiUrl);
Line 11: Line 28:
if(  mw.config.get("skin") !== "vector" ){
if(  mw.config.get("skin") !== "vector" ){
const currWikiUrl = new URL(window.location.href);
const currWikiUrl = new URL(window.location.href);
currWikiUrl.searchParams.set('useskin', 'vector');
currWikiUrl.searchParams.set('mobileaction', 'toggle_view_desktop');


window.location.replace(currWikiUrl);
window.location.replace(currWikiUrl);
Line 246: Line 263:




$( function(){
$(function () {
// toggled by toggle button. also determines which toggle button image to use
var useCustom = false;
var useCustom = false;
 
// toggleImgs[0] to switch to custom, toggleImgs[1] to revert to default
var zoomInSVG =
var toggleImgs = [
'<svg width="22" height="22" viewBox="0 0 24 24">' +
'//storage.googleapis.com/material-icons/external-assets/v4/icons/svg/ic_search_black_24px.svg',
'<path d="M15.5 14h-.8l-.3-.3a6.5 6.5 0 1 0-.7.7l.3.3v.8L20 21.5 21.5 20z ' +
'//storage.googleapis.com/material-icons/external-assets/v4/icons/svg/ic_youtube_searched_for_black_24px.svg'
'M10 14a4 4 0 1 1 0-8 4 4 0 0 1 0 8z ' +
];
'M11 7H9v2H7v2h2v2h2v-2h2V9h-2z"/>' +
var zoomInImg = '//storage.googleapis.com/material-icons/external-assets/v4/icons/svg/ic_zoom_in_black_24px.svg';
'</svg>';
var zoomOutImg = '//storage.googleapis.com/material-icons/external-assets/v4/icons/svg/ic_zoom_out_black_24px.svg';
 
var zoomOutSVG =
// create DOM elements
'<svg width="22" height="22" viewBox="0 0 24 24">' +
$('#content').prepend('<div id="zoomButtons" style="z-index: 9999;">\
'<path d="M15.5 14h-.8l-.3-.3a6.5 6.5 0 1 0-.7.7l.3.3v.8L20 21.5 21.5 20z ' +
<img id="zoomInIcon" src="' + zoomInImg + '" alt="zoom in"">\
'M7 9h6v2H7z"/>' +
<img id="zoomOutIcon" src="' + zoomOutImg + '" alt="zoom out"">\
'</svg>';
<img id="toggleButton" src="' + toggleImgs[+ useCustom] + '" alt="toggle zoom">&nbsp</div>');
 
$('#zoomButtons').css({'float': 'right'});
var toggleSVG =
'<svg width="22" height="22" viewBox="0 0 24 24">' +
// find DOM elements used later
'<path d="M5 4h14v2H5zm4 4h6l-2 12h-2z"/>' +
'</svg>';
 
$('#content').prepend(
'<div id="zoomButtons" style="z-index:9999; float:right; display:flex; gap:8px; cursor:pointer;">' +
'<span id="zoomInIcon">' + zoomInSVG + '</span>' +
'<span id="zoomOutIcon">' + zoomOutSVG + '</span>' +
'<span id="toggleButton">' + toggleSVG + '</span>' +
'</div>'
);
 
var $bodyContent = $('.mw-body-content');
var $bodyContent = $('.mw-body-content');
var $toggleButton = $('#toggleButton');
 
var sizes = [parseFloat($bodyContent.css('font-size'))];
// sizes[0] is default, sizes[1] is custom
var sizes = [parseFloat($('.mw-body-content').css('font-size'))];
// default custom zoom of 2
sizes[1] = sizes[0] + 2;
sizes[1] = sizes[0] + 2;
 
// the + converts bool to 0 or 1 to use as array index
function updateSize() {
function updateSize() {
$bodyContent.css({'font-size':(sizes[+ useCustom] + 'pt')});
$bodyContent.css('font-size', sizes[+useCustom] + 'pt');
}
}
function toggle() {
function toggle() {
useCustom = !useCustom;
useCustom = !useCustom;
$toggleButton.attr('src',toggleImgs[+ useCustom]);
updateSize();
updateSize();
}
}
function zoom(dif) {
function zoom(dif) {
sizes[1] += dif;
sizes[1] += dif;
Line 291: Line 314:
}
}
}
}
 
$( '#zoomInIcon' ).on( 'click', function(){
$('#zoomInIcon').on('click', function () {
console.log("Zoom +");
zoom(1);
zoom(1);
});
});
 
$( '#zoomOutIcon' ).on( 'click', function(){
$('#zoomOutIcon').on('click', function () {
console.log("Zoom -");
zoom(-1);
zoom(-1);
});
});
 
$( '#toggleButton' ).on( 'click', toggle );
$('#toggleButton').on('click', toggle);
});
});




Line 571: Line 593:
});
});
}());
}());
/* 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');
} );
/* 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() === true) { // 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');
        }
    });
});
// ==UserScript==
// @name        MediaWiki Smart Single Quotes
// @namespace    http://your.local/
// @version      1.0
// @description  Convert straight single quotes to typographic single quotes on MediaWiki pages (visual only).
// @match        https://wiki.ekatrafoundation.org/*
// @grant        none
// ==/UserScript==
(function () {
    'use strict';
    function convertSingleQuotesText(text) {
        if (!text || text.indexOf("'") === -1) return text;
        text = text.replace(/([A-Za-z0-9])'([A-Za-z0-9])/g, "$1’$2"); // contractions/possessives
        text = text.replace(/(^|[\s\(\[\{\<\u2014\u2013"“'«])'(?=\S)/g, "$1‘"); // opening quotes
        text = text.replace(/'/g, "’"); // remaining closing quotes
        return text;
    }
    function walkAndReplace(root) {
        if (!root) return;
        try {
            var walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, null, false);
            var n;
            var blacklist = new Set(["CODE", "PRE", "SCRIPT", "STYLE", "TEXTAREA", "NOSCRIPT", "MATH", "INPUT"]);
            while ((n = walker.nextNode())) {
                var parent = n.parentNode;
                if (!parent) continue;
                var anc = parent, skip = false;
                while (anc && anc.nodeType === 1) {
                    if (blacklist.has(anc.nodeName)) { skip = true; break; }
                    anc = anc.parentNode;
                }
                if (skip) continue;
                var orig = n.nodeValue;
                var rep = convertSingleQuotesText(orig);
                if (rep !== orig) n.nodeValue = rep;
            }
        } catch (e) {
            console.error('smartQuotes error', e);
        }
    }
    function applyOnce() {
        var root = document.querySelector('.mw-parser-output') || document.body;
        walkAndReplace(root);
    }
    // run after window.load, also watch for AJAX content
    window.addEventListener('load', function () {
        setTimeout(applyOnce, 150);
        var obs = new MutationObserver(function (mutations) {
            mutations.forEach(function (m) {
                m.addedNodes && m.addedNodes.forEach(function (n) {
                    if (n.nodeType === 1) walkAndReplace(n);
                    else if (n.nodeType === 3 && n.parentNode) walkAndReplace(n.parentNode);
                });
            });
        });
        obs.observe(document.body, { childList: true, subtree: true });
    }, false);
})();