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:
// ── Load Sanscript.js first, then init everything ────────────────
/* MediaWiki:Common.js — grantha.io
(function() {
*
* 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 loadScript(url, callback) {
( function () {
     var s = document.createElement('script');
 
     s.src = url;
  var LS_SCRIPT_KEY = 'grantha_reader_script';
     s.onload = callback;
  var currentScript = 'deva';
    document.head.appendChild(s);
 
  // ── 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;
   }
   }


  loadScript(
   // ── Character maps for Kannada / Tamil ─────────────────────────
    'https://cdn.jsdelivr.net/npm/sanscript.js@1.1.2/sanscript.min.js',
    function() { initScriptSwitcher(); }
  );
 
   // ── Character maps for Kannada and Tamil ─────────────────────
   var SCRIPT_MAP = {
   var SCRIPT_MAP = {
     kn: {
     kn: {
Line 34: Line 86:
     ta: {
     ta: {
       'अ':'அ','आ':'ஆ','इ':'இ','ई':'ஈ','उ':'உ','ऊ':'ஊ',
       'अ':'அ','आ':'ஆ','इ':'இ','ई':'ஈ','उ':'உ','ऊ':'ஊ',
      'ऋ':'ரு','ॠ':'ரூ',
       'ए':'ஏ','ऐ':'ஐ','ओ':'ஓ','औ':'ஔ',
       'ए':'ஏ','ऐ':'ஐ','ओ':'ஓ','औ':'ஔ',
       'क':'க','ख':'க','ग':'க','घ':'க','ङ':'ங',
       'क':'க','ख':'க','ग':'க','घ':'க','ङ':'ங',
Line 40: Line 93:
       'त':'த','थ':'த','द':'த','ध':'த','न':'ந',
       'त':'த','थ':'த','द':'த','ध':'த','न':'ந',
       'प':'ப','फ':'ப','ब':'ப','भ':'ப','म':'ம',
       'प':'ப','फ':'ப','ब':'ப','भ':'ப','म':'ம',
       'य':'ய','र':'ர','ल':'ல','व':'வ',
       'य':'ய','र':'ர','ल':'ல','ळ':'ழ','व':'வ',
       'श':'ஶ','ष':'ஷ','स':'ஸ','ह':'ஹ',
       'श':'ஶ','ष':'ஷ','स':'ஸ','ह':'ஹ',
       'ा':'ா','ि':'ி','ी':'ீ','ु':'ு','ू':'ூ',
       'ा':'ா','ि':'ி','ी':'ீ','ु':'ு','ू':'ூ',
      'ृ':'ு','ॄ':'ூ',
       'े':'ே','ै':'ை','ो':'ோ','ौ':'ௌ',
       'े':'ே','ै':'ை','ो':'ோ','ौ':'ௌ',
       'ं':'ம்','ः':':','्':'்','ॐ':'ௐ',
       'ं':'ம்','ः':':','ँ':'ம்','्':'்','ॐ':'ௐ','ऽ':'ௗ',
       '०':'0','१':'1','२':'2','३':'3','४':'4',
       '०':'0','१':'1','२':'2','३':'3','४':'4',
       '५':'5','६':'6','७':'7','८':'8','९':'9'
       '५':'5','६':'6','७':'7','८':'8','९':'9'
Line 50: Line 104:
   };
   };


   var PRE_PROCESS = [
   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(text) {
   function transliterateText( text, script ) {
     PRE_PROCESS.forEach(function(pair) {
     if ( script === 'en' ) return devanagariToIAST( text );
      text = text.replace(pair[0], pair[1]);
    var map = SCRIPT_MAP[ script ];
     });
    if ( !map ) return text;
     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 = [];
      return Sanscript.t(text, 'devanagari', 'iast');
 
   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 );
      } );
     }
     }
     var map = SCRIPT_MAP[script];
 
    if (!map) return text;
    // ── Sidebar TOC (.vector-toc-text spans) ─────────────────────
    var processed = preProcess(text);
    // We target the .vector-toc-text spans that Vector itself renders,
     return Array.from(processed).map(function(ch) {
     // rather than walking raw text nodes. Mutating textContent of an
       return map[ch] !== undefined ? map[ch] : ch;
    // existing child span is a characterData mutation — Vector's own
     }).join('');
    // 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 );
     } );
   }
   }


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


     // Restore original devanagari
     function attachHighlight( li ) {
    content.querySelectorAll('[data-deva]').forEach(function(el) {
       observer.observe( li, { attributes: true, attributeFilter: [ 'class' ] } );
       el.textContent = el.getAttribute('data-deva');
     }
      el.removeAttribute('data-deva');
     });


     if (script === 'deva') return;
     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 );


    var walker = document.createTreeWalker(content, NodeFilter.SHOW_TEXT);
            // Tag any newly revealed .vector-toc-text spans for transliteration
    var nodes = [];
            var newTextSpans = [];
    while (walker.nextNode()) nodes.push(walker.currentNode);
            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;
        }


    nodes.forEach(function(node) {
        // Class change → scroll active item into view if needed.
      var orig = node.textContent;
        if ( m.attributeName !== 'class' ) return;
      var trans = transliterateText(orig, script);
        var li = m.target;
      if (trans !== orig) {
        if ( !li.classList.contains( 'vector-toc-list-item-active' ) ) return;
         var span = document.createElement('span');
        var container = document.querySelector( '.vector-sticky-pinned-container' );
         span.setAttribute('data-deva', orig);
        if ( !container ) return;
        span.textContent = trans;
        var liRect  = li.getBoundingClientRect();
        node.parentNode.replaceChild(span, node);
        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 );
   }
   }


   function initScriptSwitcher() {
  // ── Init ──────────────────────────────────────────────────────
     mw.hook('wikipage.content').add(function() {
   function init() {
       // Only add on doc pages (pages with gr-doc-title)
     var content      = document.querySelector( '.mw-parser-output' );
      var title = document.querySelector('.gr-doc-title');
    var alreadyTagged = content && content.querySelector( '[data-deva]' );
       if (!title) return;
    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';
    }


      var bar = document.createElement('div');
    watchTocActive();
      bar.className = 'gr-script-bar';
  }
      bar.innerHTML =
        '<span class="gr-script-label">change script to</span>' +
        '<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);
  // ── 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 );
    } );
  }


      bar.querySelectorAll('.gr-script-btn').forEach(function(btn) {
  // ── Fallback for non-MW environments ───────────────────────────
        btn.addEventListener('click', function(e) {
  if ( document.readyState === 'loading' ) {
          e.preventDefault();
    document.addEventListener( 'DOMContentLoaded', init );
          bar.querySelectorAll('.gr-script-btn').forEach(function(b) {
  } else {
            b.classList.remove('active');
    init();
          });
          btn.classList.add('active');
          applyScript(btn.getAttribute('data-script'));
        });
      });
    });
   }
   }


})();
}() );

Latest revision as of 07:16, 17 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();
  }

}() );