MediaWiki:Common.js
From Taylor Wiki
Note: After publishing, you may have to bypass your browser's cache to see the changes.
- Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
- Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
- Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
/* Dynamic session breadcrumb trail with automatic Home anchor */
( function () {
var conf = mw.config.get([
'wgAction',
'wgNamespaceNumber',
'wgPageName',
'wgTitle',
'wgIsMainPage',
'wgMainPageTitle'
]);
// Only run on standard page views (ignore edit forms, history, special pages)
if ( conf.wgAction !== 'view' || conf.wgNamespaceNumber < 0 ) {
return;
}
var STORAGE_KEY = 'gewame_wiki_crumbs';
var MAX_CRUMBS = 5;
var mainPageTitle = conf.wgMainPageTitle || 'Main Page';
var homeUrl = mw.util.getUrl( mainPageTitle );
var isHome = conf.wgIsMainPage || ( conf.wgPageName === mainPageTitle.replace( / /g, '_' ) );
// If currently on Home, reset history to just Home and don't render a trail
if ( isHome ) {
try {
sessionStorage.setItem( STORAGE_KEY, JSON.stringify( [ { title: 'Home', url: homeUrl } ] ) );
} catch ( e ) {}
return;
}
var currentTitle = conf.wgTitle.replace( /_/g, ' ' );
var currentUrl = mw.util.getUrl( conf.wgPageName );
var history = [];
try {
var raw = sessionStorage.getItem( STORAGE_KEY );
if ( raw ) {
history = JSON.parse( raw );
}
} catch ( e ) {
history = [];
}
// Always ensure 'Home' is the very first crumb
if ( !history.length || history[0].title !== 'Home' ) {
history = [ { title: 'Home', url: homeUrl } ];
}
// If current page is already in the trail, trim back to it (prevents loops)
var existingIndex = -1;
for ( var i = 0; i < history.length; i++ ) {
if ( history[i].url === currentUrl ) {
existingIndex = i;
break;
}
}
if ( existingIndex !== -1 ) {
history = history.slice( 0, existingIndex + 1 );
} else {
history.push( { title: currentTitle, url: currentUrl } );
// Keep within limit, preserving 'Home' at index 0
if ( history.length > MAX_CRUMBS ) {
history.splice( 1, 1 );
}
}
try {
sessionStorage.setItem( STORAGE_KEY, JSON.stringify( history ) );
} catch ( e ) {}
// Build the breadcrumb bar
var $nav = $( '<div class="mw-dynamic-breadcrumbs" aria-label="Breadcrumb Trail"></div>' );
$nav.append( '<span class="crumb-label">Trail:</span> ' );
for ( var j = 0; j < history.length; j++ ) {
var isCurrent = ( j === history.length - 1 );
if ( j > 0 ) {
$nav.append( '<span class="crumb-sep">›</span>' );
}
if ( isCurrent ) {
$nav.append( $( '<span>' ).addClass( 'crumb-current' ).text( history[j].title ) );
} else {
var $link = $( '<a>' )
.addClass( 'crumb-link' )
.attr( 'href', history[j].url )
.text( history[j].title );
$nav.append( $link );
}
}
// Inject above page title in Timeless
$( function () {
var $heading = $( '#firstHeading' );
if ( $heading.length ) {
$nav.insertBefore( $heading );
} else {
$( '#mw-content-text' ).prepend( $nav );
}
} );
}() );