Jump to content

MediaWiki:Common.js: Difference between revisions

From Grantha
No edit summary
No edit summary
 
(14 intermediate revisions by the same user not shown)
Line 1: Line 1:
(function () {
/* MediaWiki:Common.js — grantha.io  (v6)
*
* Changes vs v5:
*  1. TOC active highlight fix: Vector 2022 sets the active class on the
*    <li.vector-toc-list-item>, but Common.js wraps all text nodes inside
*    .vector-toc-text spans in <span data-deva="…">.  The CSS colour rule
*    was targeting .vector-toc-list-item-active > a which never matched
*    because the <a> sits deeper and its text is now inside a <span>.
*    Fix: MutationObserver watches the <li> for class changes and directly
*    applies/removes the orange colour via inline style on the .vector-toc-link
*    ancestor, bypassing the CSS specificity war entirely.
*  2. All other behaviour identical to v5.
*/


( function () {
  var LS_SCRIPT_KEY = 'grantha_reader_script';
   var currentScript = 'deva';
   var currentScript = 'deva';


   // ── IAST transliteration (inline, no external library) ─────────
   // ── IAST transliteration ────────────────────────────────────────
   function devanagariToIAST(text) {
   function devanagariToIAST( text ) {
     var CONSONANTS = {
     var CONSONANTS = {
       'क':'k','ख':'kh','ग':'g','घ':'gh','ङ':'ṅ',
       'क':'k','ख':'kh','ग':'g','घ':'gh','ङ':'ṅ',
Line 28: Line 43:
     };
     };
     var HALANTA = '्';
     var HALANTA = '्';
     var chars = Array.from(text);
     var chars = Array.from( text );
     var result = '';
     var result = '';
     var i = 0;
     var i = 0;
     while (i < chars.length) {
     while ( i < chars.length ) {
       var ch = chars[i];
       var ch   = chars[ i ];
       if (CONSONANTS[ch]) {
      var next = chars[ i + 1 ];
         var base = CONSONANTS[ch];
       if ( CONSONANTS[ ch ] ) {
        var next = chars[i + 1];
         var base = CONSONANTS[ ch ];
         if (next === HALANTA) {
         if ( next === HALANTA )         { result += base;               i += 2; }
          result += base; i += 2;
         else if ( DIACRITICS[ next ] )   { result += base + DIACRITICS[ next ]; i += 2; }
         } else if (DIACRITICS[next]) {
         else if ( next === 'ं' || next === 'ः' ) { result += base + 'a' + MISC[ next ]; i += 2; }
          result += base + DIACRITICS[next]; i += 2;
         else                             { result += base + 'a';         i++;   }
         } else if (next === 'ं' || next === 'ः') {
       } else if ( VOWELS[ ch ] )         { result += VOWELS[ ch ];       i++; }
          result += base + 'a' + MISC[next]; i += 2;
       else if ( DIACRITICS[ ch ] )       { result += DIACRITICS[ ch ];   i++; }
         } else {
       else if ( MISC[ ch ] )             { result += MISC[ ch ];         i++; }
          result += base + 'a'; i++;
       else                               { result += ch;                 i++; }
        }
       } else if (VOWELS[ch])     { result += VOWELS[ch];     i++; }
       else if (DIACRITICS[ch])   { result += DIACRITICS[ch]; i++; }
       else if (MISC[ch])         { result += MISC[ch];       i++; }
       else                       { result += ch;             i++; }
     }
     }
     return result;
     return result;
Line 73: Line 83:
     ta: {
     ta: {
       'अ':'அ','आ':'ஆ','इ':'இ','ई':'ஈ','उ':'உ','ऊ':'ஊ',
       'अ':'அ','आ':'ஆ','इ':'இ','ई':'ஈ','उ':'உ','ऊ':'ஊ',
      'ऋ':'ரு','ॠ':'ரூ',
       'ए':'ஏ','ऐ':'ஐ','ओ':'ஓ','औ':'ஔ',
       'ए':'ஏ','ऐ':'ஐ','ओ':'ஓ','औ':'ஔ',
       'क':'க','ख':'க','ग':'க','घ':'க','ङ':'ங',
       'क':'க','ख':'க','ग':'க','घ':'க','ङ':'ங',
Line 79: Line 90:
       'त':'த','थ':'த','द':'த','ध':'த','न':'ந',
       'त':'த','थ':'த','द':'த','ध':'த','न':'ந',
       'प':'ப','फ':'ப','ब':'ப','भ':'ப','म':'ம',
       'प':'ப','फ':'ப','ब':'ப','भ':'ப','म':'ம',
       'य':'ய','र':'ர','ல':'','व':'வ',
       'य':'ய','र':'ர','ल':'ல','ळ':'','व':'வ',
       'श':'ஶ','ष':'ஷ','स':'ஸ','ह':'ஹ',
       'श':'ஶ','ष':'ஷ','स':'ஸ','ह':'ஹ',
       'ा':'ா','ि':'ி','ी':'ீ','ु':'ு','ू':'ூ',
       'ा':'ா','ि':'ி','ी':'ீ','ु':'ு','ू':'ூ',
      'ृ':'ு','ॄ':'ூ',
       'े':'ே','ै':'ை','ो':'ோ','ौ':'ௌ',
       'े':'ே','ै':'ை','ो':'ோ','ौ':'ௌ',
       'ं':'ம்','ः':':','्':'்','ॐ':'ௐ',
       'ं':'ம்','ः':':','ँ':'ம்','्':'்','ॐ':'ௐ','ऽ':'ௗ',
       '०':'0','१':'1','२':'2','३':'3','४':'4',
       '०':'0','१':'1','२':'2','३':'3','४':'4',
       '५':'5','६':'6','७':'7','८':'8','९':'9'
       '५':'5','६':'6','७':'7','८':'8','९':'9'
Line 90: Line 102:


   var PRE = [
   var PRE = [
     [/ङ्क/g,'ंक'],[/ङ्ख/g,'ंख'],[/ङ्ग/g,'ंग'],[/ङ्घ/g,'ंघ'],
     [ /ङ्क/g, 'ंक' ], [ /ङ्ख/g, 'ंख' ], [ /ङ्ग/g, 'ंग' ], [ /ङ्घ/g, 'ंघ' ],
     [/ञ्च/g,'ंच'],[/ञ्ज/g,'ंज'],[/ण्ट/g,'ंट'],[/ण्ड/g,'ंड'],
     [ /ञ्च/g, 'ंच' ], [ /ञ्ज/g, 'ंज' ], [ /ण्ट/g, 'ंट' ], [ /ण्ड/g, 'ंड' ],
     [/न्त/g,'ंत'],[/न्द/g,'ंद'],[/म्ब/g,'ंब'],[/म्भ/g,'ंभ']
     [ /न्त/g, 'ंत' ], [ /न्द/g, 'ंद' ], [ /म्ब/g, 'ंब' ], [ /म्भ/g, 'ंभ' ]
   ];
   ];


   function transliterateText(text, script) {
   function transliterateText( text, script ) {
     if (script === 'en') return devanagariToIAST(text);
     if ( script === 'en' ) return devanagariToIAST( text );
     var map = SCRIPT_MAP[script];
     var map = SCRIPT_MAP[ script ];
     if (!map) return text;
     if ( !map ) return text;
     var t = text;
     var t = text;
     PRE.forEach(function (p) { t = t.replace(p[0], p[1]); });
     PRE.forEach( function ( p ) { t = t.replace( p[ 0 ], p[ 1 ] ); } );
     return Array.from(t).map(function (ch) {
     return Array.from( t ).map( function ( ch ) {
       return map[ch] !== undefined ? map[ch] : ch;
       return map[ ch ] !== undefined ? map[ ch ] : ch;
     }).join('');
     } ).join( '' );
   }
   }


   // ── Collect all transliteratable text nodes once ────────────────
   // ── Tag all transliteratable text nodes once per page ───────────
  // Store originals as data-deva on a wrapper span.
  // On script switch, update textContent of those spans — never
  // touch innerHTML of the whole content block.
   var translatableSpans = [];
   var translatableSpans = [];


   function tagTextNodes() {
   function tagTextNodes() {
     var content = document.querySelector('.mw-parser-output');
     var content = document.querySelector( '.mw-parser-output' );
     if (!content) return;
     if ( content ) {
      var walker = document.createTreeWalker( content, NodeFilter.SHOW_TEXT );
      var nodes  = [];
      while ( walker.nextNode() ) nodes.push( walker.currentNode );


    var walker = document.createTreeWalker(content, NodeFilter.SHOW_TEXT);
      nodes.forEach( function ( node ) {
    var nodes = [];
        var p = node.parentNode;
    while (walker.nextNode()) nodes.push(walker.currentNode);
        if ( !p ) return;
        if ( p.hasAttribute && p.hasAttribute( 'data-deva' ) ) return;
        if ( p.closest ) {
          if ( p.closest( '.gr-controls' ) || p.closest( '.mw-editsection' ) ) return;
        }
        var orig = node.textContent;
        if ( !orig.trim() ) return;
        var span = document.createElement( 'span' );
        span.setAttribute( 'data-deva', orig );
        span.textContent = orig;
        p.replaceChild( span, node );
        translatableSpans.push( span );
      } );
    }


     nodes.forEach(function (node) {
     // Tag .vector-toc-text spans for TOC transliteration
      var p = node.parentNode;
    document.querySelectorAll( '.vector-toc .vector-toc-text' ).forEach( function ( span ) {
      if (!p) return;
      if ( span.hasAttribute( 'data-deva' ) ) return;
      // Skip already tagged
       var orig = span.textContent;
      if (p.hasAttribute && p.hasAttribute('data-deva')) return;
       if ( !orig.trim() ) return;
      // Skip UI elements
       span.setAttribute( 'data-deva', orig );
      if (p.closest) {
       translatableSpans.push( span );
        if (p.closest('.gr-script-bar') ||
     } );
            p.closest('.vector-toc') ||
            p.closest('#toc') ||
            p.closest('.mw-editsection')) return;
      }
       var orig = node.textContent;
       if (!orig.trim()) return;
      // Wrap in span with original stored
      var span = document.createElement('span');
       span.setAttribute('data-deva', orig);
      span.textContent = orig;
      p.replaceChild(span, node);
       translatableSpans.push(span);
     });
   }
   }


   function applyScript(script) {
  // ── Apply a script to all tagged spans ─────────────────────────
   function applyScript( script ) {
     currentScript = script;
     currentScript = script;
     translatableSpans.forEach(function (span) {
     translatableSpans.forEach( function ( span ) {
       if (!span.parentNode) return; // detached
       if ( !span.parentNode ) return;
       var orig = span.getAttribute('data-deva');
       var orig = span.getAttribute( 'data-deva' );
       if (script === 'deva') {
       if ( !orig ) return;
         span.textContent = orig;
      span.textContent = ( script === 'deva' )
        ? orig
        : transliterateText( orig, script );
    } );
  }
 
  // ── TOC active-item highlight ────────────────────────────────────
  // FIX: Instead of relying on CSS :active selectors (which fail because
  // Common.js wraps text nodes in <span data-deva>, making > a or > .link
  // selectors not match the coloured text), we use a MutationObserver to
  // watch each <li> for class changes and imperatively apply/remove the
  // orange colour via inline style on the .vector-toc-link inside it.
  // This is immune to DOM depth and span nesting.
  function watchTocActive() {
    var toc = document.querySelector( '.vector-toc' );
    if ( !toc ) return;
    if ( !window.MutationObserver ) return;
    /* Guard only the structObserver — attach it once per toc element.
      Per-<li> attachment is already guarded by _grHighlightAttached,
      so calling watchTocActive() multiple times is safe and picks up
      any <li> items that weren't in the DOM on the first call. */
    if ( toc._grObserved ) {
      /* Re-scan for any <li> items that arrived after first call */
      toc.querySelectorAll( '.vector-toc-list-item' ).forEach( attachHighlight );
      return;
    }
    toc._grObserved = true;
 
    var ACTIVE_COLOR  = '#f57c00';
    var ACTIVE_WEIGHT = '700';
 
    function setLinkActive( li, active ) {
      var link = li.querySelector( '.vector-toc-link' ) || li.querySelector( 'a' );
      if ( !link ) return;
      if ( active ) {
         link.style.setProperty( 'color',      ACTIVE_COLOR,  'important' );
        link.style.setProperty( 'font-weight', ACTIVE_WEIGHT, 'important' );
        /* Colour ALL descendant elements — covers both:
        *  • data-deva <span> wrappers (Devanagari mode, textContent replaced)
        *  • .vector-toc-text / .vector-toc-numb spans (all scripts)
        * After applyScript() runs for non-Deva scripts, textContent is a
        * plain text node so querySelectorAll('span') still finds the
        * structural spans (.vector-toc-text etc.) which need colouring. */
        link.querySelectorAll( '*' ).forEach( function ( el ) {
          el.style.setProperty( 'color', ACTIVE_COLOR, 'important' );
        } );
       } else {
       } else {
         span.textContent = transliterateText(orig, script);
         link.style.removeProperty( 'color' );
        link.style.removeProperty( 'font-weight' );
        link.querySelectorAll( '*' ).forEach( function ( el ) {
          el.style.removeProperty( 'color' );
        } );
       }
       }
    });
    // Update active button
    var bar = document.querySelector('.gr-script-bar');
    if (bar) {
      bar.querySelectorAll('.gr-script-btn').forEach(function (b) {
        b.classList.toggle('active', b.getAttribute('data-script') === script);
      });
     }
     }
    function attachHighlight( li ) {
      if ( li._grHighlightAttached ) return;
      li._grHighlightAttached = true;
      liObserver.observe( li, { attributes: true, attributeFilter: [ 'class' ] } );
      /* Apply immediately if already active on attachment */
      if ( li.classList.contains( 'vector-toc-list-item-active' ) ) {
        setLinkActive( li, true );
      }
    }
    var liObserver = new MutationObserver( function ( mutations ) {
      mutations.forEach( function ( m ) {
        if ( m.attributeName !== 'class' ) return;
        var li = m.target;
        var isActive = li.classList.contains( 'vector-toc-list-item-active' );
        setLinkActive( li, isActive );
        /* Scroll active item into view within the TOC container —
        * but ONLY when the TOC sidebar is actually visible and expanded.
        * If the TOC is collapsed or hidden, scrollIntoView scrolls the
        * whole page instead of just the TOC, which hijacks the reading
        * position. */
        if ( isActive ) {
          /* ── Auto-expand parent section in TOC ────────────────────────
          * Vector collapses child sections under a parent li. When a child
          * becomes active we must expand its parent by removing the
          * vector-toc-list-item-collapsed class, mirroring what Vector's
          * own JS does on click. Walk up to find collapsed ancestors. */
          var ancestor = li.parentNode;
          while ( ancestor && ancestor !== document.body ) {
            if ( ancestor.classList &&
                ancestor.classList.contains( 'vector-toc-list-item' ) &&
                ancestor.classList.contains( 'vector-toc-list-item-collapsed' ) ) {
              ancestor.classList.remove( 'vector-toc-list-item-collapsed' );
            }
            ancestor = ancestor.parentNode;
          }
          /* ── Scroll active item into view within the TOC ──────────────
          * Use getBoundingClientRect for both the item and the scroll
          * container so the measurement is always in viewport coords —
          * avoids the offsetTop-relative-to-offsetParent mismatch. */
          var container = document.querySelector( '.vector-sticky-pinned-container' );
          if ( container ) {
            var tocVisible = container.offsetHeight > 0 &&
                            container.offsetParent !== null &&
                            window.getComputedStyle( container ).display !== 'none' &&
                            window.getComputedStyle( container ).visibility !== 'hidden';
            if ( tocVisible ) {
              var liRect = li.getBoundingClientRect();
              var cRect  = container.getBoundingClientRect();
              /* Only scroll if the item is outside the visible container area */
              if ( liRect.top < cRect.top + 4 || liRect.bottom > cRect.bottom - 4 ) {
                /* Walk up to find the actual scrollable ancestor */
                var scrollHost = null;
                var node = li.parentNode;
                while ( node && node !== document.body ) {
                  var overflow = window.getComputedStyle( node ).overflowY;
                  if ( ( overflow === 'auto' || overflow === 'scroll' ) &&
                      node.scrollHeight > node.clientHeight ) {
                    scrollHost = node;
                    break;
                  }
                  node = node.parentNode;
                }
                /* Fallback: use container itself if no scrollable ancestor found */
                if ( !scrollHost && container.scrollHeight > container.clientHeight ) {
                  scrollHost = container;
                }
                if ( scrollHost ) {
                  /* Convert li position to scrollHost-relative using rects */
                  var hostRect = scrollHost.getBoundingClientRect();
                  var currentScroll = scrollHost.scrollTop;
                  var liTop = liRect.top - hostRect.top + currentScroll;
                  var target = liTop - ( scrollHost.clientHeight / 2 ) + ( li.offsetHeight / 2 );
                  scrollHost.scrollTop = Math.max( 0, target );
                }
              }
            }
          }
        }
      } );
    } );
    var structObserver = new MutationObserver( function ( mutations ) {
      mutations.forEach( function ( m ) {
        if ( m.type !== 'childList' ) return;
        m.addedNodes.forEach( function ( n ) {
          if ( n.nodeType !== 1 ) return;
          /* Attach highlight observer to newly added list items */
          if ( n.classList && n.classList.contains( 'vector-toc-list-item' ) ) {
            attachHighlight( n );
          }
          if ( n.querySelectorAll ) {
            n.querySelectorAll( '.vector-toc-list-item' ).forEach( attachHighlight );
          }
          /* Tag any new .vector-toc-text spans for transliteration */
          var newSpans = [];
          if ( n.classList && n.classList.contains( 'vector-toc-text' ) ) newSpans.push( n );
          if ( n.querySelectorAll ) {
            n.querySelectorAll( '.vector-toc-text' ).forEach( function ( s ) { newSpans.push( s ); } );
          }
          newSpans.forEach( function ( span ) {
            if ( span.hasAttribute( 'data-deva' ) ) return;
            var orig = span.textContent;
            if ( !orig.trim() ) return;
            span.setAttribute( 'data-deva', orig );
            if ( currentScript !== 'deva' ) {
              span.textContent = transliterateText( orig, currentScript );
            }
            translatableSpans.push( span );
          } );
        } );
      } );
    } );
    toc.querySelectorAll( '.vector-toc-list-item' ).forEach( attachHighlight );
    structObserver.observe( toc, { childList: true, subtree: true } );
    /* On initial load, colour the already-active item.
    * scrollIntoView is intentionally skipped here — calling it while the
    * TOC sidebar might be collapsed causes the PAGE to scroll to the element
    * rather than scrolling within the TOC container.  The liObserver handles
    * scrolling the TOC as the user scrolls the page content. */
    setTimeout( function () {
      var active = toc.querySelector( '.vector-toc-list-item-active' );
      if ( active ) {
        setLinkActive( active, true );
      }
    }, 300 );
   }
   }


   // ── Build switcher bar ─────────────────────────────────────────
   // ── Init ────────────────────────────────────────────────────────
   function buildBar() {
   function init() {
     var title = document.querySelector('.gr-doc-title');
     /* Remove appearance panel + watchlist overflow.
    if (!title) return;
    * Vector injects some of these elements via its own JS after DOMContentLoaded,
    if (document.querySelector('.gr-script-bar')) return;
    * so we use a MutationObserver to catch them whenever they appear. */
    /* Remove appearance panel elements by their stable IDs only.
    * We deliberately avoid class-based selectors like
    * .mw-portlet-vector-user-menu-overflow because on some Vector versions
    * that class name is shared with the user-menu portlet (which contains
    * the login/logout/preferences links) and removing it hides the profile
    * dropdown.  ID-based removal is safe and precise. */
    var HIDE_IDS = [
      'vector-appearance',
      'vector-appearance-pinned-container',
      'vector-appearance-unpinned-container'
    ];
    function removeHiddenEls() {
      HIDE_IDS.forEach( function ( id ) {
        var el = document.getElementById( id );
        if ( el && el.parentNode ) el.parentNode.removeChild( el );
      } );
      /* Also remove the appearance toggle button by its aria-controls attribute.
      * Scope the search to page-tools area only — never touch the header user-links. */
      var pageTools = document.getElementById( 'vector-page-tools' ) ||
                      document.querySelector( '.vector-page-tools-pinned-container' );
      if ( pageTools ) {
        pageTools.querySelectorAll( '[aria-controls="vector-appearance"]' )
          .forEach( function ( el ) {
            if ( el.parentNode ) el.parentNode.removeChild( el );
          } );
      }
    }
    removeHiddenEls();
 
    /* ── Teeka view-mode detection ────────────────────────────────────────
    * Teeka pages carry <div class="gr-teeka-page" data-primary="X" data-slug="Y">
    *
    * Two modes:
    *  gr-standalone  — user opened the teeka URL directly, or ?ref=0
    *                    → plain reading view, no coloured containers
    *  gr-ref-mode    — user navigated here from the main doc, or ?ref=1
    *                    → coloured teeka-block containers (the default styled view)
    *
    * Detection order: ?ref= query param > document.referrer > default (standalone)
    * ─────────────────────────────────────────────────────────────────── */
    ( function detectTeekaMode() {
      var teekaPage = document.querySelector( '.gr-teeka-page' );
      if ( !teekaPage ) return; // not a teeka page — nothing to do
 
      var primary = teekaPage.getAttribute( 'data-primary' ) || '';
      var artPath = ( window.mw && mw.config.get( 'wgArticlePath' ) ) || '/wiki/$1';
      var mainUrl = artPath.replace( '$1', primary );
 
      // 1. Query param override: ?ref=1 or ?ref=0
      var qs = window.location.search;
      var refParam = qs.match( /[?&]ref=([01])/ );
      if ( refParam ) {
        document.body.classList.add( refParam[1] === '1' ? 'gr-ref-mode' : 'gr-standalone' );
        return;
      }


    var bar = document.createElement('div');
      // 2. Referrer check — did we come from the main doc?
    bar.className = 'gr-script-bar';
      var ref = document.referrer || '';
    bar.innerHTML =
      var fromMain = ref && primary && ref.indexOf( mainUrl ) !== -1;
      '<span class="gr-script-label">change script to</span>' +
       document.body.classList.add( fromMain ? 'gr-ref-mode' : 'gr-standalone' );
       '<a class="gr-script-btn active" data-script="deva">देवनागरी</a>' +
    }() );
      '<a class="gr-script-btn" data-script="kn">ಕನ್ನಡ</a>' +
      '<a class="gr-script-btn" data-script="ta">தமிழ்</a>' +
      '<a class="gr-script-btn" data-script="en">English</a>';


     title.after(bar);
     if ( window.MutationObserver ) {
      var hideObserver = new MutationObserver( function ( mutations ) {
        var needsClean = false;
        mutations.forEach( function ( m ) {
          if ( m.addedNodes.length ) needsClean = true;
        } );
        if ( needsClean ) removeHiddenEls();
      } );
      /* Watch only direct children of body — NOT subtree.
      * Vector appends the appearance panel as a direct child of body.
      * Using subtree:true would fire on every inner DOM change (including
      * Vector setting active classes on TOC items) and interfere with the
      * liObserver that handles active highlight colouring. */
      hideObserver.observe( document.body, { childList: true, subtree: false } );
      /* Stop observing after 6s — Vector will have finished by then */
      setTimeout( function () { hideObserver.disconnect(); }, 6000 );
    }


     bar.querySelectorAll('.gr-script-btn').forEach(function (btn) {
     var content      = document.querySelector( '.mw-parser-output' );
       btn.addEventListener('click', function (e) {
    var alreadyTagged = content && content.querySelector( '[data-deva]' );
         e.preventDefault();
    if ( !alreadyTagged ) {
         applyScript(btn.getAttribute('data-script'));
      translatableSpans = [];
       });
      tagTextNodes();
     });
    } else {
       document.querySelectorAll( '.vector-toc .vector-toc-text:not([data-deva])' ).forEach( function ( span ) {
         var orig = span.textContent;
        if ( !orig.trim() ) return;
         span.setAttribute( 'data-deva', orig );
        translatableSpans.push( span );
      } );
    }
 
    var saved = ( function () {
       try { return localStorage.getItem( LS_SCRIPT_KEY ); } catch ( e ) { return null; }
     }() );
    if ( saved && saved !== 'deva' ) {
      applyScript( saved );
    } else {
      currentScript = 'deva';
    }
 
    watchTocActive();
    /* Retry for Vector 2022 TOC which renders after DOMContentLoaded */
    setTimeout( watchTocActive, 300 );
    setTimeout( watchTocActive, 800 );
   }
   }


   // ── TOC active highlight (CSS-driven, MutationObserver backup) ──
   // ── React to toolbar dropdown changes ──────────────────────────
  function watchTocActive() {
  window.addEventListener( 'gr-script-change', function ( e ) {
     var toc = document.querySelector('.vector-toc');
     var script = e && e.detail && e.detail.script;
     if (!toc || toc._grObserved) return;
     if ( script ) applyScript( script );
    toc._grObserved = true;
  } );


     var observer = new MutationObserver(function (mutations) {
  // ── MediaWiki hook (SPA-style navigation) ───────────────────────
       mutations.forEach(function (m) {
  if ( window.mw ) {
         if (m.attributeName !== 'class') return;
     mw.hook( 'wikipage.content' ).add( function () {
         var li = m.target;
       setTimeout( function () {
        var link = li.querySelector(':scope > .vector-toc-link');
         var content      = document.querySelector( '.mw-parser-output' );
         if (!link) return;
         var alreadyTagged = content && content.querySelector( '[data-deva]' );
        if (li.classList.contains('vector-toc-list-item-active')) {
         if ( !alreadyTagged ) {
           link.style.color = '#f57c00';
           translatableSpans = [];
           link.style.fontWeight = '700';
           tagTextNodes();
         } else {
         } else {
           link.style.color = '';
           document.querySelectorAll( '.vector-toc .vector-toc-text:not([data-deva])' ).forEach( function ( span ) {
          link.style.fontWeight = '';
            var orig = span.textContent;
            if ( !orig.trim() ) return;
            span.setAttribute( 'data-deva', orig );
            translatableSpans.push( span );
          } );
         }
         }
       });
        if ( currentScript !== 'deva' ) applyScript( currentScript );
     });
        watchTocActive();
       }, 150 );
     } );
  }


    toc.querySelectorAll('.vector-toc-list-item').forEach(function (li) {
  if ( document.readyState === 'loading' ) {
      observer.observe(li, { attributes: true, attributeFilter: ['class'] });
    document.addEventListener( 'DOMContentLoaded', init );
     });
  } else {
     init();
   }
   }


  // ── Init ───────────────────────────────────────────────────────
}() );
   function init() {
 
     tagTextNodes();
 
     buildBar();
// ── Main page: by-Grantha / by-Author toggle ──────────────────
     watchTocActive();
( function () {
   function grHomeView( v ) {
     var gView = document.getElementById( 'gr-view-grantha' );
    var aView = document.getElementById( 'gr-view-author' );
    var gBtn  = document.getElementById( 'gr-toggle-grantha' );
     var aBtn  = document.getElementById( 'gr-toggle-author' );
     if ( !gView || !aView || !gBtn || !aBtn ) return;
 
    gView.style.display = ( v === 'grantha' ) ? '' : 'none';
    aView.style.display = ( v === 'author'  ) ? '' : 'none';
    gBtn.className = 'gr-toggle-btn' + ( v === 'grantha' ? ' gr-toggle-active' : '' );
    aBtn.className = 'gr-toggle-btn' + ( v === 'author'  ? ' gr-toggle-active' : '' );
    try { localStorage.setItem( 'gr_home_view', v ); } catch ( e ) {}
   }
   }


   // MW hook fires when page content is ready (including after MW re-renders)
   function initHomeToggle() {
  var hooked = false;
    var gBtn = document.getElementById( 'gr-toggle-grantha' );
  if (window.mw) {
    var aBtn = document.getElementById( 'gr-toggle-author' );
    mw.hook('wikipage.content').add(function () {
    if ( !gBtn || !aBtn ) return;
      var oldBar = document.querySelector('.gr-script-bar');
 
      if (oldBar) oldBar.remove();
    gBtn.addEventListener( 'click', function () { grHomeView( 'grantha' ); } );
      if (!hooked) {
    aBtn.addEventListener( 'click', function () { grHomeView( 'author' );  } );
        // First run — tag nodes and build everything
    [ gBtn, aBtn ].forEach( function ( btn ) {
        hooked = true;
       btn.addEventListener( 'keydown', function ( e ) {
        translatableSpans = [];
        if ( e.key === 'Enter' || e.key === ' ' ) btn.click();
        setTimeout(init, 100);
      } );
       } else {
    } );
        // Subsequent MW re-renders — nodes are already tagged,
 
        // just rebuild the bar and re-attach the TOC observer
    var saved;
        setTimeout(function () {
    try { saved = localStorage.getItem( 'gr_home_view' ); } catch ( e ) {}
          buildBar();
     if ( saved === 'author' ) grHomeView( 'author' );
          watchTocActive();
        }, 100);
      }
     });
   }
   }


  // Fallback for non-MW environments
   if ( document.readyState === 'loading' ) {
   if (document.readyState === 'loading') {
     document.addEventListener( 'DOMContentLoaded', initHomeToggle );
     document.addEventListener('DOMContentLoaded', init);
   } else {
   } else {
     init();
     initHomeToggle();
   }
   }
 
}() );
})();

Latest revision as of 17:40, 25 April 2026

/* MediaWiki:Common.js — grantha.io  (v6)
 *
 * Changes vs v5:
 *  1. TOC active highlight fix: Vector 2022 sets the active class on the
 *     <li.vector-toc-list-item>, but Common.js wraps all text nodes inside
 *     .vector-toc-text spans in <span data-deva="…">.  The CSS colour rule
 *     was targeting .vector-toc-list-item-active > a which never matched
 *     because the <a> sits deeper and its text is now inside a <span>.
 *     Fix: MutationObserver watches the <li> for class changes and directly
 *     applies/removes the orange colour via inline style on the .vector-toc-link
 *     ancestor, bypassing the CSS specificity war entirely.
 *  2. All other behaviour identical to v5.
 */

( function () {

  var LS_SCRIPT_KEY = 'grantha_reader_script';
  var currentScript = 'deva';

  // ── IAST transliteration ────────────────────────────────────────
  function devanagariToIAST( text ) {
    var CONSONANTS = {
      'क':'k','ख':'kh','ग':'g','घ':'gh','ङ':'ṅ',
      'च':'c','छ':'ch','ज':'j','झ':'jh','ञ':'ñ',
      'ट':'ṭ','ठ':'ṭh','ड':'ḍ','ढ':'ḍh','ण':'ṇ',
      'त':'t','थ':'th','द':'d','ध':'dh','न':'n',
      'प':'p','फ':'ph','ब':'b','भ':'bh','म':'m',
      'य':'y','र':'r','ल':'l','ळ':'ḷ','व':'v',
      'श':'ś','ष':'ṣ','स':'s','ह':'h'
    };
    var DIACRITICS = {
      'ा':'ā','ि':'i','ी':'ī','ु':'u','ू':'ū',
      'ृ':'ṛ','ॄ':'ṝ','े':'e','ै':'ai','ो':'o','ौ':'au'
    };
    var VOWELS = {
      'अ':'a','आ':'ā','इ':'i','ई':'ī','उ':'u','ऊ':'ū',
      'ऋ':'ṛ','ॠ':'ṝ','ए':'e','ऐ':'ai','ओ':'o','औ':'au','ऽ':"'"
    };
    var MISC = {
      'ं':'ṃ','ः':'ḥ','ँ':'m̐','ॐ':'oṃ',
      '०':'0','१':'1','२':'2','३':'3','४':'4',
      '५':'5','६':'6','७':'7','८':'8','९':'9'
    };
    var HALANTA = '्';
    var chars = Array.from( text );
    var result = '';
    var i = 0;
    while ( i < chars.length ) {
      var ch   = chars[ i ];
      var next = chars[ i + 1 ];
      if ( CONSONANTS[ ch ] ) {
        var base = CONSONANTS[ ch ];
        if ( next === HALANTA )          { result += base;               i += 2; }
        else if ( DIACRITICS[ next ] )   { result += base + DIACRITICS[ next ]; i += 2; }
        else if ( next === 'ं' || next === 'ः' ) { result += base + 'a' + MISC[ next ]; i += 2; }
        else                             { result += base + 'a';         i++;    }
      } else if ( VOWELS[ ch ] )         { result += VOWELS[ ch ];       i++; }
      else if ( DIACRITICS[ ch ] )       { result += DIACRITICS[ ch ];   i++; }
      else if ( MISC[ ch ] )             { result += MISC[ ch ];         i++; }
      else                               { result += ch;                 i++; }
    }
    return result;
  }

  // ── Character maps for Kannada / Tamil ─────────────────────────
  var SCRIPT_MAP = {
    kn: {
      'अ':'ಅ','आ':'ಆ','इ':'ಇ','ई':'ಈ','उ':'ಉ','ऊ':'ಊ','ऋ':'ಋ',
      'ए':'ಏ','ऐ':'ಐ','ओ':'ಓ','औ':'ಔ','ऽ':'ಽ',
      'क':'ಕ','ख':'ಖ','ग':'ಗ','घ':'ಘ','ङ':'ಙ',
      'च':'ಚ','छ':'ಛ','ज':'ಜ','झ':'ಝ','ञ':'ಞ',
      'ट':'ಟ','ठ':'ಠ','ड':'ಡ','ढ':'ಢ','ण':'ಣ',
      'त':'ತ','थ':'ಥ','द':'ದ','ध':'ಧ','न':'ನ',
      'प':'ಪ','फ':'ಫ','ब':'ಬ','भ':'ಭ','म':'ಮ',
      'य':'ಯ','र':'ರ','ल':'ಲ','व':'ವ',
      'श':'ಶ','ष':'ಷ','स':'ಸ','ह':'ಹ',
      'ा':'ಾ','ि':'ಿ','ी':'ೀ','ु':'ು','ू':'ೂ',
      'ृ':'ೃ','े':'ೇ','ै':'ೈ','ो':'ೋ','ौ':'ೌ',
      'ं':'ಂ','ः':'ಃ','्':'್',
      '०':'೦','१':'೧','२':'೨','३':'೩','४':'೪',
      '५':'೫','६':'೬','७':'೭','८':'೮','९':'೯'
    },
    ta: {
      'अ':'அ','आ':'ஆ','इ':'இ','ई':'ஈ','उ':'உ','ऊ':'ஊ',
      'ऋ':'ரு','ॠ':'ரூ',
      'ए':'ஏ','ऐ':'ஐ','ओ':'ஓ','औ':'ஔ',
      'क':'க','ख':'க','ग':'க','घ':'க','ङ':'ங',
      'च':'ச','छ':'ச','ज':'ஜ','झ':'ஜ','ञ':'ஞ',
      'ट':'ட','ठ':'ட','ड':'ட','ढ':'ட','ण':'ண',
      'त':'த','थ':'த','द':'த','ध':'த','न':'ந',
      'प':'ப','फ':'ப','ब':'ப','भ':'ப','म':'ம',
      'य':'ய','र':'ர','ल':'ல','ळ':'ழ','व':'வ',
      'श':'ஶ','ष':'ஷ','स':'ஸ','ह':'ஹ',
      'ा':'ா','ि':'ி','ी':'ீ','ु':'ு','ू':'ூ',
      'ृ':'ு','ॄ':'ூ',
      'े':'ே','ै':'ை','ो':'ோ','ौ':'ௌ',
      'ं':'ம்','ः':':','ँ':'ம்','्':'்','ॐ':'ௐ','ऽ':'ௗ',
      '०':'0','१':'1','२':'2','३':'3','४':'4',
      '५':'5','६':'6','७':'7','८':'8','९':'9'
    }
  };

  var PRE = [
    [ /ङ्क/g, 'ंक' ], [ /ङ्ख/g, 'ंख' ], [ /ङ्ग/g, 'ंग' ], [ /ङ्घ/g, 'ंघ' ],
    [ /ञ्च/g, 'ंच' ], [ /ञ्ज/g, 'ंज' ], [ /ण्ट/g, 'ंट' ], [ /ण्ड/g, 'ंड' ],
    [ /न्त/g, 'ंत' ], [ /न्द/g, 'ंद' ], [ /म्ब/g, 'ंब' ], [ /म्भ/g, 'ंभ' ]
  ];

  function transliterateText( text, script ) {
    if ( script === 'en' ) return devanagariToIAST( text );
    var map = SCRIPT_MAP[ script ];
    if ( !map ) return text;
    var t = text;
    PRE.forEach( function ( p ) { t = t.replace( p[ 0 ], p[ 1 ] ); } );
    return Array.from( t ).map( function ( ch ) {
      return map[ ch ] !== undefined ? map[ ch ] : ch;
    } ).join( '' );
  }

  // ── Tag all transliteratable text nodes once per page ───────────
  var translatableSpans = [];

  function tagTextNodes() {
    var content = document.querySelector( '.mw-parser-output' );
    if ( content ) {
      var walker = document.createTreeWalker( content, NodeFilter.SHOW_TEXT );
      var nodes  = [];
      while ( walker.nextNode() ) nodes.push( walker.currentNode );

      nodes.forEach( function ( node ) {
        var p = node.parentNode;
        if ( !p ) return;
        if ( p.hasAttribute && p.hasAttribute( 'data-deva' ) ) return;
        if ( p.closest ) {
          if ( p.closest( '.gr-controls' ) || p.closest( '.mw-editsection' ) ) return;
        }
        var orig = node.textContent;
        if ( !orig.trim() ) return;
        var span = document.createElement( 'span' );
        span.setAttribute( 'data-deva', orig );
        span.textContent = orig;
        p.replaceChild( span, node );
        translatableSpans.push( span );
      } );
    }

    // Tag .vector-toc-text spans for TOC transliteration
    document.querySelectorAll( '.vector-toc .vector-toc-text' ).forEach( function ( span ) {
      if ( span.hasAttribute( 'data-deva' ) ) return;
      var orig = span.textContent;
      if ( !orig.trim() ) return;
      span.setAttribute( 'data-deva', orig );
      translatableSpans.push( span );
    } );
  }

  // ── Apply a script to all tagged spans ─────────────────────────
  function applyScript( script ) {
    currentScript = script;
    translatableSpans.forEach( function ( span ) {
      if ( !span.parentNode ) return;
      var orig = span.getAttribute( 'data-deva' );
      if ( !orig ) return;
      span.textContent = ( script === 'deva' )
        ? orig
        : transliterateText( orig, script );
    } );
  }

  // ── TOC active-item highlight ────────────────────────────────────
  // FIX: Instead of relying on CSS :active selectors (which fail because
  // Common.js wraps text nodes in <span data-deva>, making > a or > .link
  // selectors not match the coloured text), we use a MutationObserver to
  // watch each <li> for class changes and imperatively apply/remove the
  // orange colour via inline style on the .vector-toc-link inside it.
  // This is immune to DOM depth and span nesting.
  function watchTocActive() {
    var toc = document.querySelector( '.vector-toc' );
    if ( !toc ) return;
    if ( !window.MutationObserver ) return;
    /* Guard only the structObserver — attach it once per toc element.
       Per-<li> attachment is already guarded by _grHighlightAttached,
       so calling watchTocActive() multiple times is safe and picks up
       any <li> items that weren't in the DOM on the first call. */
    if ( toc._grObserved ) {
      /* Re-scan for any <li> items that arrived after first call */
      toc.querySelectorAll( '.vector-toc-list-item' ).forEach( attachHighlight );
      return;
    }
    toc._grObserved = true;

    var ACTIVE_COLOR  = '#f57c00';
    var ACTIVE_WEIGHT = '700';

    function setLinkActive( li, active ) {
      var link = li.querySelector( '.vector-toc-link' ) || li.querySelector( 'a' );
      if ( !link ) return;
      if ( active ) {
        link.style.setProperty( 'color',       ACTIVE_COLOR,  'important' );
        link.style.setProperty( 'font-weight', ACTIVE_WEIGHT, 'important' );
        /* Colour ALL descendant elements — covers both:
         *   • data-deva <span> wrappers (Devanagari mode, textContent replaced)
         *   • .vector-toc-text / .vector-toc-numb spans (all scripts)
         * After applyScript() runs for non-Deva scripts, textContent is a
         * plain text node so querySelectorAll('span') still finds the
         * structural spans (.vector-toc-text etc.) which need colouring. */
        link.querySelectorAll( '*' ).forEach( function ( el ) {
          el.style.setProperty( 'color', ACTIVE_COLOR, 'important' );
        } );
      } else {
        link.style.removeProperty( 'color' );
        link.style.removeProperty( 'font-weight' );
        link.querySelectorAll( '*' ).forEach( function ( el ) {
          el.style.removeProperty( 'color' );
        } );
      }
    }

    function attachHighlight( li ) {
      if ( li._grHighlightAttached ) return;
      li._grHighlightAttached = true;
      liObserver.observe( li, { attributes: true, attributeFilter: [ 'class' ] } );
      /* Apply immediately if already active on attachment */
      if ( li.classList.contains( 'vector-toc-list-item-active' ) ) {
        setLinkActive( li, true );
      }
    }

    var liObserver = new MutationObserver( function ( mutations ) {
      mutations.forEach( function ( m ) {
        if ( m.attributeName !== 'class' ) return;
        var li = m.target;
        var isActive = li.classList.contains( 'vector-toc-list-item-active' );
        setLinkActive( li, isActive );

        /* Scroll active item into view within the TOC container —
         * but ONLY when the TOC sidebar is actually visible and expanded.
         * If the TOC is collapsed or hidden, scrollIntoView scrolls the
         * whole page instead of just the TOC, which hijacks the reading
         * position. */
        if ( isActive ) {
          /* ── Auto-expand parent section in TOC ────────────────────────
           * Vector collapses child sections under a parent li. When a child
           * becomes active we must expand its parent by removing the
           * vector-toc-list-item-collapsed class, mirroring what Vector's
           * own JS does on click. Walk up to find collapsed ancestors. */
          var ancestor = li.parentNode;
          while ( ancestor && ancestor !== document.body ) {
            if ( ancestor.classList &&
                 ancestor.classList.contains( 'vector-toc-list-item' ) &&
                 ancestor.classList.contains( 'vector-toc-list-item-collapsed' ) ) {
              ancestor.classList.remove( 'vector-toc-list-item-collapsed' );
            }
            ancestor = ancestor.parentNode;
          }

          /* ── Scroll active item into view within the TOC ──────────────
           * Use getBoundingClientRect for both the item and the scroll
           * container so the measurement is always in viewport coords —
           * avoids the offsetTop-relative-to-offsetParent mismatch. */
          var container = document.querySelector( '.vector-sticky-pinned-container' );
          if ( container ) {
            var tocVisible = container.offsetHeight > 0 &&
                             container.offsetParent !== null &&
                             window.getComputedStyle( container ).display !== 'none' &&
                             window.getComputedStyle( container ).visibility !== 'hidden';
            if ( tocVisible ) {
              var liRect = li.getBoundingClientRect();
              var cRect  = container.getBoundingClientRect();
              /* Only scroll if the item is outside the visible container area */
              if ( liRect.top < cRect.top + 4 || liRect.bottom > cRect.bottom - 4 ) {
                /* Walk up to find the actual scrollable ancestor */
                var scrollHost = null;
                var node = li.parentNode;
                while ( node && node !== document.body ) {
                  var overflow = window.getComputedStyle( node ).overflowY;
                  if ( ( overflow === 'auto' || overflow === 'scroll' ) &&
                       node.scrollHeight > node.clientHeight ) {
                    scrollHost = node;
                    break;
                  }
                  node = node.parentNode;
                }
                /* Fallback: use container itself if no scrollable ancestor found */
                if ( !scrollHost && container.scrollHeight > container.clientHeight ) {
                  scrollHost = container;
                }
                if ( scrollHost ) {
                  /* Convert li position to scrollHost-relative using rects */
                  var hostRect = scrollHost.getBoundingClientRect();
                  var currentScroll = scrollHost.scrollTop;
                  var liTop = liRect.top - hostRect.top + currentScroll;
                  var target = liTop - ( scrollHost.clientHeight / 2 ) + ( li.offsetHeight / 2 );
                  scrollHost.scrollTop = Math.max( 0, target );
                }
              }
            }
          }
        }
      } );
    } );

    var structObserver = new MutationObserver( function ( mutations ) {
      mutations.forEach( function ( m ) {
        if ( m.type !== 'childList' ) return;
        m.addedNodes.forEach( function ( n ) {
          if ( n.nodeType !== 1 ) return;
          /* Attach highlight observer to newly added list items */
          if ( n.classList && n.classList.contains( 'vector-toc-list-item' ) ) {
            attachHighlight( n );
          }
          if ( n.querySelectorAll ) {
            n.querySelectorAll( '.vector-toc-list-item' ).forEach( attachHighlight );
          }

          /* Tag any new .vector-toc-text spans for transliteration */
          var newSpans = [];
          if ( n.classList && n.classList.contains( 'vector-toc-text' ) ) newSpans.push( n );
          if ( n.querySelectorAll ) {
            n.querySelectorAll( '.vector-toc-text' ).forEach( function ( s ) { newSpans.push( s ); } );
          }
          newSpans.forEach( function ( span ) {
            if ( span.hasAttribute( 'data-deva' ) ) return;
            var orig = span.textContent;
            if ( !orig.trim() ) return;
            span.setAttribute( 'data-deva', orig );
            if ( currentScript !== 'deva' ) {
              span.textContent = transliterateText( orig, currentScript );
            }
            translatableSpans.push( span );
          } );
        } );
      } );
    } );

    toc.querySelectorAll( '.vector-toc-list-item' ).forEach( attachHighlight );
    structObserver.observe( toc, { childList: true, subtree: true } );

    /* On initial load, colour the already-active item.
     * scrollIntoView is intentionally skipped here — calling it while the
     * TOC sidebar might be collapsed causes the PAGE to scroll to the element
     * rather than scrolling within the TOC container.  The liObserver handles
     * scrolling the TOC as the user scrolls the page content. */
    setTimeout( function () {
      var active = toc.querySelector( '.vector-toc-list-item-active' );
      if ( active ) {
        setLinkActive( active, true );
      }
    }, 300 );
  }

  // ── Init ────────────────────────────────────────────────────────
  function init() {
    /* Remove appearance panel + watchlist overflow.
     * Vector injects some of these elements via its own JS after DOMContentLoaded,
     * so we use a MutationObserver to catch them whenever they appear. */
    /* Remove appearance panel elements by their stable IDs only.
     * We deliberately avoid class-based selectors like
     * .mw-portlet-vector-user-menu-overflow because on some Vector versions
     * that class name is shared with the user-menu portlet (which contains
     * the login/logout/preferences links) and removing it hides the profile
     * dropdown.  ID-based removal is safe and precise. */
    var HIDE_IDS = [
      'vector-appearance',
      'vector-appearance-pinned-container',
      'vector-appearance-unpinned-container'
    ];
    function removeHiddenEls() {
      HIDE_IDS.forEach( function ( id ) {
        var el = document.getElementById( id );
        if ( el && el.parentNode ) el.parentNode.removeChild( el );
      } );
      /* Also remove the appearance toggle button by its aria-controls attribute.
       * Scope the search to page-tools area only — never touch the header user-links. */
      var pageTools = document.getElementById( 'vector-page-tools' ) ||
                      document.querySelector( '.vector-page-tools-pinned-container' );
      if ( pageTools ) {
        pageTools.querySelectorAll( '[aria-controls="vector-appearance"]' )
          .forEach( function ( el ) {
            if ( el.parentNode ) el.parentNode.removeChild( el );
          } );
      }
    }
    removeHiddenEls();

    /* ── Teeka view-mode detection ────────────────────────────────────────
     * Teeka pages carry <div class="gr-teeka-page" data-primary="X" data-slug="Y">
     *
     * Two modes:
     *   gr-standalone  — user opened the teeka URL directly, or ?ref=0
     *                    → plain reading view, no coloured containers
     *   gr-ref-mode    — user navigated here from the main doc, or ?ref=1
     *                    → coloured teeka-block containers (the default styled view)
     *
     * Detection order: ?ref= query param > document.referrer > default (standalone)
     * ─────────────────────────────────────────────────────────────────── */
    ( function detectTeekaMode() {
      var teekaPage = document.querySelector( '.gr-teeka-page' );
      if ( !teekaPage ) return;  // not a teeka page — nothing to do

      var primary = teekaPage.getAttribute( 'data-primary' ) || '';
      var artPath = ( window.mw && mw.config.get( 'wgArticlePath' ) ) || '/wiki/$1';
      var mainUrl = artPath.replace( '$1', primary );

      // 1. Query param override: ?ref=1 or ?ref=0
      var qs = window.location.search;
      var refParam = qs.match( /[?&]ref=([01])/ );
      if ( refParam ) {
        document.body.classList.add( refParam[1] === '1' ? 'gr-ref-mode' : 'gr-standalone' );
        return;
      }

      // 2. Referrer check — did we come from the main doc?
      var ref = document.referrer || '';
      var fromMain = ref && primary && ref.indexOf( mainUrl ) !== -1;
      document.body.classList.add( fromMain ? 'gr-ref-mode' : 'gr-standalone' );
    }() );

    if ( window.MutationObserver ) {
      var hideObserver = new MutationObserver( function ( mutations ) {
        var needsClean = false;
        mutations.forEach( function ( m ) {
          if ( m.addedNodes.length ) needsClean = true;
        } );
        if ( needsClean ) removeHiddenEls();
      } );
      /* Watch only direct children of body — NOT subtree.
       * Vector appends the appearance panel as a direct child of body.
       * Using subtree:true would fire on every inner DOM change (including
       * Vector setting active classes on TOC items) and interfere with the
       * liObserver that handles active highlight colouring. */
      hideObserver.observe( document.body, { childList: true, subtree: false } );
      /* Stop observing after 6s — Vector will have finished by then */
      setTimeout( function () { hideObserver.disconnect(); }, 6000 );
    }

    var content       = document.querySelector( '.mw-parser-output' );
    var alreadyTagged = content && content.querySelector( '[data-deva]' );
    if ( !alreadyTagged ) {
      translatableSpans = [];
      tagTextNodes();
    } else {
      document.querySelectorAll( '.vector-toc .vector-toc-text:not([data-deva])' ).forEach( function ( span ) {
        var orig = span.textContent;
        if ( !orig.trim() ) return;
        span.setAttribute( 'data-deva', orig );
        translatableSpans.push( span );
      } );
    }

    var saved = ( function () {
      try { return localStorage.getItem( LS_SCRIPT_KEY ); } catch ( e ) { return null; }
    }() );
    if ( saved && saved !== 'deva' ) {
      applyScript( saved );
    } else {
      currentScript = 'deva';
    }

    watchTocActive();
    /* Retry for Vector 2022 TOC which renders after DOMContentLoaded */
    setTimeout( watchTocActive, 300 );
    setTimeout( watchTocActive, 800 );
  }

  // ── React to toolbar dropdown changes ──────────────────────────
  window.addEventListener( 'gr-script-change', function ( e ) {
    var script = e && e.detail && e.detail.script;
    if ( script ) applyScript( script );
  } );

  // ── MediaWiki hook (SPA-style navigation) ───────────────────────
  if ( window.mw ) {
    mw.hook( 'wikipage.content' ).add( function () {
      setTimeout( function () {
        var content       = document.querySelector( '.mw-parser-output' );
        var alreadyTagged = content && content.querySelector( '[data-deva]' );
        if ( !alreadyTagged ) {
          translatableSpans = [];
          tagTextNodes();
        } else {
          document.querySelectorAll( '.vector-toc .vector-toc-text:not([data-deva])' ).forEach( function ( span ) {
            var orig = span.textContent;
            if ( !orig.trim() ) return;
            span.setAttribute( 'data-deva', orig );
            translatableSpans.push( span );
          } );
        }
        if ( currentScript !== 'deva' ) applyScript( currentScript );
        watchTocActive();
      }, 150 );
    } );
  }

  if ( document.readyState === 'loading' ) {
    document.addEventListener( 'DOMContentLoaded', init );
  } else {
    init();
  }

}() );


// ── Main page: by-Grantha / by-Author toggle ──────────────────
( function () {
  function grHomeView( v ) {
    var gView = document.getElementById( 'gr-view-grantha' );
    var aView = document.getElementById( 'gr-view-author' );
    var gBtn  = document.getElementById( 'gr-toggle-grantha' );
    var aBtn  = document.getElementById( 'gr-toggle-author' );
    if ( !gView || !aView || !gBtn || !aBtn ) return;

    gView.style.display = ( v === 'grantha' ) ? '' : 'none';
    aView.style.display = ( v === 'author'  ) ? '' : 'none';
    gBtn.className = 'gr-toggle-btn' + ( v === 'grantha' ? ' gr-toggle-active' : '' );
    aBtn.className = 'gr-toggle-btn' + ( v === 'author'  ? ' gr-toggle-active' : '' );
    try { localStorage.setItem( 'gr_home_view', v ); } catch ( e ) {}
  }

  function initHomeToggle() {
    var gBtn = document.getElementById( 'gr-toggle-grantha' );
    var aBtn = document.getElementById( 'gr-toggle-author' );
    if ( !gBtn || !aBtn ) return;

    gBtn.addEventListener( 'click', function () { grHomeView( 'grantha' ); } );
    aBtn.addEventListener( 'click', function () { grHomeView( 'author' );  } );
    [ gBtn, aBtn ].forEach( function ( btn ) {
      btn.addEventListener( 'keydown', function ( e ) {
        if ( e.key === 'Enter' || e.key === ' ' ) btn.click();
      } );
    } );

    var saved;
    try { saved = localStorage.getItem( 'gr_home_view' ); } catch ( e ) {}
    if ( saved === 'author' ) grHomeView( 'author' );
  }

  if ( document.readyState === 'loading' ) {
    document.addEventListener( 'DOMContentLoaded', initHomeToggle );
  } else {
    initHomeToggle();
  }
}() );