Jump to content

MediaWiki:Common.js: Difference between revisions

From Anandamakaranda
No edit summary
No edit summary
Line 2: Line 2:
  *
  *
  * Changes vs v6:
  * Changes vs v6:
  *  1. BUG FIX: The main IIFE was never properly closed in v6 the "About"
  *  1. BUG FIX: Main IIFE was never properly closed — About link block was
  *    link injection block was pasted inside it without the closing }() );
  *    pasted inside it without closing }() ); which broke the module
  *    This broke the JS module boundary and caused the by-Author toggle on
  *    boundary and killed the by-Author toggle. Each block is now its
*    the main page to fail (the grHomeView IIFE ran in a corrupted scope).
  *    own self-contained IIFE.
  *    Fix: About link injection is now its own self-contained IIFE, cleanly
  * 2. TOC: "Beginning" link removed.
  *     separated from the transliteration/TOC IIFE.
  *  3. TOC: Heading label changed from "Contents" → "विषयसूची".
  *  2. TOC: Remove the auto-generated "Beginning" link (Vector 2022 always
  * 4. TOC: मूल / उल्लेख nav links injected at top of TOC panel.
  *     inserts a first TOC entry that links to the page top; on Sanskrit
  * 5. TOC: All subsections expanded by default on load.
  *     content pages this is unnecessary and clutters the TOC).
  *  6. TOC: Only the active item is bold; all others reset to normal weight.
  *  3. TOC: Add "मूल" (Moola) and "उल्लेख" (Ullekha) nav links below the
  * 7. About link: URL now derived from wgArticlePath so it works under
  *     document title area — Moola links back to the primary bhashya page
  *    any sub-path (e.g. /My_wiki/). Points to "My_wiki:About".
  *    (on teeka/vyakhya pages), Ullekha links to the references index page
  * 8. TOC customisations skipped on Main_Page and About pages (no sidebar
  *     for the document. Both use the existing data-primary / doc-slug
  *    TOC on those pages — consistent with __NOTOC__ treatment).
  *    attributes already present in the page HTML.
*  4. All other behaviour identical to v6.
  */
  */


Line 93: Line 91:
       'क':'க','ख':'க','ग':'க','घ':'க','ङ':'ங',
       'क':'க','ख':'க','ग':'க','घ':'க','ङ':'ங',
       'च':'ச','छ':'ச','ज':'ஜ','झ':'ஜ','ञ':'ஞ',
       'च':'ச','छ':'ச','ज':'ஜ','झ':'ஜ','ञ':'ஞ',
       '':'ட','ठ':'ட','ड':'ட','ढ':'ட','ண':'ண',
       '':'ட','ठ':'ட','ड':'ட','ढ':'ட','ண':'ண',
       'त':'த','थ':'த','द':'த','ध':'த','न':'ந',
       'त':'த','थ':'த','द':'த','ध':'த','न':'ந',
       'प':'ப','फ':'ப','ब':'ப','भ':'ப','म':'ம',
       'प':'ப','फ':'ப','ब':'ப','भ':'ப','म':'ம',
       'य':'ய','र':'ர','':'ல','ळ':'ழ','व':'வ',
       'य':'ய','र':'ர','':'ல','ळ':'ழ','व':'வ',
       'श':'ஶ','ष':'ஷ','स':'ஸ','ह':'ஹ',
       'श':'ஶ','ष':'ஷ','स':'ஸ','ह':'ஹ',
       'ा':'ா','ि':'ி','ी':'ீ','ु':'ு','ू':'ூ',
       'ा':'ா','ि':'ி','ी':'ீ','ु':'ு','ू':'ூ',
       'ृ':'ு','ॄ':'ூ',
       'ृ':'ு','ॄ':'ூ',
       'े':'ே','':'ை','ो':'ோ','ौ':'ௌ',
       'े':'ே','':'ை','ो':'ோ','ौ':'ௌ',
       'ं':'ம்','ः':':','ँ':'ம்','्':'்','ॐ':'ௐ','ऽ':'ௗ',
       'ं':'ம்','ः':':','ँ':'ம்','्':'்','ॐ':'ௐ','ऽ':'ௗ',
       '०':'0','१':'1','२':'2','३':'3','४':'4',
       '०':'0','१':'1','२':'2','३':'3','४':'4',
Line 139: Line 137:
         if ( p.hasAttribute && p.hasAttribute( 'data-deva' ) ) return;
         if ( p.hasAttribute && p.hasAttribute( 'data-deva' ) ) return;
         if ( p.closest ) {
         if ( p.closest ) {
           if ( p.closest( '.gr-controls' ) || p.closest( '.mw-editsection' ) ) return;
           if ( p.closest( '.gr-controls' )   ) return;
          if ( p.closest( '.mw-editsection' ) ) return;
          if ( p.closest( '#gr-toc-doc-nav' ) ) return;  /* don't wrap nav buttons */
         }
         }
         var orig = node.textContent;
         var orig = node.textContent;
Line 174: Line 174:
   }
   }


   // ── TOC: Remove "Beginning" link ────────────────────────────────
   // ── Pages where the sidebar TOC is absent / should be left alone ─
   // Vector 2022 always inserts a first TOC item linking to the page top
   // Main_Page uses __NOTOC__; About pages are similar full-page views.
   // (labelled "Beginning" in English UI). On Sanskrit content pages this
   function _isNoTocPage() {
   // is redundant — remove it so the TOC starts at the first real heading.
    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;
    /* Replace direct text nodes only — preserves the toggle button sibling */
    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 auto-generated "Beginning" / top-of-page link ─
   function removeTocBeginning() {
   function removeTocBeginning() {
    if ( _isNoTocPage() ) return;
     var toc = document.querySelector( '.vector-toc' );
     var toc = document.querySelector( '.vector-toc' );
     if ( !toc ) return;
     if ( !toc ) return;
    /* The "Beginning" entry lives in a <li> that either:
     var el = toc.querySelector( '#vector-toc-beginning' );
    *  (a) has class vector-toc-list-item AND contains an <a> whose href
     if ( !el ) {
    *      ends in the page title with no fragment (i.e. no "#" anchor), or
       /* Fallback: first <li> whose anchor has no "#" fragment */
    *  (b) is the very first <li> inside .vector-toc-contents whose link
    *      has no hash fragment at all (it scrolls to the very top).
    * We target it by its unique id (#vector-toc-beginning) which Vector
    * 2022 reliably sets, with a fallback to the first fragment-free item.
    */
     var beginning = toc.querySelector( '#vector-toc-beginning' );
     if ( !beginning ) {
       /* Fallback: first <li> whose anchor has no "#" in href */
       var items = toc.querySelectorAll( '.vector-toc-list-item' );
       var items = toc.querySelectorAll( '.vector-toc-list-item' );
       for ( var i = 0; i < items.length; i++ ) {
       for ( var i = 0; i < items.length; i++ ) {
         var a = items[ i ].querySelector( 'a' );
         var a = items[ i ].querySelector( 'a' );
         if ( a && a.href.indexOf( '#' ) === -1 ) {
         if ( a && a.href.indexOf( '#' ) === -1 ) { el = items[ i ]; break; }
          beginning = items[ i ];
          break;
        }
       }
       }
     }
     }
     if ( beginning && beginning.parentNode ) {
     if ( el && el.parentNode ) el.parentNode.removeChild( el );
       beginning.parentNode.removeChild( beginning );
  }
     }
 
  // ── 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 Moola / Ullekha nav links ───────────────────────
   // ── TOC: Inject मूल / उल्लेख nav links ─────────────────────────
  // Adds two navigation buttons above the TOC list:
  //  मूल → the primary bhashya page this teeka belongs to
  //          (read from .gr-teeka-page[data-primary] when present,
  //          otherwise derived from the current page path)
  /उल्लेख → the /Ullekha sub-page for this document,
  //          which lists all pramana references cited in it.
  //
  // The nav bar is injected once and is guarded against duplicate runs.
   function injectTocDocNav() {
   function injectTocDocNav() {
    if ( _isNoTocPage() ) return;
     var toc = document.querySelector( '.vector-toc' );
     var toc = document.querySelector( '.vector-toc' );
     if ( !toc ) return;
     if ( !toc ) return;
     if ( document.getElementById( 'gr-toc-doc-nav' ) ) return;
     if ( document.getElementById( 'gr-toc-doc-nav' ) ) return;


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


    /* For teeka/vyakhya pages the imported HTML contains:
    *  <div class="gr-teeka-page" data-primary="Brahmasutra" data-slug="Nyayasudha">
    * Use that when available. */
     var teekaPage  = document.querySelector( '.gr-teeka-page' );
     var teekaPage  = document.querySelector( '.gr-teeka-page' );
     var primarySlug = teekaPage ? ( teekaPage.getAttribute( 'data-primary' ) || '' ) : '';
     var primarySlug = teekaPage ? ( teekaPage.getAttribute( 'data-primary' ) || '' ) : '';
     var docSlug    = teekaPage ? ( teekaPage.getAttribute( 'data-slug' )   || '' ) : '';
     var docSlug    = teekaPage ? ( teekaPage.getAttribute( 'data-slug'   ) || '' ) : '';


    /* If not a teeka page, derive slugs from the page title.
    * Page titles look like "Brahmasutra" or "Brahmasutra/Part1". */
     if ( !primarySlug ) {
     if ( !primarySlug ) {
      /* Top-level doc pages: the slug IS the page (or its root) */
       primarySlug = pageTitle.split( '/' )[ 0 ];
       primarySlug = pageTitle.split( '/' )[ 0 ];
       docSlug    = primarySlug;
       docSlug    = primarySlug;
     }
     }
    if ( !primarySlug ) return;


    if ( !primarySlug ) return;  /* nothing to link to */
    /* ── Build URLs ──────────────────────────────────────────────── */
     function wikiUrl( slug ) {
     function wikiUrl( slug ) {
       if ( window.mw && mw.util && mw.util.getUrl ) {
       if ( window.mw && mw.util && mw.util.getUrl ) return mw.util.getUrl( slug );
        return mw.util.getUrl( slug );
      }
       return artPath.replace( '$1', encodeURIComponent( slug ).replace( /%2F/g, '/' ) );
       return artPath.replace( '$1', encodeURIComponent( slug ).replace( /%2F/g, '/' ) );
     }
     }


     var moolaUrl  = wikiUrl( primarySlug );
     var moolaUrl  = wikiUrl( primarySlug );
     var ullekhaUrl = wikiUrl( ( teekaPage ? ( primarySlug + '/Vyakhya/' + docSlug ) : primarySlug ) + '/Ullekha' );
     var ullekhaUrl = wikiUrl( primarySlug + '/Ullekha' );


     /* ── Don't show Moola link if we ARE the moola page ─────────── */
     /* Hide Moola button when we are already on the moola/bhashya page */
     var isMoola = !teekaPage && ( pageTitle === primarySlug || pageTitle.indexOf( primarySlug + '/Part' ) === 0 );
     var isMoola = !teekaPage &&
                  ( pageTitle === primarySlug ||
                    pageTitle.indexOf( primarySlug + '/Part' ) === 0 );


    /* ── Build the nav bar ───────────────────────────────────────── */
     var nav = document.createElement( 'div' );
     var nav = document.createElement( 'div' );
     nav.id = 'gr-toc-doc-nav';
     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 navStyle = [
     var base = [
       'display:flex',
       'display:inline-block', 'padding:2px 9px', 'border-radius:3px',
       'gap:6px',
       'font-size:0.80em', 'font-weight:500', 'text-decoration:none',
      'padding:6px 8px 4px',
       'border:1px solid currentColor', 'line-height:1.65',
       'border-bottom:1px solid var(--border-color-base,#a2a9b1)',
       'white-space:nowrap', 'font-family:inherit',
       'margin-bottom:4px',
      'flex-wrap:wrap',
     ].join( ';' );
     ].join( ';' );
    nav.setAttribute( 'style', navStyle );


    var btnBase = [
     function btn( href, label, color, bg ) {
      'display:inline-block',
      'padding:2px 8px',
      'border-radius:3px',
      'font-size:0.82em',
      'font-weight:500',
      'text-decoration:none',
      'border:1px solid currentColor',
      'line-height:1.6',
      'white-space:nowrap',
    ].join( ';' );
 
     function makeBtn( href, label, colorVar, bgVar ) {
       var a = document.createElement( 'a' );
       var a = document.createElement( 'a' );
       a.href = href;
       a.href = href;
       a.textContent = label;
       a.textContent = label;
       a.setAttribute( 'style',
       a.setAttribute( 'style', base + ';color:' + color + ';background:' + bg + ';' );
        btnBase + ';'
       a.addEventListener( 'mouseover', function () { this.style.opacity = '0.72'; } );
        + 'color:' + colorVar + ';'
       a.addEventListener( 'mouseout', function () { this.style.opacity = '1';   } );
        + 'background:' + bgVar + ';'
      );
      a.setAttribute( 'data-deva-skip', '1' );   /* don't transliterate these */
       a.addEventListener( 'mouseover', function () {
        this.style.opacity = '0.78';
      } );
       a.addEventListener( 'mouseout', function () {
        this.style.opacity = '1';
      } );
       return a;
       return a;
     }
     }


     if ( !isMoola ) {
     if ( !isMoola ) nav.appendChild( btn( moolaUrl,  'मूल',    '#b04b00', '#fff3e0' ) );
      nav.appendChild( makeBtn( moolaUrl,  'मूल',    '#b04b00', '#fff3e0' ) );
     nav.appendChild(                 btn( ullekhaUrl, 'उल्लेख', '#1a5f8a', '#e8f4fc' ) );
    }
     nav.appendChild(   makeBtn( ullekhaUrl, 'उल्लेख', '#1a6496', '#e8f4fc' ) );


    /* Insert the nav bar at the very top of the TOC, before the heading */
     var tocContents = toc.querySelector( '.vector-toc-contents' );
     var tocInner = toc.querySelector( '.vector-toc-contents' ) || toc.firstElementChild || toc;
    if ( tocContents ) toc.insertBefore( nav, tocContents );
     toc.insertBefore( nav, tocInner );
     else              toc.appendChild( nav );
   }
   }


   // ── TOC active-item highlight ────────────────────────────────────
   // ── TOC active-item highlight ────────────────────────────────────
   // FIX (v6): Instead of relying on CSS :active selectors (which fail because
   // Uses MutationObserver on each <li> to apply/remove orange colour and
   // Common.js wraps text nodes in <span data-deva>, making > a or > .link
   // bold imperatively — bypasses CSS specificity entirely.
   // selectors not match the coloured text), we use a MutationObserver to
   //
   // watch each <li> for class changes and imperatively apply/remove the
   // v7 change: inactive items get font-weight:400 explicitly set so that
   // orange colour via inline style on the .vector-toc-link inside it.
  // no CSS rule can accidentally make them bold. Only the active item
   // This is immune to DOM depth and span nesting.
   // gets font-weight:700. This replaces all the level-1/2/3 bold rules
   // in the CSS that were also making non-active headings bold.
   function watchTocActive() {
   function watchTocActive() {
    if ( _isNoTocPage() ) return;
     var toc = document.querySelector( '.vector-toc' );
     var toc = document.querySelector( '.vector-toc' );
     if ( !toc ) return;
     if ( !toc ) return;
     if ( !window.MutationObserver ) return;
     if ( !window.MutationObserver ) return;
    /* Guard only the structObserver — attach it once per toc element.
 
      Per-<li> attachment is already guarded by _grHighlightAttached,
      so calling watchTocActive() multiple times is safe and picks up
      any <li> items that weren't in the DOM on the first call. */
     if ( toc._grObserved ) {
     if ( toc._grObserved ) {
      /* Re-scan for any <li> items that arrived after first call */
       toc.querySelectorAll( '.vector-toc-list-item' ).forEach( attachHighlight );
       toc.querySelectorAll( '.vector-toc-list-item' ).forEach( attachHighlight );
       return;
       return;
Line 332: Line 315:
     toc._grObserved = true;
     toc._grObserved = true;


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


     function setLinkActive( li, active ) {
     function setActive( li, on ) {
       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 ( active ) {
       if ( on ) {
         link.style.setProperty( 'color',      ACTIVE_COLOR, 'important' );
         link.style.setProperty( 'color',      ACTIVE_COLOR, 'important' );
         link.style.setProperty( 'font-weight', ACTIVE_WEIGHT, 'important' );
         link.style.setProperty( 'font-weight', '700',       'important' );
         link.querySelectorAll( '*' ).forEach( function ( el ) {
         link.querySelectorAll( '*' ).forEach( function ( el ) {
           el.style.setProperty( 'color', ACTIVE_COLOR, 'important' );
           el.style.setProperty( 'color',       ACTIVE_COLOR, 'important' );
          el.style.setProperty( 'font-weight', '700',        'important' );
         } );
         } );
       } else {
       } else {
         link.style.removeProperty( 'color' );
         link.style.removeProperty( 'color' );
         link.style.removeProperty( 'font-weight' );
         link.style.setProperty( 'font-weight', '400', 'important' );
         link.querySelectorAll( '*' ).forEach( function ( el ) {
         link.querySelectorAll( '*' ).forEach( function ( el ) {
           el.style.removeProperty( 'color' );
           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' ) );
      } );
     }
     }


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


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


         if ( isActive ) {
         if ( active ) {
           /* ── Auto-expand parent section in TOC ────────────────────────
           /* Expand any collapsed ancestor sections */
          * Vector collapses child sections under a parent li. When a child
           var anc = li.parentNode;
          * becomes active we must expand its parent by removing the
           while ( anc && anc !== document.body ) {
          * vector-toc-list-item-collapsed class. */
             if ( anc.classList &&
           var ancestor = li.parentNode;
                 anc.classList.contains( 'vector-toc-list-item' ) &&
           while ( ancestor && ancestor !== document.body ) {
                 anc.classList.contains( 'vector-toc-list-item-collapsed' ) ) {
             if ( ancestor.classList &&
               anc.classList.remove( 'vector-toc-list-item-collapsed' );
                 ancestor.classList.contains( 'vector-toc-list-item' ) &&
                 ancestor.classList.contains( 'vector-toc-list-item-collapsed' ) ) {
               ancestor.classList.remove( 'vector-toc-list-item-collapsed' );
             }
             }
             ancestor = ancestor.parentNode;
             anc = anc.parentNode;
           }
           }


           /* ── Scroll active item into view within the TOC ──────────────
           /* Scroll active item into visible TOC area */
          * Use getBoundingClientRect so measurement is always in viewport
          * coords — avoids offsetTop-relative-to-offsetParent mismatch. */
           var container = document.querySelector( '.vector-sticky-pinned-container' );
           var container = document.querySelector( '.vector-sticky-pinned-container' );
           if ( container ) {
           if ( container ) {
             var tocVisible = container.offsetHeight > 0 &&
             var vis = container.offsetHeight > 0 &&
                            container.offsetParent !== null &&
                      container.offsetParent !== null &&
                            window.getComputedStyle( container ).display !== 'none' &&
                      window.getComputedStyle( container ).display !== 'none' &&
                            window.getComputedStyle( container ).visibility !== 'hidden';
                      window.getComputedStyle( container ).visibility !== 'hidden';
             if ( tocVisible ) {
             if ( vis ) {
               var liRect = li.getBoundingClientRect();
               var lr = li.getBoundingClientRect();
               var cRect  = container.getBoundingClientRect();
               var cr = container.getBoundingClientRect();
               if ( liRect.top < cRect.top + 4 || liRect.bottom > cRect.bottom - 4 ) {
               if ( lr.top < cr.top + 4 || lr.bottom > cr.bottom - 4 ) {
                 var scrollHost = null;
                 var sh = null, node = li.parentNode;
                var node = li.parentNode;
                 while ( node && node !== document.body ) {
                 while ( node && node !== document.body ) {
                   var overflow = window.getComputedStyle( node ).overflowY;
                   var ov = window.getComputedStyle( node ).overflowY;
                   if ( ( overflow === 'auto' || overflow === 'scroll' ) &&
                   if ( ( ov === 'auto' || ov === 'scroll' ) &&
                       node.scrollHeight > node.clientHeight ) {
                       node.scrollHeight > node.clientHeight ) {
                     scrollHost = node;
                     sh = node; break;
                    break;
                   }
                   }
                   node = node.parentNode;
                   node = node.parentNode;
                 }
                 }
                 if ( !scrollHost && container.scrollHeight > container.clientHeight ) {
                 if ( !sh && container.scrollHeight > container.clientHeight ) sh = container;
                  scrollHost = container;
                 if ( sh ) {
                }
                   var hr  = sh.getBoundingClientRect();
                 if ( scrollHost ) {
                   var top = lr.top - hr.top + sh.scrollTop;
                   var hostRect = scrollHost.getBoundingClientRect();
                   sh.scrollTop = Math.max( 0, top - sh.clientHeight / 2 + li.offsetHeight / 2 );
                   var currentScroll = scrollHost.scrollTop;
                  var liTop = liRect.top - hostRect.top + currentScroll;
                   var target = liTop - ( scrollHost.clientHeight / 2 ) + ( li.offsetHeight / 2 );
                  scrollHost.scrollTop = Math.max( 0, target );
                 }
                 }
               }
               }
Line 425: Line 402:
     } );
     } );


     var structObserver = new MutationObserver( function ( mutations ) {
     var structObs = new MutationObserver( function ( mutations ) {
       mutations.forEach( function ( m ) {
       mutations.forEach( function ( m ) {
         if ( m.type !== 'childList' ) return;
         if ( m.type !== 'childList' ) return;
         m.addedNodes.forEach( function ( n ) {
         m.addedNodes.forEach( function ( n ) {
           if ( n.nodeType !== 1 ) return;
           if ( n.nodeType !== 1 ) return;
           if ( n.classList && n.classList.contains( 'vector-toc-list-item' ) ) {
           if ( n.classList && n.classList.contains( 'vector-toc-list-item' ) ) attachHighlight( n );
            attachHighlight( n );
           if ( n.querySelectorAll ) n.querySelectorAll( '.vector-toc-list-item' ).forEach( attachHighlight );
          }
           if ( n.querySelectorAll ) {
            n.querySelectorAll( '.vector-toc-list-item' ).forEach( attachHighlight );
          }


           var newSpans = [];
           var newSpans = [];
           if ( n.classList && n.classList.contains( 'vector-toc-text' ) ) newSpans.push( n );
           if ( n.classList && n.classList.contains( 'vector-toc-text' ) ) newSpans.push( n );
           if ( n.querySelectorAll ) {
           if ( n.querySelectorAll ) n.querySelectorAll( '.vector-toc-text' ).forEach( function ( s ) { newSpans.push( s ); } );
            n.querySelectorAll( '.vector-toc-text' ).forEach( function ( s ) { newSpans.push( s ); } );
          }
           newSpans.forEach( function ( span ) {
           newSpans.forEach( function ( span ) {
             if ( span.hasAttribute( 'data-deva' ) ) return;
             if ( span.hasAttribute( 'data-deva' ) ) return;
Line 447: Line 418:
             if ( !orig.trim() ) return;
             if ( !orig.trim() ) return;
             span.setAttribute( 'data-deva', orig );
             span.setAttribute( 'data-deva', orig );
             if ( currentScript !== 'deva' ) {
             if ( currentScript !== 'deva' ) span.textContent = transliterateText( orig, currentScript );
              span.textContent = transliterateText( orig, currentScript );
            }
             translatableSpans.push( span );
             translatableSpans.push( span );
           } );
           } );
Line 457: Line 426:


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


     setTimeout( function () {
     setTimeout( function () {
      normaliseAll();
       var active = toc.querySelector( '.vector-toc-list-item-active' );
       var active = toc.querySelector( '.vector-toc-list-item-active' );
       if ( active ) {
       if ( active ) setActive( active, true );
        setLinkActive( active, true );
      }
     }, 300 );
     }, 300 );
  }
  // ── Run all TOC customisations ───────────────────────────────────
  function setupToc() {
    removeTocBeginning();
    renameTocTitle();
    expandTocSections();
    injectTocDocNav();
    watchTocActive();
   }
   }


Line 479: Line 456:
         if ( el && el.parentNode ) el.parentNode.removeChild( el );
         if ( el && el.parentNode ) el.parentNode.removeChild( el );
       } );
       } );
       var pageTools = document.getElementById( 'vector-page-tools' ) ||
       var pt = document.getElementById( 'vector-page-tools' ) ||
                      document.querySelector( '.vector-page-tools-pinned-container' );
              document.querySelector( '.vector-page-tools-pinned-container' );
       if ( pageTools ) {
       if ( pt ) {
         pageTools.querySelectorAll( '[aria-controls="vector-appearance"]' )
         pt.querySelectorAll( '[aria-controls="vector-appearance"]' )
           .forEach( function ( el ) {
           .forEach( function ( el ) { if ( el.parentNode ) el.parentNode.removeChild( el ); } );
            if ( el.parentNode ) el.parentNode.removeChild( el );
          } );
       }
       }
     }
     }
Line 492: Line 467:
     /* ── Teeka view-mode detection ──────────────────────────────── */
     /* ── Teeka view-mode detection ──────────────────────────────── */
     ( function detectTeekaMode() {
     ( function detectTeekaMode() {
       var teekaPage = document.querySelector( '.gr-teeka-page' );
       var tp = document.querySelector( '.gr-teeka-page' );
       if ( !teekaPage ) return;
       if ( !tp ) return;
 
       var primary = tp.getAttribute( 'data-primary' ) || '';
       var primary = teekaPage.getAttribute( 'data-primary' ) || '';
       var artPath = ( window.mw && mw.config.get( 'wgArticlePath' ) ) || '/wiki/$1';
       var artPath = ( window.mw && mw.config.get( 'wgArticlePath' ) ) || '/wiki/$1';
       var mainUrl = artPath.replace( '$1', primary );
       var mainUrl = artPath.replace( '$1', primary );
 
       var refParam = window.location.search.match( /[?&]ref=([01])/ );
       var qs = window.location.search;
      var refParam = qs.match( /[?&]ref=([01])/ );
       if ( refParam ) {
       if ( refParam ) {
         document.body.classList.add( refParam[1] === '1' ? 'gr-ref-mode' : 'gr-standalone' );
         document.body.classList.add( refParam[1] === '1' ? 'gr-ref-mode' : 'gr-standalone' );
         return;
         return;
       }
       }
       var ref = document.referrer || '';
       var ref = document.referrer || '';
       var fromMain = ref && primary && ref.indexOf( mainUrl ) !== -1;
       document.body.classList.add( ( ref && primary && ref.indexOf( mainUrl ) !== -1 )
      document.body.classList.add( fromMain ? 'gr-ref-mode' : 'gr-standalone' );
        ? 'gr-ref-mode' : 'gr-standalone' );
     }() );
     }() );


     if ( window.MutationObserver ) {
     if ( window.MutationObserver ) {
       var hideObserver = new MutationObserver( function ( mutations ) {
       var hideObs = new MutationObserver( function ( mutations ) {
         var needsClean = false;
         var dirty = false;
         mutations.forEach( function ( m ) {
         mutations.forEach( function ( m ) { if ( m.addedNodes.length ) dirty = true; } );
          if ( m.addedNodes.length ) needsClean = true;
         if ( dirty ) removeHiddenEls();
        } );
         if ( needsClean ) removeHiddenEls();
       } );
       } );
       hideObserver.observe( document.body, { childList: true, subtree: false } );
       hideObs.observe( document.body, { childList: true, subtree: false } );
       setTimeout( function () { hideObserver.disconnect(); }, 6000 );
       setTimeout( function () { hideObs.disconnect(); }, 6000 );
     }
     }


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


     /* TOC setup — remove Beginning link, inject doc-nav, start active watcher.
     /* TOC setup — Vector 2022 defers TOC render, retry at 300ms / 800ms */
    * Retry at 300ms and 800ms because Vector 2022 renders the TOC after
     setupToc();
    * DOMContentLoaded via its own JS. */
     setTimeout( setupToc, 300 );
     removeTocBeginning();
     setTimeout( setupToc, 800 );
    injectTocDocNav();
    watchTocActive();
     setTimeout( function () {
      removeTocBeginning();
      injectTocDocNav();
      watchTocActive();
    }, 300 );
     setTimeout( function () {
      removeTocBeginning();
      injectTocDocNav();
      watchTocActive();
    }, 800 );
   }
   }


   // ── React to toolbar dropdown changes ──────────────────────────
   // ── React to toolbar script-change events ──────────────────────
   window.addEventListener( 'gr-script-change', function ( e ) {
   window.addEventListener( 'gr-script-change', function ( e ) {
     var script = e && e.detail && e.detail.script;
     var script = e && e.detail && e.detail.script;
Line 570: Line 524:
   } );
   } );


   // ── MediaWiki hook (SPA-style navigation) ───────────────────────
   // ── MediaWiki SPA-style navigation hook ─────────────────────────
   if ( window.mw ) {
   if ( window.mw ) {
     mw.hook( 'wikipage.content' ).add( function () {
     mw.hook( 'wikipage.content' ).add( function () {
Line 588: Line 542:
         }
         }
         if ( currentScript !== 'deva' ) applyScript( currentScript );
         if ( currentScript !== 'deva' ) applyScript( currentScript );
         removeTocBeginning();
         setupToc();
        injectTocDocNav();
        watchTocActive();
       }, 150 );
       }, 150 );
     } );
     } );
Line 604: Line 556:




// ── Inject "About" link into the header navigation ─────────────────
// ── Inject "About" link into the header ────────────────────────────
// This is its own IIFE — completely separate from the main IIFE above.
// Own IIFE — was incorrectly nested inside main IIFE in v6 (the missing
// (v6 bug: it was incorrectly nested inside the main IIFE without a
// }() ); broke the module boundary and killed the by-Author toggle).
// closing }() ); which broke the module boundary and killed the
//  by-Author toggle on the main page.)
( function () {
( function () {
   function injectAboutLink() {
   function injectAboutLink() {
Line 618: Line 568:
     if ( !headerEnd ) return;
     if ( !headerEnd ) return;


     var aboutLink = document.createElement( 'a' );
     /* Build the URL correctly for any sub-path install.
     aboutLink.id        = 'gr-about-link';
    * wgArticlePath looks like "/My_wiki/index.php/$1" or "/wiki/$1".
     aboutLink.href      = ( window.mw
    * mw.util.getUrl() uses that internally, so it always produces the
       ? mw.util.getUrl( 'Grantha:About' )
    * right URL for whatever MediaWiki thinks its own root is. */
       : '/wiki/Grantha:About' );
     var href;
     aboutLink.textContent = 'About';
     if ( window.mw && mw.util && mw.util.getUrl ) {
     aboutLink.style.cssText = [
       href = mw.util.getUrl( 'My_wiki:About' );
       'color: rgba(255,255,255,0.88)',
    } else {
      'font-size: 0.88em',
       var ap = ( window.mw && mw.config && mw.config.get( 'wgArticlePath' ) ) || '/wiki/$1';
       'font-family: system-ui, sans-serif',
      href = ap.replace( '$1', 'My_wiki:About' );
      'font-weight: 500',
     }
       'text-decoration: none',
 
      'padding: 4px 10px',
    var a  = document.createElement( 'a' );
      'border-radius: 4px',
    a.id    = 'gr-about-link';
       'margin-right: 6px',
    a.href  = href;
      'transition: color 0.15s, background 0.15s',
    a.textContent = 'About';
       'white-space: nowrap',
     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( ';' );
     ].join( ';' );
     aboutLink.addEventListener( 'mouseover', function () {
     a.addEventListener( 'mouseover', function () {
       this.style.color = '#fff';
       this.style.color = '#fff'; this.style.background = 'rgba(255,255,255,0.12)';
      this.style.background = 'rgba(255,255,255,0.12)';
     } );
     } );
     aboutLink.addEventListener( 'mouseout', function () {
     a.addEventListener( 'mouseout', function () {
       this.style.color = 'rgba(255,255,255,0.88)';
       this.style.color = 'rgba(255,255,255,0.88)'; this.style.background = 'transparent';
      this.style.background = 'transparent';
     } );
     } );


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


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


Line 670: Line 617:
     var aBtn  = document.getElementById( 'gr-toggle-author' );
     var aBtn  = document.getElementById( 'gr-toggle-author' );
     if ( !gView || !aView || !gBtn || !aBtn ) return;
     if ( !gView || !aView || !gBtn || !aBtn ) return;
     gView.style.display = ( v === 'grantha' ) ? '' : 'none';
     gView.style.display = ( v === 'grantha' ) ? '' : 'none';
     aView.style.display = ( v === 'author'  ) ? '' : 'none';
     aView.style.display = ( v === 'author'  ) ? '' : 'none';
Line 682: Line 628:
     var aBtn = document.getElementById( 'gr-toggle-author' );
     var aBtn = document.getElementById( 'gr-toggle-author' );
     if ( !gBtn || !aBtn ) return;
     if ( !gBtn || !aBtn ) return;
     gBtn.addEventListener( 'click', function () { grHomeView( 'grantha' ); } );
     gBtn.addEventListener( 'click', function () { grHomeView( 'grantha' ); } );
     aBtn.addEventListener( 'click', function () { grHomeView( 'author' );  } );
     aBtn.addEventListener( 'click', function () { grHomeView( 'author' );  } );
Line 690: Line 635:
       } );
       } );
     } );
     } );
     var saved;
     var saved;
     try { saved = localStorage.getItem( 'gr_home_view' ); } catch ( e ) {}
     try { saved = localStorage.getItem( 'gr_home_view' ); } catch ( e ) {}
Line 696: Line 640:
   }
   }


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

Revision as of 14:21, 28 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 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 changed from "Contents" → "विषयसूची".
 *  4. TOC: मूल / उल्लेख nav links injected at top of TOC panel.
 *  5. TOC: All subsections expanded by default on load.
 *  6. TOC: Only the active item is bold; all others reset to normal weight.
 *  7. About link: URL now derived from wgArticlePath so it works under
 *     any sub-path (e.g. /My_wiki/). Points to "My_wiki:About".
 *  8. TOC customisations skipped on Main_Page and About pages (no sidebar
 *     TOC on those pages — consistent with __NOTOC__ treatment).
 */

( 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;  /* don't wrap nav buttons */
        }
        var orig = node.textContent;
        if ( !orig.trim() ) return;
        var span = document.createElement( 'span' );
        span.setAttribute( 'data-deva', orig );
        span.textContent = orig;
        p.replaceChild( span, node );
        translatableSpans.push( span );
      } );
    }

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

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

  // ── Pages where the sidebar TOC is absent / should be left alone ─
  // Main_Page uses __NOTOC__; About pages are similar full-page views.
  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;
    /* Replace direct text nodes only — preserves the toggle button sibling */
    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 auto-generated "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 ) {
      /* Fallback: first <li> whose anchor has no "#" fragment */
      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' );

    /* Hide Moola button when we are already on the moola/bhashya page */
    var isMoola = !teekaPage &&
                  ( pageTitle === primarySlug ||
                    pageTitle.indexOf( primarySlug + '/Part' ) === 0 );

    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 btn( 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;
    }

    if ( !isMoola ) nav.appendChild( btn( moolaUrl,   'मूल',    '#b04b00', '#fff3e0' ) );
    nav.appendChild(                 btn( ullekhaUrl, 'उल्लेख', '#1a5f8a', '#e8f4fc' ) );

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

  // ── TOC active-item highlight ────────────────────────────────────
  // Uses MutationObserver on each <li> to apply/remove orange colour and
  // bold imperatively — bypasses CSS specificity entirely.
  //
  // v7 change: inactive items get font-weight:400 explicitly set so that
  // no CSS rule can accidentally make them bold. Only the active item
  // gets font-weight:700. This replaces all the level-1/2/3 bold rules
  // in the CSS that were also making non-active headings bold.
  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;
      if ( on ) {
        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 any 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();

    /* ── Teeka view-mode detection ──────────────────────────────── */
    ( 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'; }

    /* TOC setup — Vector 2022 defers TOC render, retry at 300ms / 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 hook ─────────────────────────
  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 transliteration / TOC IIFE */


// ── Inject "About" link into the header ────────────────────────────
// Own IIFE — was incorrectly nested inside main IIFE in v6 (the missing
// }() ); broke the module boundary and killed the by-Author toggle).
( 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;

    /* Build the URL correctly for any sub-path install.
     * wgArticlePath looks like "/My_wiki/index.php/$1" or "/wiki/$1".
     * mw.util.getUrl() uses that internally, so it always produces the
     * right URL for whatever MediaWiki thinks its own root is. */
    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();
}() );