MediaWiki

Common.js: Difference between revisions

Kashya (talk | contribs)
No edit summary
Kashya (talk | contribs)
No edit summary
Line 132: Line 132:


// --- Automated Random Short Picker for Vanipedia (Kasya) ---
// --- Automated Random Short Picker for Vanipedia (Kasya) ---
$(document).ready(function() {
$(document).ready(function() {
     var $widget = $('.vanipedia-random-shorts-widget');
     var $widget = $('.vanipedia-random-shorts-widget');
      
      
     // Only run if the widget block exists on the currently active page
     // Execute logic only if the widget template container is physically present
     if ($widget.length) {
     if ($widget.length) {
         var $dbZone = $widget.find('.vani-shorts-source-db');
         var $dbZone = $widget.find('.vani-shorts-source-db');
Line 142: Line 141:
         var $titleFrame = $widget.find('.vani-shorts-title');
         var $titleFrame = $widget.find('.vani-shorts-title');
          
          
         // Find all gallery boxes inside your transcluded list page
         // Scan the target container broadly for any links targeting YouTube or Shorts endpoints
         var $galleryItems = $dbZone.find('.gallerybox, li, .gallerytext');
         var $links = $dbZone.find('a[href*="youtube.com"], a[href*="/shorts/"]');
       
        // Fallback: search for anchor links if the layout gets compressed
        if ($galleryItems.length === 0) {
            $galleryItems = $dbZone.find('a[href*="youtube.com"]');
        }


         if ($galleryItems.length === 0) {
         if ($links.length === 0) {
             $viewport.text("No videos detected on the shorts list page.");
             $viewport.html("<div style='color:#c0392b; padding:10px; font-size:11px; text-align:center;'>No valid video links processed in source container.</div>");
             return;
             return;
         }
         }


         // 1. Pick an item completely at random out of your thousands of videos
         // 1. Pick a random link item out of the thousands loaded in the memory container
         var randomIdx = Math.floor(Math.random() * $galleryItems.length);
         var randomIdx = Math.floor(Math.random() * $links.length);
         var $pickedItem = $galleryItems.eq(randomIdx);
         var $pickedLink = $links.eq(randomIdx);


         // 2. Extract the video link and the text title properties
         // 2. Read the raw destination web link address
         var rowHtml = $pickedItem.html() || '';
         var href = $pickedLink.attr('href') || '';
        var rowText = $pickedItem.text() || '';
       
         var videoId = '';
         var videoId = '';
         var cleanTitle = 'YouTube Short';
         var cleanTitle = 'YouTube Short Selection';


         // 3. Scan the item for standard /shorts/ or watch parameter patterns
         // 3. Extract the YouTube ID string cleanly from both standard watch and vertical shorts structures
        var matchShort = rowHtml.match(/\/shorts\/([a-zA-Z0-9_-]+)/) || rowText.match(/\/shorts\/([a-zA-Z0-9_-]+)/);
        if (href.indexOf('/shorts/') !== -1) {
         var matchWatch = rowHtml.match(/v=([a-zA-Z0-9_-]+)/) || rowText.match(/v=([a-zA-Z0-9_-]+)/);
            var segments = href.split('/shorts/');
 
            if (segments.length > 1) {
        if (matchShort && matchShort[1]) {
                videoId = segments[1].split('?')[0].split('#')[0].split('&')[0];
            videoId = matchShort[1];
            }
        } else if (matchWatch && matchWatch[1]) {
         } else if (href.indexOf('v=') !== -1) {
            videoId = matchWatch[1];
            var vParts = href.split('v=');
            if (vParts.length > 1) {
                videoId = vParts[1].split('&')[0].split('#')[0].split('?')[0];
            }
         } else {
         } else {
             // Ultimate fallback lookup for raw URLs
             // Absolute fall-back for short domain links (e.g. youtu.be/ID)
             var hrefAttr = $pickedItem.find('a').attr('href') || $pickedItem.attr('href') || '';
             var slashParts = href.split('/');
             if (hrefAttr.indexOf('/shorts/') !== -1) {
             videoId = slashParts[slashParts.length - 1].split('?')[0].split('#')[0];
                videoId = hrefAttr.split('/shorts/')[1].split(/[?#]/)[0];
            }
         }
         }


         // 4. Extract and polish the text title description
        // Clean up text boundaries
         if (rowText.indexOf('|') !== -1) {
        videoId = $.trim(videoId);
             var parts = rowText.split('|');
 
             cleanTitle = (parts.length > 1 && parts[1].indexOf('link=') === -1) ? parts[1].trim() : parts[0].replace(/File:[^\s|]+/g, '').trim();
         // 4. Extract Title label from the text properties surrounding the random link element
         } else {
        // Looks up the container cell/line block containing our link
             cleanTitle = rowText.replace(/File:[^\s|]+/g, '').replace(/link=[^\s]+/g, '').trim();
        var $parentLine = $pickedLink.closest('li, td, div, .gallerytext');
        var fullRowText = $parentLine.length ? $parentLine.text() : $pickedLink.text();
 
         if (fullRowText && fullRowText.indexOf('|') !== -1) {
             var pieces = fullRowText.split('|');
             // Look for the element that doesn't say "link=" or "File:" to serve as our title
            for (var i = 0; i < pieces.length; i++) {
                var currentPiece = $.trim(pieces[i]);
                if (currentPiece.indexOf('link=') !== 0 && currentPiece.indexOf('File:') !== 0 && currentPiece.length > 2) {
                    cleanTitle = currentPiece;
                    break;
                }
            }
         } else if (fullRowText) {
             cleanTitle = fullRowText.replace(/File:[^\s|]+/g, '').replace(/link=[^\s]+/g, '').replace(/https?:\/\/[^\s]+/g, '').trim();
         }
         }


         if (!cleanTitle || cleanTitle.length < 2) {
        // Ultimate fallback check if title parses blank
             cleanTitle = "Short Video Selection";
         if (!cleanTitle || cleanTitle.length < 3) {
             cleanTitle = "Short Video";
         }
         }


         // 5. Replace the loader with the actual clean embedding frame
         // 5. Replace the "Loading short..." text with the operational player box
         if (videoId) {
         if (videoId && videoId.length > 3) {
             var embedUrl = "https://youtube.com" + videoId;
             var embedUrl = "https://youtube.com" + videoId;
             $viewport.html('<iframe width="260" height="260" src="' + embedUrl + '" frameborder="0" allowfullscreen style="border-radius: 8px; border: none;"></iframe>');
             $viewport.html('<iframe width="260" height="260" src="' + embedUrl + '" frameborder="0" allowfullscreen style="border-radius: 8px; border: none;"></iframe>');
             $titleFrame.text(cleanTitle);
             $titleFrame.text(cleanTitle);
         } else {
         } else {
             $viewport.html('<div style="color:#c0392b; padding:10px; font-size:11px; text-align:center;">Failed to resolve short code sequence.</div>');
             $viewport.html('<div style="color:#c0392b; padding:10px; font-size:11px; text-align:center;">Failed to resolve short code sequence (' + href + ').</div>');
         }
         }
     }
     }
});
});

Revision as of 05:31, 20 May 2026

/* Any JavaScript here will be loaded for all users on every page load. */

if (mw.config.get('wgPageName' ) === 'Krishna_says_in_Bhagavad-gita') { 
  /* switch tooltip texts from content-div to label-div */
  const v_labels = Array.from(document.getElementsByClassName("tabs-label"));
  const v_content = Array.from(document.getElementsByClassName("tabs-content"));
  for (var i = 0; i < v_labels.length; i++) {
    v_labels[i].title = v_content[i].title;
    v_content[i].title = "";
  }
  /* adjust wikitables */
  var arr = Array.from(document.getElementsByClassName("wikitable"));
  for (var t = 0; t < arr.length; t++) {
    /* insert THEAD in wikitable */
    var thead = document.createElement("thead");
    thead.style.display = "block";
    var wtbl = arr[t];
    wtbl.insertBefore(thead, wtbl.firstChild);
    /* move first row of TBODY to THEAD */
    thead.appendChild(wtbl.rows[0]);
    /* make TBODY scrollable */
    var tbody = wtbl.tBodies[0];
    tbody.style.display = "block";
    tbody.style.overflowY = "auto";
    tbody.style.maxHeight = "500px";    
    for (var r = 0; r < wtbl.rows.length; r++) {
      var row = wtbl.rows[r];
      /* adjust column widths and hide from-until columns */
      row.cells[0].classList = "cw_0";
      row.cells[1].classList = "cw_150";
      row.cells[2].classList = "cw_500";
      /* mark the text */ 
      if (r == 0) continue;
      var v_text = row.cells[2].textContent;
      var v_html = ""; var v_from = 0;
      var marks = JSON.parse(row.cells[0].textContent.replaceAll("O", "[").replaceAll("C", "]"));
      for (var m = 0; m < marks.length; m++) {
        v_html += 
          v_text.substr(v_from,marks[m][0]-v_from) + "<mark>" +
          v_text.substr(marks[m][0],marks[m][1]-marks[m][0]+1) + "</mark>";
        v_from = marks[m][1]+1;
      }
      v_html += v_text.substr(v_from);
      row.cells[2].innerHTML = v_html;
    }
  }
}

// install Google Search
// document.write('<script type="text/javascript" src="'
// + 'http://vanipedia.org/w/index.php?title=MediaWiki:GoogleSearch.js'
// + '&action=raw&ctype=text/javascript"></' + 'script>');

// install JQuery
//document.write('<script type="text/javascript" src="'
//+ 'http://vanipedia.org/w/index.php?title=MediaWiki:JQuery.js'
//+ '&action=raw&ctype=text/javascript"></' + 'script>');

// install WikEd toolbar and Vanify
//document.write('<script type="text/javascript" src="'
//+ 'http://vanipedia.org/w/index.php?title=MediaWiki:Vaniquotes.js'
//+ '&action=raw&ctype=text/javascript"></' + 'script>');
 
// install Replace
//document.write('<script type="text/javascript" src="'
//+ 'http://vanipedia.org/w/index.php?title=MediaWiki:TextboxReplace.js'
//+ '&action=raw&ctype=text/javascript"></' + 'script>');
 
// install Unify
//document.write('<script type="text/javascript" src="'
//+ 'http://vanipedia.org/w/index.php?title=MediaWiki:Unify.js'
//+ '&action=raw&ctype=text/javascript"></' + 'script>');
 
// install Vanify
//document.write('<script type="text/javascript" src="'
//+ 'http://vanipedia.org/w/index.php?title=MediaWiki:Vanify.js'
//+ '&action=raw&ctype=text/javascript"></' + 'script>');

// install Vani_suggest for diacritics auto-suggest pulldown on the search bar
//document.write('<script type="text/javascript" src="'
//+ 'http://vanipedia.org/w/index.php?title=MediaWiki:Vani_suggest.js'
//+ '&action=raw&ctype=text/javascript"></' + 'script>');

// install previous/next links for video categories in all languages
 //document.write('<script type="text/javascript" src="/navcat/navcat.js"></' + 'script>');
 
// Buttons
 
//addOnloadHook(function() {
 
//if (document.editform) {
//addPortletLink("p-cactions", "javascript:Unify()", "unify", "ca-unify", "Convert Balarama fonts to Unicode", "");
// addPortletLink("p-cactions", "javascript:Vanify()", "vanify", "ca-vanify", "Corrects vani markup", "");
// addPortletLink('p-cactions', 'javascript:format()', 'format', 'ca-format', 'Format article', '');
//addPortletLink('p-cactions', 'javascript:wpTextboxReplace()', 'Replace', 'ca-replace', 'Replaces text in the edit window', 'R');
//}
//});
 
// end Buttons

// --- VANIPEDIA DARK MODE TOGGLE (Kasya) ---
$(document).ready(function() {
    // Create the floating button
    var toggleBtn = $('<button id="dark-mode-toggle" title="Toggle Dark Mode" style="position:fixed; bottom:25px; right:25px; z-index:9999; width:45px; height:45px; border-radius:50%; background:#2c3e50; color:#f1c40f; font-size:20px; border:none; box-shadow:0 4px 10px rgba(0,0,0,0.3); cursor:pointer; display:flex; align-items:center; justify-content:center; transition: transform 0.2s;">🌙</button>');
    $('body').append(toggleBtn);

    // Hover effect for the button
    toggleBtn.hover(
        function() { $(this).css('transform', 'scale(1.1)'); },
        function() { $(this).css('transform', 'scale(1.0)'); }
    );

    // Check if the user previously selected dark mode
    if (localStorage.getItem('vanipedia-theme') === 'dark') {
        $('html').addClass('dark-theme');
        toggleBtn.text('🔆').css('background', '#f1c40f').css('color', '#2c3e50');
    }

    // Click event handler
    toggleBtn.click(function() {
        $('html').toggleClass('dark-theme');
        
        if ($('html').hasClass('dark-theme')) {
            localStorage.setItem('vanipedia-theme', 'dark');
            toggleBtn.text('🔆').css('background', '#f1c40f').css('color', '#2c3e50');
        } else {
            localStorage.setItem('vanipedia-theme', 'light');
            toggleBtn.text('☽').css('background', '#2c3e50').css('color', '#f1c40f');
        }
    });
});

// --- Automated Random Short Picker for Vanipedia (Kasya) ---
$(document).ready(function() {
    var $widget = $('.vanipedia-random-shorts-widget');
    
    // Execute logic only if the widget template container is physically present
    if ($widget.length) {
        var $dbZone = $widget.find('.vani-shorts-source-db');
        var $viewport = $widget.find('.vani-shorts-viewport');
        var $titleFrame = $widget.find('.vani-shorts-title');
        
        // Scan the target container broadly for any links targeting YouTube or Shorts endpoints
        var $links = $dbZone.find('a[href*="youtube.com"], a[href*="/shorts/"]');

        if ($links.length === 0) {
            $viewport.html("<div style='color:#c0392b; padding:10px; font-size:11px; text-align:center;'>No valid video links processed in source container.</div>");
            return;
        }

        // 1. Pick a random link item out of the thousands loaded in the memory container
        var randomIdx = Math.floor(Math.random() * $links.length);
        var $pickedLink = $links.eq(randomIdx);

        // 2. Read the raw destination web link address 
        var href = $pickedLink.attr('href') || '';
        var videoId = '';
        var cleanTitle = 'YouTube Short Selection';

        // 3. Extract the YouTube ID string cleanly from both standard watch and vertical shorts structures
        if (href.indexOf('/shorts/') !== -1) {
            var segments = href.split('/shorts/');
            if (segments.length > 1) {
                videoId = segments[1].split('?')[0].split('#')[0].split('&')[0];
            }
        } else if (href.indexOf('v=') !== -1) {
            var vParts = href.split('v=');
            if (vParts.length > 1) {
                videoId = vParts[1].split('&')[0].split('#')[0].split('?')[0];
            }
        } else {
            // Absolute fall-back for short domain links (e.g. youtu.be/ID)
            var slashParts = href.split('/');
            videoId = slashParts[slashParts.length - 1].split('?')[0].split('#')[0];
        }

        // Clean up text boundaries
        videoId = $.trim(videoId);

        // 4. Extract Title label from the text properties surrounding the random link element
        // Looks up the container cell/line block containing our link
        var $parentLine = $pickedLink.closest('li, td, div, .gallerytext');
        var fullRowText = $parentLine.length ? $parentLine.text() : $pickedLink.text();

        if (fullRowText && fullRowText.indexOf('|') !== -1) {
            var pieces = fullRowText.split('|');
            // Look for the element that doesn't say "link=" or "File:" to serve as our title
            for (var i = 0; i < pieces.length; i++) {
                var currentPiece = $.trim(pieces[i]);
                if (currentPiece.indexOf('link=') !== 0 && currentPiece.indexOf('File:') !== 0 && currentPiece.length > 2) {
                    cleanTitle = currentPiece;
                    break;
                }
            }
        } else if (fullRowText) {
            cleanTitle = fullRowText.replace(/File:[^\s|]+/g, '').replace(/link=[^\s]+/g, '').replace(/https?:\/\/[^\s]+/g, '').trim();
        }

        // Ultimate fallback check if title parses blank
        if (!cleanTitle || cleanTitle.length < 3) {
            cleanTitle = "Short Video";
        }

        // 5. Replace the "Loading short..." text with the operational player box
        if (videoId && videoId.length > 3) {
            var embedUrl = "https://youtube.com" + videoId;
            $viewport.html('<iframe width="260" height="260" src="' + embedUrl + '" frameborder="0" allowfullscreen style="border-radius: 8px; border: none;"></iframe>');
            $titleFrame.text(cleanTitle);
        } else {
            $viewport.html('<div style="color:#c0392b; padding:10px; font-size:11px; text-align:center;">Failed to resolve short code sequence (' + href + ').</div>');
        }
    }
});