MediaWiki

Common.js: Difference between revisions

Kashya (talk | contribs)
No edit summary
Kashya (talk | contribs)
No edit summary
Line 135: Line 135:
     var $widget = $('.vanipedia-random-shorts-widget');
     var $widget = $('.vanipedia-random-shorts-widget');
      
      
     // Execute logic only if the widget template container is physically present
     // Only execute if the target widget exists on the current viewport
     if ($widget.length) {
     if ($widget.length) {
         var $dbZone = $widget.find('.vani-shorts-source-db');
         var $dbZone = $widget.find('.vani-shorts-source-db');
Line 141: Line 141:
         var $titleFrame = $widget.find('.vani-shorts-title');
         var $titleFrame = $widget.find('.vani-shorts-title');
          
          
         // Scan the target container broadly for any links targeting YouTube or Shorts endpoints
         // Target all standard media links containing YouTube or Shorts strings
         var $links = $dbZone.find('a[href*="youtube.com"], a[href*="/shorts/"]');
         var $links = $dbZone.find('a[href*="youtube.com"], a[href*="youtu.be"], a[href*="/shorts/"]');


         if ($links.length === 0) {
         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>");
             $viewport.html("<div style='color:#c0392b; padding:10px; font-size:11px; text-align:center;'>Database reading failed. Please check list transclusion configuration.</div>");
             return;
             return;
         }
         }


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


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


         // 3. Extract the YouTube ID string cleanly from both standard watch and vertical shorts structures
         // 3. Robust Regex parameter engine to isolate the video sequence string
         if (href.indexOf('/shorts/') !== -1) {
         if (href.indexOf('/shorts/') !== -1) {
             var segments = href.split('/shorts/');
             var shortMatch = href.match(/\/shorts\/([a-zA-Z0-9_-]{11})/);
             if (segments.length > 1) {
             if (shortMatch) videoId = shortMatch[1];
                videoId = segments[1].split('?')[0].split('#')[0].split('&')[0];
            }
         } else if (href.indexOf('v=') !== -1) {
         } else if (href.indexOf('v=') !== -1) {
             var vParts = href.split('v=');
             var watchMatch = href.match(/v=([a-zA-Z0-9_-]{11})/);
             if (vParts.length > 1) {
             if (watchMatch) videoId = watchMatch[1];
                videoId = vParts[1].split('&')[0].split('#')[0].split('?')[0];
            }
         } else {
         } else {
            // Absolute fall-back for short domain links (e.g. youtu.be/ID)
             var rawMatch = href.match(/\/([a-zA-Z0-9_-]{11})/);
             var slashParts = href.split('/');
             if (rawMatch) videoId = rawMatch[1];
             videoId = slashParts[slashParts.length - 1].split('?')[0].split('#')[0];
         }
         }


        // Clean up text boundaries
         // 4. Trace the parents up to capture the clean descriptive text segment
        videoId = $.trim(videoId);
         var $parentBlock = $pickedLink.closest('.gallerybox, li, td, tr, div');
 
         var textContent = $parentBlock.length ? $parentBlock.text() : $pickedLink.text();
         // 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) {
         if (textContent && textContent.indexOf('|') !== -1) {
             var pieces = fullRowText.split('|');
             var segments = textContent.split('|');
            // Look for the element that doesn't say "link=" or "File:" to serve as our title
             for (var i = 0; i < segments.length; i++) {
             for (var i = 0; i < pieces.length; i++) {
                 var piece = $.trim(segments[i]);
                 var currentPiece = $.trim(pieces[i]);
                 if (piece.indexOf('link=') !== 0 && piece.indexOf('File:') !== 0 && piece.length > 2) {
                 if (currentPiece.indexOf('link=') !== 0 && currentPiece.indexOf('File:') !== 0 && currentPiece.length > 2) {
                     cleanTitle = piece;
                     cleanTitle = currentPiece;
                     break;
                     break;
                 }
                 }
             }
             }
         } else if (fullRowText) {
         } else if (textContent) {
             cleanTitle = fullRowText.replace(/File:[^\s|]+/g, '').replace(/link=[^\s]+/g, '').replace(/https?:\/\/[^\s]+/g, '').trim();
             cleanTitle = textContent.replace(/File:[^\s|]+/g, '').replace(/link=[^\s]+/g, '').replace(/https?:\/\/[^\s]+/g, '').trim();
         }
         }


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


         // 5. Replace the "Loading short..." text with the operational player box
         // 5. Unload the placeholder message and inject the active embedded video frame player
         if (videoId && videoId.length > 3) {
         if (videoId && videoId.length === 11) {
             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 (' + href + ').</div>');
             $viewport.html('<div style="color:#c0392b; padding:10px; font-size:11px; text-align:center;">Failed to resolve short code index. Trying another...</div>');
            // Auto-fallback retry loop if a bad line was parsed out
            setTimeout(function() { window.location.reload(); }, 1500);
         }
         }
     }
     }
});
});

Revision as of 05:41, 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');
    
    // Only execute if the target widget exists on the current viewport
    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');
        
        // Target all standard media links containing YouTube or Shorts strings
        var $links = $dbZone.find('a[href*="youtube.com"], a[href*="youtu.be"], a[href*="/shorts/"]');

        if ($links.length === 0) {
            $viewport.html("<div style='color:#c0392b; padding:10px; font-size:11px; text-align:center;'>Database reading failed. Please check list transclusion configuration.</div>");
            return;
        }

        // 1. Target and extract an individual item link entirely at random
        var randomIdx = Math.floor(Math.random() * $links.length);
        var $pickedLink = $links.eq(randomIdx);

        // 2. Resolve target landing paths and properties
        var href = $pickedLink.attr('href') || '';
        var videoId = '';
        var cleanTitle = 'YouTube Short Selection';

        // 3. Robust Regex parameter engine to isolate the video sequence string
        if (href.indexOf('/shorts/') !== -1) {
            var shortMatch = href.match(/\/shorts\/([a-zA-Z0-9_-]{11})/);
            if (shortMatch) videoId = shortMatch[1];
        } else if (href.indexOf('v=') !== -1) {
            var watchMatch = href.match(/v=([a-zA-Z0-9_-]{11})/);
            if (watchMatch) videoId = watchMatch[1];
        } else {
            var rawMatch = href.match(/\/([a-zA-Z0-9_-]{11})/);
            if (rawMatch) videoId = rawMatch[1];
        }

        // 4. Trace the parents up to capture the clean descriptive text segment
        var $parentBlock = $pickedLink.closest('.gallerybox, li, td, tr, div');
        var textContent = $parentBlock.length ? $parentBlock.text() : $pickedLink.text();

        if (textContent && textContent.indexOf('|') !== -1) {
            var segments = textContent.split('|');
            for (var i = 0; i < segments.length; i++) {
                var piece = $.trim(segments[i]);
                if (piece.indexOf('link=') !== 0 && piece.indexOf('File:') !== 0 && piece.length > 2) {
                    cleanTitle = piece;
                    break;
                }
            }
        } else if (textContent) {
            cleanTitle = textContent.replace(/File:[^\s|]+/g, '').replace(/link=[^\s]+/g, '').replace(/https?:\/\/[^\s]+/g, '').trim();
        }

        // Ultimate fallback sanity check for clean titles
        if (!cleanTitle || cleanTitle.length < 2) {
            cleanTitle = "Short Video";
        }

        // 5. Unload the placeholder message and inject the active embedded video frame player
        if (videoId && videoId.length === 11) {
            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 index. Trying another...</div>');
            // Auto-fallback retry loop if a bad line was parsed out
            setTimeout(function() { window.location.reload(); }, 1500);
        }
    }
});