Jump to content

MediaWiki:Common.js: Difference between revisions

From Grantha
No edit summary
No edit summary
 
(15 intermediate revisions by the same user not shown)
Line 1: Line 1:
(function () {
/* MediaWiki:Common.js — grantha.io
*
* Responsibilities:
*  1. Transliteration engine (Devanāgarī → IAST / Kannada / Tamil).
*  2. Tag all transliteratable text nodes once per page load.
*  3. Apply the script stored in localStorage('grantha_reader_script')
*    so every page opens in the user's preferred script automatically.
*  4. Listen for the 'gr-script-change' CustomEvent dispatched by the
*    ReaderToolbar dropdown and re-apply the new script immediately.
*  5. TOC active-item highlight via MutationObserver (unchanged).
*
* The script-switcher bar/buttons previously built here are removed —
* the ReaderToolbar extension now owns the dropdown UI.
*
* localStorage key shared with ReaderToolbar: 'grantha_reader_script'
*/


  // ── 1. Load Sanscript from a reliable CDN ──────────────────────
( function () {
  var sanscriptReady = false;
  var s = document.createElement('script');
  s.src = 'https://cdn.jsdelivr.net/gh/sanskrit-coders/sanscript.js@master/sanscript.js';
  s.onload = function () { sanscriptReady = true; };
  document.head.appendChild(s);


   // ── 2. Character maps ──────────────────────────────────────────
  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 = {
   var SCRIPT_MAP = {
     kn: {
     kn: {
Line 28: Line 86:
     ta: {
     ta: {
       'अ':'அ','आ':'ஆ','इ':'இ','ई':'ஈ','उ':'உ','ऊ':'ஊ',
       'अ':'அ','आ':'ஆ','इ':'இ','ई':'ஈ','उ':'உ','ऊ':'ஊ',
      'ऋ':'ரு','ॠ':'ரூ',
       'ए':'ஏ','ऐ':'ஐ','ओ':'ஓ','औ':'ஔ',
       'ए':'ஏ','ऐ':'ஐ','ओ':'ஓ','औ':'ஔ',
       'क':'க','ख':'க','ग':'க','घ':'க','ङ':'ங',
       'क':'க','ख':'க','ग':'க','घ':'க','ङ':'ங',
       'च':'ச','छ':'ச','ज':'ஜ','झ':'ஜ','ञ':'ஞ',
       'च':'ச','छ':'ச','ज':'ஜ','झ':'ஜ','ञ':'ஞ',
       'ट':'ட','ठ':'ட','ड':'ட','ढ':'ட','':'ண',
       'ट':'ட','ठ':'ட','ड':'ட','ढ':'ட','':'ண',
       'त':'த','थ':'த','द':'த','ध':'த','न':'ந',
       'त':'த','थ':'த','द':'த','ध':'த','न':'ந',
       'प':'ப','फ':'ப','ब':'ப','भ':'ப','म':'ம',
       'प':'ப','फ':'ப','ब':'ப','भ':'ப','म':'ம',
       'य':'ய','र':'ர','ल':'ல','व':'வ',
       'य':'ய','र':'ர','ल':'ல','ळ':'ழ','व':'வ',
       'श':'ஶ','ष':'ஷ','स':'ஸ','ह':'ஹ',
       'श':'ஶ','ष':'ஷ','स':'ஸ','ह':'ஹ',
       'ा':'ா','ि':'ி','ी':'ீ','ு':'ு','':'ூ',
       'ा':'ா','ि':'ி','ी':'ீ','ु':'ு','ू':'ூ',
      'ृ':'ு','':'ூ',
       'े':'ே','ै':'ை','ो':'ோ','ौ':'ௌ',
       'े':'ே','ै':'ை','ो':'ோ','ौ':'ௌ',
       'ं':'ம்','ः':':','्':'்','ॐ':'ௐ',
       'ं':'ம்','ः':':','ँ':'ம்','्':'்','ॐ':'ௐ','ऽ':'ௗ',
       '०':'0','१':'1','२':'2','३':'3','४':'4',
       '०':'0','१':'1','२':'2','३':'3','४':'4',
       '५':'5','६':'6','७':'7','':'8','९':'9'
       '५':'5','६':'6','७':'7','':'8','९':'9'
     }
     }
   };
   };


   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 preProcess(t) {
   function transliterateText( text, script ) {
     PRE.forEach(function (p) { t = t.replace(p[0], p[1]); });
    if ( script === 'en' ) return devanagariToIAST( text );
     return t;
    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( '' );
   }
   }


   function transliterateText(text, script) {
  // ── Tag all transliteratable text nodes once per page ───────────
     if (script === 'en') {
  var translatableSpans = [];
      if (sanscriptReady && window.Sanscript) {
 
         return window.Sanscript.t(text, 'devanagari', 'iast');
   function tagTextNodes() {
       }
    // ── Main article content ──────────────────────────────────────
      return text;
    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 );
       } );
     }
     }
    var map = SCRIPT_MAP[script];
 
     if (!map) return text;
     // ── Sidebar TOC (.vector-toc-text spans) ─────────────────────
     return Array.from(preProcess(text)).map(function (ch) {
    // We target the .vector-toc-text spans that Vector itself renders,
       return map[ch] !== undefined ? map[ch] : ch;
    // rather than walking raw text nodes. Mutating textContent of an
    }).join('');
    // existing child span is a characterData mutation — Vector's own
    // MutationObserver only watches for childList changes on the <li>,
    // so it will NOT fire, and the "unknown title" bug is avoided.
     document.querySelectorAll( '.vector-toc .vector-toc-text' ).forEach( function ( span ) {
       if ( span.hasAttribute( 'data-deva' ) ) return; // already tagged
      var orig = span.textContent;
      if ( !orig.trim() ) return;
      span.setAttribute( 'data-deva', orig );
      translatableSpans.push( span );
    } );
   }
   }


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


    // Restore devanagari first
  // ── TOC active-item highlight ───────────────────────────────────
    content.querySelectorAll('[data-deva]').forEach(function (el) {
  function watchTocActive() {
      el.textContent = el.getAttribute('data-deva');
    var toc = document.querySelector( '.vector-toc' );
      el.removeAttribute('data-deva');
    if ( !toc || toc._grObserved ) return;
     });
     toc._grObserved = true;
 
     if ( !window.MutationObserver ) return;
     if (script === 'deva') return;


     // If English but Sanscript not ready, retry after short delay
     function attachHighlight( li ) {
    if (script === 'en' && (!sanscriptReady || !window.Sanscript)) {
       observer.observe( li, { attributes: true, attributeFilter: [ 'class' ] } );
       setTimeout(function () { applyScript('en'); }, 300);
      return;
     }
     }


     var walker = document.createTreeWalker(content, NodeFilter.SHOW_TEXT);
     var observer = new MutationObserver( function ( mutations ) {
    var nodes = [];
      mutations.forEach( function ( m ) {
    while (walker.nextNode()) nodes.push(walker.currentNode);
        // New list items added (lazy render) → attach highlight + tag for transliteration
        if ( m.type === 'childList' ) {
          m.addedNodes.forEach( function ( n ) {
            if ( n.nodeType !== 1 ) return;
            if ( n.classList.contains( 'vector-toc-list-item' ) ) {
              attachHighlight( n );
            }
            n.querySelectorAll && n.querySelectorAll( '.vector-toc-list-item' )
              .forEach( attachHighlight );


    nodes.forEach(function (node) {
            // Tag any newly revealed .vector-toc-text spans for transliteration
      var p = node.parentNode;
            var newTextSpans = [];
      if (!p) return;
            if ( n.classList && n.classList.contains( 'vector-toc-text' ) ) {
      // Skip switcher bar, TOC, and edit links
              newTextSpans.push( n );
      if (p.closest) {
            }
        if (p.closest('.gr-script-bar') ||
            if ( n.querySelectorAll ) {
            p.closest('.vector-toc') ||
              n.querySelectorAll( '.vector-toc-text' ).forEach( function ( s ) {
             p.closest('#toc') ||
                newTextSpans.push( s );
            p.closest('.mw-editsection')) return;
              } );
      }
            }
      var orig = node.textContent;
             newTextSpans.forEach( function ( span ) {
      var trans = transliterateText(orig, script);
              if ( span.hasAttribute( 'data-deva' ) ) return;
      if (trans !== orig) {
              var orig = span.textContent;
        var span = document.createElement('span');
              if ( !orig.trim() ) return;
        span.setAttribute('data-deva', orig);
              span.setAttribute( 'data-deva', orig );
        span.textContent = trans;
              if ( currentScript !== 'deva' ) {
        p.replaceChild(span, node);
                span.textContent = transliterateText( orig, currentScript );
      }
              }
    });
              translatableSpans.push( span );
  }
            } );
          } );
          return;
        }


  // ── 3. Build switcher bar ──────────────────────────────────────
        // Class change → scroll active item into view if needed.
  function buildBar() {
        if ( m.attributeName !== 'class' ) return;
    var title = document.querySelector('.gr-doc-title');
        var li = m.target;
    if (!title) return;
        if ( !li.classList.contains( 'vector-toc-list-item-active' ) ) return;
    if (document.querySelector('.gr-script-bar')) return;
        var container = document.querySelector( '.vector-sticky-pinned-container' );
        if ( !container ) return;
        var liRect  = li.getBoundingClientRect();
        var cRect  = container.getBoundingClientRect();
        var isAbove = liRect.top    < cRect.top    + 8;
        var isBelow = liRect.bottom > cRect.bottom - 8;
        if ( isAbove || isBelow ) {
          li.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
        }
      } );
    } );


     var bar = document.createElement('div');
     // Observe existing list items for class changes
    bar.className = 'gr-script-bar';
    toc.querySelectorAll( '.vector-toc-list-item' ).forEach( attachHighlight );
     bar.innerHTML =
     // Watch for new items (lazy TOC population)
      '<span class="gr-script-label">change script to</span>' +
    observer.observe( toc, { childList: true, subtree: true } );
      '<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);
     // On initial load: scroll to already-active item
    setTimeout( function () {
      var active = toc.querySelector( '.vector-toc-list-item-active' );
      if ( active ) active.scrollIntoView({ block: 'nearest', behavior: 'auto' });
    }, 400 );
  }


     bar.querySelectorAll('.gr-script-btn').forEach(function (btn) {
  // ── Init ──────────────────────────────────────────────────────
      btn.addEventListener('click', function (e) {
  function init() {
        e.preventDefault();
     var content      = document.querySelector( '.mw-parser-output' );
        bar.querySelectorAll('.gr-script-btn').forEach(function (b) {
    var alreadyTagged = content && content.querySelector( '[data-deva]' );
          b.classList.remove('active');
    if ( !alreadyTagged ) {
        });
      translatableSpans = [];
         btn.classList.add('active');
      tagTextNodes();
         applyScript(btn.getAttribute('data-script'));
    } else {
       });
      // Content already tagged — still tag TOC spans if not yet done
     });
      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 );
       } );
     }


  // Run on DOMContentLoaded to ensure bar persists on refresh
    // Apply the globally persisted script preference immediately
  if (document.readyState === 'loading') {
    var saved = ( function () {
    document.addEventListener('DOMContentLoaded', buildBar);
      try { return localStorage.getItem( LS_SCRIPT_KEY ); } catch ( e ) { return null; }
  } else {
    }() );
    buildBar();
    if ( saved && saved !== 'deva' ) {
  }
      applyScript( saved );
    } else {
      currentScript = 'deva';
    }


  // Also hook MW dynamic loads
     watchTocActive();
  if (window.mw) {
     mw.hook('wikipage.content').add(function () {
      setTimeout(buildBar, 150);
    });
   }
   }


   // ── 4. TOC active highlight via MutationObserver ───────────────
   // ── React to toolbar dropdown changes on the same page ─────────
  // Watches class changes on TOC list items so highlight works
   window.addEventListener( 'gr-script-change', function ( e ) {
   // universally on all pages, not just BS.
     var script = e && e.detail && e.detail.script;
  function watchTocActive() {
     if ( script ) applyScript( script );
     var toc = document.querySelector('.vector-toc');
  } );
     if (!toc) return;


     var observer = new MutationObserver(function (mutations) {
  // ── MediaWiki hook (SPA-style navigation support) ───────────────
       mutations.forEach(function (m) {
  if ( window.mw ) {
         if (m.type !== 'attributes' || 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 = '';
           // Tag any untagged TOC spans after navigation
           link.style.fontWeight = '';
          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 );
           } );
        }
        // Re-apply current script to newly loaded content
        if ( currentScript !== 'deva' ) {
          applyScript( currentScript );
         }
         }
       });
        watchTocActive();
     });
       }, 150 );
     } );
  }


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


   if (document.readyState === 'loading') {
}() );
     document.addEventListener('DOMContentLoaded', watchTocActive);
// ── Main page: by-Grantha / by-Author toggle ──────────────────
// Runs only on Main_Page. Attaches click handlers to the two
// <div role="button"> toggles emitted by make_main_page().
// Using delegated event attachment here (not onclick= in wikitext)
// because MediaWiki strips onclick= attributes for security.
( 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; // not on Main_Page
    gBtn.addEventListener( 'click', function () { grHomeView( 'grantha' ); } );
    aBtn.addEventListener( 'click', function () { grHomeView( 'author' );  } );
    // Keyboard support
    [ gBtn, aBtn ].forEach( function ( btn ) {
      btn.addEventListener( 'keydown', function ( e ) {
        if ( e.key === 'Enter' || e.key === ' ' ) btn.click();
      } );
    } );
    // Restore persisted preference
    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 {
   } else {
     watchTocActive();
     initHomeToggle();
   }
   }
 
}() );
})();

Latest revision as of 19:13, 19 April 2026

/* MediaWiki:Common.js — grantha.io
 *
 * Responsibilities:
 *  1. Transliteration engine (Devanāgarī → IAST / Kannada / Tamil).
 *  2. Tag all transliteratable text nodes once per page load.
 *  3. Apply the script stored in localStorage('grantha_reader_script')
 *     so every page opens in the user's preferred script automatically.
 *  4. Listen for the 'gr-script-change' CustomEvent dispatched by the
 *     ReaderToolbar dropdown and re-apply the new script immediately.
 *  5. TOC active-item highlight via MutationObserver (unchanged).
 *
 * The script-switcher bar/buttons previously built here are removed —
 * the ReaderToolbar extension now owns the dropdown UI.
 *
 * localStorage key shared with ReaderToolbar: 'grantha_reader_script'
 */

( 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() {
    // ── Main article content ──────────────────────────────────────
    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 );
      } );
    }

    // ── Sidebar TOC (.vector-toc-text spans) ─────────────────────
    // We target the .vector-toc-text spans that Vector itself renders,
    // rather than walking raw text nodes. Mutating textContent of an
    // existing child span is a characterData mutation — Vector's own
    // MutationObserver only watches for childList changes on the <li>,
    // so it will NOT fire, and the "unknown title" bug is avoided.
    document.querySelectorAll( '.vector-toc .vector-toc-text' ).forEach( function ( span ) {
      if ( span.hasAttribute( 'data-deva' ) ) return; // already tagged
      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; // detached node
      var orig = span.getAttribute( 'data-deva' );
      if ( !orig ) return;
      span.textContent = ( script === 'deva' )
        ? orig
        : transliterateText( orig, script );
    } );
  }

  // ── TOC active-item highlight ───────────────────────────────────
  function watchTocActive() {
    var toc = document.querySelector( '.vector-toc' );
    if ( !toc || toc._grObserved ) return;
    toc._grObserved = true;
    if ( !window.MutationObserver ) return;

    function attachHighlight( li ) {
      observer.observe( li, { attributes: true, attributeFilter: [ 'class' ] } );
    }

    var observer = new MutationObserver( function ( mutations ) {
      mutations.forEach( function ( m ) {
        // New list items added (lazy render) → attach highlight + tag for transliteration
        if ( m.type === 'childList' ) {
          m.addedNodes.forEach( function ( n ) {
            if ( n.nodeType !== 1 ) return;
            if ( n.classList.contains( 'vector-toc-list-item' ) ) {
              attachHighlight( n );
            }
            n.querySelectorAll && n.querySelectorAll( '.vector-toc-list-item' )
              .forEach( attachHighlight );

            // Tag any newly revealed .vector-toc-text spans for transliteration
            var newTextSpans = [];
            if ( n.classList && n.classList.contains( 'vector-toc-text' ) ) {
              newTextSpans.push( n );
            }
            if ( n.querySelectorAll ) {
              n.querySelectorAll( '.vector-toc-text' ).forEach( function ( s ) {
                newTextSpans.push( s );
              } );
            }
            newTextSpans.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 );
            } );
          } );
          return;
        }

        // Class change → scroll active item into view if needed.
        if ( m.attributeName !== 'class' ) return;
        var li = m.target;
        if ( !li.classList.contains( 'vector-toc-list-item-active' ) ) return;
        var container = document.querySelector( '.vector-sticky-pinned-container' );
        if ( !container ) return;
        var liRect  = li.getBoundingClientRect();
        var cRect   = container.getBoundingClientRect();
        var isAbove = liRect.top    < cRect.top    + 8;
        var isBelow = liRect.bottom > cRect.bottom - 8;
        if ( isAbove || isBelow ) {
          li.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
        }
      } );
    } );

    // Observe existing list items for class changes
    toc.querySelectorAll( '.vector-toc-list-item' ).forEach( attachHighlight );
    // Watch for new items (lazy TOC population)
    observer.observe( toc, { childList: true, subtree: true } );

    // On initial load: scroll to already-active item
    setTimeout( function () {
      var active = toc.querySelector( '.vector-toc-list-item-active' );
      if ( active ) active.scrollIntoView({ block: 'nearest', behavior: 'auto' });
    }, 400 );
  }

  // ── Init ──────────────────────────────────────────────────────
  function init() {
    var content       = document.querySelector( '.mw-parser-output' );
    var alreadyTagged = content && content.querySelector( '[data-deva]' );
    if ( !alreadyTagged ) {
      translatableSpans = [];
      tagTextNodes();
    } else {
      // Content already tagged — still tag TOC spans if not yet done
      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 );
      } );
    }

    // Apply the globally persisted script preference immediately
    var saved = ( function () {
      try { return localStorage.getItem( LS_SCRIPT_KEY ); } catch ( e ) { return null; }
    }() );
    if ( saved && saved !== 'deva' ) {
      applyScript( saved );
    } else {
      currentScript = 'deva';
    }

    watchTocActive();
  }

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

  // ── MediaWiki hook (SPA-style navigation support) ───────────────
  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 {
          // Tag any untagged TOC spans after navigation
          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 );
          } );
        }
        // Re-apply current script to newly loaded content
        if ( currentScript !== 'deva' ) {
          applyScript( currentScript );
        }
        watchTocActive();
      }, 150 );
    } );
  }

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

}() );
// ── Main page: by-Grantha / by-Author toggle ──────────────────
// Runs only on Main_Page. Attaches click handlers to the two
// <div role="button"> toggles emitted by make_main_page().
// Using delegated event attachment here (not onclick= in wikitext)
// because MediaWiki strips onclick= attributes for security.
( 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; // not on Main_Page
 
    gBtn.addEventListener( 'click', function () { grHomeView( 'grantha' ); } );
    aBtn.addEventListener( 'click', function () { grHomeView( 'author' );  } );
    // Keyboard support
    [ gBtn, aBtn ].forEach( function ( btn ) {
      btn.addEventListener( 'keydown', function ( e ) {
        if ( e.key === 'Enter' || e.key === ' ' ) btn.click();
      } );
    } );
 
    // Restore persisted preference
    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();
  }
}() );