Jump to content

MediaWiki:Common.js: Difference between revisions

From Anandamakaranda
No edit summary
No edit summary
Line 337: Line 337:
       var link = li.querySelector( '.vector-toc-link' ) || li.querySelector( 'a' );
       var link = li.querySelector( '.vector-toc-link' ) || li.querySelector( 'a' );
       if ( !link ) return;
       if ( !link ) return;
       if ( on ) {
       /* Only highlight as "active" if this is the LEAF active item —
      * i.e. no child list-item is also active. Vector marks both the
      * parent section AND the current sub-item as active. We only want
      * the innermost active item coloured orange. */
      var hasActiveChild = !!li.querySelector(
        '.vector-toc-list-item .vector-toc-list-item-active'
      );
      var shouldHighlight = on && !hasActiveChild;
      if ( shouldHighlight ) {
         link.style.setProperty( 'color',      ACTIVE_COLOR, 'important' );
         link.style.setProperty( 'color',      ACTIVE_COLOR, 'important' );
         link.style.setProperty( 'font-weight', '700',        'important' );
         link.style.setProperty( 'font-weight', '700',        'important' );

Revision as of 04:09, 29 April 2026

/* MediaWiki:Common.js — grantha.io  (v7)
 *
 * Changes vs v6:
 *  1. BUG FIX: Main IIFE was never properly closed — About link block was
 *     pasted inside it without the closing }() ); which broke the module
 *     boundary and killed the by-Author toggle. Each block is now its
 *     own self-contained IIFE.
 *  2. TOC: "Beginning" link removed.
 *  3. TOC: Heading label → "विषयसूची".
 *  4. TOC: मूल / उल्लेख nav links injected at top of TOC panel.
 *  5. TOC: All subsections expanded by default.
 *  6. TOC: Only the active item is bold; all others are normal weight.
 *  7. About link URL derived from wgArticlePath — works under any
 *     sub-path install (e.g. /My_wiki/). Points to "My_wiki:About".
 *  8. TOC customisations skipped on Main_Page and About pages.
 */

( 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' )    ) return;
          if ( p.closest( '.mw-editsection' ) ) return;
          if ( p.closest( '#gr-toc-doc-nav' ) ) 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 );
      } );
    }

    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 );
    } );
  }

  // ── Pages where sidebar TOC should not be modified ──────────────
  function _isNoTocPage() {
    var pn = ( window.mw && mw.config && mw.config.get( 'wgPageName' ) ) || '';
    return pn === 'Main_Page' || /^[A-Za-z0-9_]+:About$/.test( pn );
  }

  // ── TOC: rename "Contents" → "विषयसूची" ────────────────────────
  function renameTocTitle() {
    if ( _isNoTocPage() ) return;
    var toc = document.querySelector( '.vector-toc' );
    if ( !toc ) return;
    var titleEl = toc.querySelector( '.vector-toc-title' );
    if ( !titleEl ) return;
    var replaced = false;
    titleEl.childNodes.forEach( function ( n ) {
      if ( n.nodeType === 3 && n.textContent.trim() ) {
        n.textContent = 'विषयसूची';
        replaced = true;
      }
    } );
    if ( !replaced && titleEl.childElementCount === 0 ) {
      titleEl.textContent = 'विषयसूची';
    }
  }

  // ── TOC: Remove the "Beginning" / top-of-page link ─────────────
  function removeTocBeginning() {
    if ( _isNoTocPage() ) return;
    var toc = document.querySelector( '.vector-toc' );
    if ( !toc ) return;
    var el = toc.querySelector( '#vector-toc-beginning' );
    if ( !el ) {
      var items = toc.querySelectorAll( '.vector-toc-list-item' );
      for ( var i = 0; i < items.length; i++ ) {
        var a = items[ i ].querySelector( 'a' );
        if ( a && a.href.indexOf( '#' ) === -1 ) { el = items[ i ]; break; }
      }
    }
    if ( el && el.parentNode ) el.parentNode.removeChild( el );
  }

  // ── TOC: Expand all collapsed subsections on load ───────────────
  function expandTocSections() {
    if ( _isNoTocPage() ) return;
    var toc = document.querySelector( '.vector-toc' );
    if ( !toc ) return;
    toc.querySelectorAll( '.vector-toc-list-item-collapsed' ).forEach( function ( li ) {
      li.classList.remove( 'vector-toc-list-item-collapsed' );
    } );
  }

  // ── TOC: Inject मूल / उल्लेख nav links ─────────────────────────
  function injectTocDocNav() {
    if ( _isNoTocPage() ) return;
    var toc = document.querySelector( '.vector-toc' );
    if ( !toc ) return;
    if ( document.getElementById( 'gr-toc-doc-nav' ) ) return;

    var artPath   = ( window.mw && mw.config && mw.config.get( 'wgArticlePath' ) ) || '/wiki/$1';
    var pageTitle = ( window.mw && mw.config && mw.config.get( 'wgPageName'   ) ) || '';

    var teekaPage   = document.querySelector( '.gr-teeka-page' );
    var primarySlug = teekaPage ? ( teekaPage.getAttribute( 'data-primary' ) || '' ) : '';
    var docSlug     = teekaPage ? ( teekaPage.getAttribute( 'data-slug'    ) || '' ) : '';

    if ( !primarySlug ) {
      primarySlug = pageTitle.split( '/' )[ 0 ];
      docSlug     = primarySlug;
    }
    if ( !primarySlug ) return;

    function wikiUrl( slug ) {
      if ( window.mw && mw.util && mw.util.getUrl ) return mw.util.getUrl( slug );
      return artPath.replace( '$1', encodeURIComponent( slug ).replace( /%2F/g, '/' ) );
    }

    var moolaUrl   = wikiUrl( primarySlug );
    var ullekhaUrl = wikiUrl( primarySlug + '/Ullekha' );

    /* ── Button visibility rules ────────────────────────────────────────
     *
     * Three separate concepts share the label "मूल" depending on page type:
     *
     *  1. On a BHASHYA page (e.g. Bhagavadgitabhashya):
     *       मूलम् → /Moola  (verse-text-only filtered view of the same doc)
     *       Shown when the importer set data-has-moola on .gr-doc-title.
     *
     *  2. On a TEEKA page (e.g. Nyayasudha):
     *       मूल   → the primary bhashya this teeka comments on (Anuvyakhyana)
     *       Always shown on teeka pages (teekaPage div is present).
     *
     *  उल्लेख:
     *       Shown on bhashya pages when data-has-ullekha is set, or on
     *       teeka pages (links to primary bhashya's Ullekha page).
     * ──────────────────────────────────────────────────────────────── */
    var docTitleEl  = document.querySelector( '.gr-doc-title' );
    var hasMoolaPage   = docTitleEl && docTitleEl.getAttribute( 'data-has-moola' )   === '1';
    var hasUllekhaPage = docTitleEl && docTitleEl.getAttribute( 'data-has-ullekha' ) === '1';

    /* On a bhashya page, मूलम् links to the /Moola sub-page */
    var moolaPageUrl = wikiUrl( primarySlug + '/Moola' );

    /* On a teeka page, मूल links to the primary bhashya (already in moolaUrl) */
    var showMoolaPage  = !teekaPage && hasMoolaPage;   /* bhashya → /Moola */
    var showMoolaBack  = !!teekaPage;                   /* teeka  → primary bhashya */
    var showUllekha    = hasUllekhaPage || !!teekaPage;

    if ( !showMoolaPage && !showMoolaBack && !showUllekha ) return;

    var nav = document.createElement( 'div' );
    nav.id = 'gr-toc-doc-nav';
    nav.setAttribute( 'style', [
      'display:flex', 'gap:6px', 'padding:5px 8px 6px',
      'border-bottom:1px solid var(--border-color-base,#dcc9a8)',
      'margin-bottom:4px', 'flex-wrap:wrap',
    ].join( ';' ) );

    var base = [
      'display:inline-block', 'padding:2px 9px', 'border-radius:3px',
      'font-size:0.80em', 'font-weight:500', 'text-decoration:none',
      'border:1px solid currentColor', 'line-height:1.65',
      'white-space:nowrap', 'font-family:inherit',
    ].join( ';' );

    function makeBtn( href, label, color, bg ) {
      var a = document.createElement( 'a' );
      a.href = href;
      a.textContent = label;
      a.setAttribute( 'style', base + ';color:' + color + ';background:' + bg + ';' );
      a.addEventListener( 'mouseover', function () { this.style.opacity = '0.72'; } );
      a.addEventListener( 'mouseout',  function () { this.style.opacity = '1';    } );
      return a;
    }

    /* Bhashya page: show मूलम् (→ /Moola filtered view) */
    if ( showMoolaPage ) nav.appendChild( makeBtn( moolaPageUrl, 'मूलम्',  '#b04b00', '#fff3e0' ) );
    /* Teeka page: show मूल (→ primary bhashya) */
    if ( showMoolaBack ) nav.appendChild( makeBtn( moolaUrl,     'मूल',    '#b04b00', '#fff3e0' ) );
    /* Either page type: show उल्लेख when available */
    if ( showUllekha   ) nav.appendChild( makeBtn( ullekhaUrl,   'उल्लेख', '#1a5f8a', '#e8f4fc' ) );

    var tocContents = toc.querySelector( '.vector-toc-contents' );
    if ( tocContents ) toc.insertBefore( nav, tocContents );
    else               toc.appendChild( nav );
  }

  // ── TOC active-item highlight ────────────────────────────────────
  // v7: inactive items get font-weight:400 explicitly — only active gets 700.
  function watchTocActive() {
    if ( _isNoTocPage() ) return;
    var toc = document.querySelector( '.vector-toc' );
    if ( !toc ) return;
    if ( !window.MutationObserver ) return;

    if ( toc._grObserved ) {
      toc.querySelectorAll( '.vector-toc-list-item' ).forEach( attachHighlight );
      return;
    }
    toc._grObserved = true;

    var ACTIVE_COLOR = '#f57c00';

    function setActive( li, on ) {
      var link = li.querySelector( '.vector-toc-link' ) || li.querySelector( 'a' );
      if ( !link ) return;
      /* Only highlight as "active" if this is the LEAF active item —
       * i.e. no child list-item is also active. Vector marks both the
       * parent section AND the current sub-item as active. We only want
       * the innermost active item coloured orange. */
      var hasActiveChild = !!li.querySelector(
        '.vector-toc-list-item .vector-toc-list-item-active'
      );
      var shouldHighlight = on && !hasActiveChild;
      if ( shouldHighlight ) {
        link.style.setProperty( 'color',       ACTIVE_COLOR, 'important' );
        link.style.setProperty( 'font-weight', '700',        'important' );
        link.querySelectorAll( '*' ).forEach( function ( el ) {
          el.style.setProperty( 'color',       ACTIVE_COLOR, 'important' );
          el.style.setProperty( 'font-weight', '700',        'important' );
        } );
      } else {
        link.style.removeProperty( 'color' );
        link.style.setProperty( 'font-weight', '400', 'important' );
        link.querySelectorAll( '*' ).forEach( function ( el ) {
          el.style.removeProperty( 'color' );
          el.style.setProperty( 'font-weight', '400', 'important' );
        } );
      }
    }

    function normaliseAll() {
      toc.querySelectorAll( '.vector-toc-list-item' ).forEach( function ( li ) {
        setActive( li, li.classList.contains( 'vector-toc-list-item-active' ) );
      } );
    }

    function attachHighlight( li ) {
      if ( li._grHighlightAttached ) return;
      li._grHighlightAttached = true;
      liObs.observe( li, { attributes: true, attributeFilter: [ 'class' ] } );
      setActive( li, li.classList.contains( 'vector-toc-list-item-active' ) );
    }

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

        if ( active ) {
          // Expand collapsed ancestor sections
          var anc = li.parentNode;
          while ( anc && anc !== document.body ) {
            if ( anc.classList &&
                 anc.classList.contains( 'vector-toc-list-item' ) &&
                 anc.classList.contains( 'vector-toc-list-item-collapsed' ) ) {
              anc.classList.remove( 'vector-toc-list-item-collapsed' );
            }
            anc = anc.parentNode;
          }

          // Scroll active item into visible TOC area
          var container = document.querySelector( '.vector-sticky-pinned-container' );
          if ( container ) {
            var vis = container.offsetHeight > 0 &&
                      container.offsetParent !== null &&
                      window.getComputedStyle( container ).display !== 'none' &&
                      window.getComputedStyle( container ).visibility !== 'hidden';
            if ( vis ) {
              var lr = li.getBoundingClientRect();
              var cr = container.getBoundingClientRect();
              if ( lr.top < cr.top + 4 || lr.bottom > cr.bottom - 4 ) {
                var sh = null, node = li.parentNode;
                while ( node && node !== document.body ) {
                  var ov = window.getComputedStyle( node ).overflowY;
                  if ( ( ov === 'auto' || ov === 'scroll' ) &&
                       node.scrollHeight > node.clientHeight ) { sh = node; break; }
                  node = node.parentNode;
                }
                if ( !sh && container.scrollHeight > container.clientHeight ) sh = container;
                if ( sh ) {
                  var hr  = sh.getBoundingClientRect();
                  var top = lr.top - hr.top + sh.scrollTop;
                  sh.scrollTop = Math.max( 0, top - sh.clientHeight / 2 + li.offsetHeight / 2 );
                }
              }
            }
          }
        }
      } );
    } );

    var structObs = new MutationObserver( function ( mutations ) {
      mutations.forEach( function ( m ) {
        if ( m.type !== 'childList' ) return;
        m.addedNodes.forEach( function ( n ) {
          if ( n.nodeType !== 1 ) return;
          if ( n.classList && n.classList.contains( 'vector-toc-list-item' ) ) attachHighlight( n );
          if ( n.querySelectorAll ) n.querySelectorAll( '.vector-toc-list-item' ).forEach( attachHighlight );
          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 );
    structObs.observe( toc, { childList: true, subtree: true } );

    setTimeout( function () {
      normaliseAll();
      var active = toc.querySelector( '.vector-toc-list-item-active' );
      if ( active ) setActive( active, true );
    }, 300 );
  }

  // ── Run all TOC customisations ───────────────────────────────────
  function setupToc() {
    removeTocBeginning();
    renameTocTitle();
    expandTocSections();
    injectTocDocNav();
    watchTocActive();
  }

  // ── Init ────────────────────────────────────────────────────────
  function init() {
    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 );
      } );
      var pt = document.getElementById( 'vector-page-tools' ) ||
               document.querySelector( '.vector-page-tools-pinned-container' );
      if ( pt ) {
        pt.querySelectorAll( '[aria-controls="vector-appearance"]' )
          .forEach( function ( el ) { if ( el.parentNode ) el.parentNode.removeChild( el ); } );
      }
    }
    removeHiddenEls();

    ( function detectTeekaMode() {
      var tp = document.querySelector( '.gr-teeka-page' );
      if ( !tp ) return;
      var primary = tp.getAttribute( 'data-primary' ) || '';
      var artPath = ( window.mw && mw.config.get( 'wgArticlePath' ) ) || '/wiki/$1';
      var mainUrl = artPath.replace( '$1', primary );
      var refParam = window.location.search.match( /[?&]ref=([01])/ );
      if ( refParam ) {
        document.body.classList.add( refParam[1] === '1' ? 'gr-ref-mode' : 'gr-standalone' );
        return;
      }
      var ref = document.referrer || '';
      document.body.classList.add(
        ( ref && primary && ref.indexOf( mainUrl ) !== -1 ) ? 'gr-ref-mode' : 'gr-standalone'
      );
    }() );

    if ( window.MutationObserver ) {
      var hideObs = new MutationObserver( function ( mutations ) {
        var dirty = false;
        mutations.forEach( function ( m ) { if ( m.addedNodes.length ) dirty = true; } );
        if ( dirty ) removeHiddenEls();
      } );
      hideObs.observe( document.body, { childList: true, subtree: false } );
      setTimeout( function () { hideObs.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'; }

    // Vector 2022 defers TOC render — retry at 300ms and 800ms
    setupToc();
    setTimeout( setupToc, 300 );
    setTimeout( setupToc, 800 );
  }

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

  // ── MediaWiki 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 );
        setupToc();
      }, 150 );
    } );
  }

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

}() );   /* ← end of main IIFE */


// ── Inject "About" link into the header ────────────────────────────
// Separate IIFE — v6 had this nested inside the main IIFE without a
// closing }() ); which broke the module boundary and killed the
// by-Author toggle on the main page.
( function () {
  function injectAboutLink() {
    if ( document.getElementById( 'gr-about-link' ) ) return;

    var headerEnd = document.querySelector( '.vector-header-end' ) ||
                    document.querySelector( '#vector-user-links' ) ||
                    document.querySelector( '.mw-header' );
    if ( !headerEnd ) return;

    // mw.util.getUrl() uses wgArticlePath internally, so it always produces
    // the correct URL regardless of whether the wiki is at / or /My_wiki/.
    var href;
    if ( window.mw && mw.util && mw.util.getUrl ) {
      href = mw.util.getUrl( 'My_wiki:About' );
    } else {
      var ap = ( window.mw && mw.config && mw.config.get( 'wgArticlePath' ) ) || '/wiki/$1';
      href = ap.replace( '$1', 'My_wiki:About' );
    }

    var a = document.createElement( 'a' );
    a.id  = 'gr-about-link';
    a.href = href;
    a.textContent = 'About';
    a.style.cssText = [
      'color:rgba(255,255,255,0.88)', 'font-size:0.88em',
      'font-family:system-ui,sans-serif', 'font-weight:500',
      'text-decoration:none', 'padding:4px 10px', 'border-radius:4px',
      'margin-right:6px', 'transition:color 0.15s,background 0.15s',
      'white-space:nowrap',
    ].join( ';' );
    a.addEventListener( 'mouseover', function () {
      this.style.color = '#fff';
      this.style.background = 'rgba(255,255,255,0.12)';
    } );
    a.addEventListener( 'mouseout', function () {
      this.style.color = 'rgba(255,255,255,0.88)';
      this.style.background = 'transparent';
    } );

    var ul = document.querySelector( '.vector-user-links' ) ||
             document.querySelector( '#pt-userpage' );
    if ( ul && ul.parentNode === headerEnd ) headerEnd.insertBefore( a, ul );
    else headerEnd.appendChild( a );
  }

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


// ── 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();
}() );


// ── Ullekha reference link handler ─────────────────────────────────
// Two behaviours:
//   A) On the Ullekha page: clicking a .gr-ullekha-ref-link opens the
//      bhashya page at the anchor with a ?hlUllekha= param that triggers
//      highlight on arrival. Opens in the same tab (wiki navigation).
//   B) On the bhashya page: if URL has ?hlUllekha=<text>, find that text
//      in the page, scroll to it, and highlight it with a yellow background.
( function () {

  // ── B) Bhashya page — highlight on arrival ──────────────────────
  function highlightOnArrival() {
    var search = window.location.search;
    if ( !search ) return;
    var m = search.match( /[?&]hlUllekha=([^&]+)/ );
    if ( !m ) return;
    var needle;
    try { needle = decodeURIComponent( m[ 1 ] ); } catch ( e ) { return; }
    if ( !needle || needle.length < 4 ) return;

    var content = document.querySelector( '.mw-parser-output' );
    if ( !content ) return;

    /* Walk all text nodes and find the first occurrence of needle.
     * We search in the textContent of every leaf element. */
    var walker = document.createTreeWalker( content, NodeFilter.SHOW_TEXT );
    var found = false;
    while ( walker.nextNode() && !found ) {
      var node = walker.currentNode;
      var txt  = node.textContent || '';
      /* partial match — needle may span multiple text nodes,
         so check for the first 30 chars */
      var snippet = needle.slice( 0, 30 );
      if ( txt.indexOf( snippet ) !== -1 ) {
        var span = document.createElement( 'mark' );
        span.className = 'gr-ullekha-highlight';
        span.style.cssText = 'background:#fff176;border-radius:2px;padding:0 2px;';
        var parent = node.parentNode;
        /* Wrap the matching portion */
        var idx = txt.indexOf( snippet );
        if ( idx >= 0 ) {
          var before = document.createTextNode( txt.slice( 0, idx ) );
          var after  = document.createTextNode( txt.slice( idx + snippet.length ) );
          span.textContent = txt.slice( idx, idx + needle.length > txt.length
            ? txt.length : needle.length );
          parent.insertBefore( before, node );
          parent.insertBefore( span,   node );
          parent.insertBefore( after,  node );
          parent.removeChild( node );
          /* Scroll into view */
          setTimeout( function () {
            span.scrollIntoView( { behavior: 'smooth', block: 'center' } );
          }, 300 );
          found = true;
        }
      }
    }
  }

  // ── A) Ullekha page — make ref links navigate with hlUllekha param ──
  function wireUllekhaLinks() {
    document.querySelectorAll( '.gr-ullekha-ref-link' ).forEach( function ( wrap ) {
      var anchor = wrap.getAttribute( 'data-anchor' ) || '';
      var hl     = wrap.getAttribute( 'data-hl' )     || '';
      var a = wrap.querySelector( 'a' );
      if ( !a ) return;

      /* Rebuild the href to include ?hlUllekha= */
      var base = a.href.split( '#' )[ 0 ];
      var encoded = encodeURIComponent( hl );
      a.href = base + ( hl ? '?hlUllekha=' + encoded : '' )
                    + ( anchor ? '#' + anchor : '' );
    } );
  }

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