MediaWiki:Common.portal.js: Difference between revisions
MediaWiki interface page
More actions
No edit summary |
No edit summary |
||
| Line 70: | Line 70: | ||
function initPortalSlider( page ) { | function initPortalSlider( page ) { | ||
var | var hero = page.querySelector( '.portal-hero' ); | ||
if ( ! | if ( !hero ) return; | ||
var category = hero.dataset.category || ''; | |||
var category = | var listPage = hero.dataset.listpage || ''; | ||
var listPage = | |||
if ( !listPage && !category ) return; | if ( !listPage && !category ) return; | ||
| Line 81: | Line 80: | ||
var seed = dailySeed(); | var seed = dailySeed(); | ||
getFileList( listPage, category ) | getFileList( listPage, category ) | ||
.then( function ( files ) { | .then( function ( files ) { | ||
if ( !files.length ) throw new Error( 'No files found' ); | if ( !files.length ) throw new Error( 'No files found' ); | ||
files = seededShuffle( files, seed ); | files = seededShuffle( files, seed ); | ||
files = files.slice( 0, 12 ); | files = files.slice( 0, 12 ); | ||
return fetchThumbnails( files ); | return fetchThumbnails( files ); | ||
} ) | } ) | ||
.then( function ( slides ) { | .then( function ( slides ) { | ||
if ( !slides.length ) throw new Error( 'No thumbnails' ); | if ( !slides.length ) throw new Error( 'No thumbnails' ); | ||
buildCarousel( | buildCarousel( hero, slides ); | ||
} ) | } ) | ||
.catch( function () { | .catch( function () { /* silent — hero stays dark */ } ); | ||
} | } | ||
| Line 192: | Line 181: | ||
} | } | ||
/** Build and wire the carousel DOM */ | /** Build and wire the carousel DOM — bsw-hero style */ | ||
function buildCarousel( | function buildCarousel( hero, slides ) { | ||
var current = 0; | var current = 0; | ||
var total = slides.length; | var total = slides.length; | ||
var timer; | var timer; | ||
var bg = hero.querySelector( '.portal-hero-bg' ); | |||
var caption = hero.querySelector( '.portal-hero-caption' ); | |||
var | var dotsEl = hero.querySelector( '.portal-hero-dots' ); | ||
var prevBtn = hero.querySelector( '.portal-hero-prev' ); | |||
var nextBtn = hero.querySelector( '.portal-hero-next' ); | |||
var caption = | |||
var dotsEl = | |||
var prevBtn = | |||
var nextBtn = | |||
/* Build dot indicators */ | |||
if ( dotsEl ) { | if ( dotsEl ) { | ||
dotsEl.innerHTML = ''; | dotsEl.innerHTML = ''; | ||
slides.forEach( function ( _, i ) { | slides.forEach( function ( _, i ) { | ||
var dot = document.createElement( 'span' ); | var dot = document.createElement( 'span' ); | ||
dot.className = 'portal- | dot.className = 'portal-hero-dot' + ( i === 0 ? ' is-active' : '' ); | ||
dot.setAttribute( 'role', 'button' ); | |||
dot.setAttribute( 'tabindex', '0' ); | |||
dot.addEventListener( 'click', function () { goTo( i ); } ); | dot.addEventListener( 'click', function () { goTo( i ); } ); | ||
dotsEl.appendChild( dot ); | dotsEl.appendChild( dot ); | ||
| Line 237: | Line 209: | ||
current = ( n + total ) % total; | current = ( n + total ) % total; | ||
var s = slides[ current ]; | var s = slides[ current ]; | ||
/* Set background image on the bg div — same as bsw-slide-bg */ | |||
if ( bg ) { | |||
bg.style.backgroundImage = 'url(' + s.thumb + ')'; | |||
} | |||
if ( caption ) { | |||
caption.textContent = s.caption; | |||
} | |||
if ( dotsEl ) { | if ( dotsEl ) { | ||
dotsEl.querySelectorAll( '.portal- | dotsEl.querySelectorAll( '.portal-hero-dot' ).forEach( function ( d, i ) { | ||
d.classList.toggle( 'is-active', i === current ); | d.classList.toggle( 'is-active', i === current ); | ||
} ); | } ); | ||
} | } | ||
resetTimer(); | resetTimer(); | ||
} | } | ||
| Line 252: | Line 228: | ||
function resetTimer() { | function resetTimer() { | ||
clearInterval( timer ); | clearInterval( timer ); | ||
timer = setInterval( function () { goTo( current + 1 ); }, | timer = setInterval( function () { goTo( current + 1 ); }, 6000 ); | ||
} | } | ||
if ( prevBtn ) { | if ( prevBtn ) { | ||
prevBtn.addEventListener( 'click', function () { goTo( current - 1 ); } ); | prevBtn.addEventListener( 'click', function () { goTo( current - 1 ); } ); | ||
prevBtn.addEventListener( 'keydown', function ( e ) { if ( e.key === 'Enter' || e.key === ' ' ) { e.preventDefault(); goTo( current - 1 ); } } ); | prevBtn.addEventListener( 'keydown', function ( e ) { | ||
if ( e.key === 'Enter' || e.key === ' ' ) { e.preventDefault(); goTo( current - 1 ); } | |||
} ); | |||
} | } | ||
if ( nextBtn ) { | if ( nextBtn ) { | ||
nextBtn.addEventListener( 'click', function () { goTo( current + 1 ); } ); | nextBtn.addEventListener( 'click', function () { goTo( current + 1 ); } ); | ||
nextBtn.addEventListener( 'keydown', function ( e ) { if ( e.key === 'Enter' || e.key === ' ' ) { e.preventDefault(); goTo( current + 1 ); } } ); | nextBtn.addEventListener( 'keydown', function ( e ) { | ||
if ( e.key === 'Enter' || e.key === ' ' ) { e.preventDefault(); goTo( current + 1 ); } | |||
} ); | |||
} | } | ||
hero.addEventListener( 'mouseenter', function () { clearInterval( timer ); } ); | |||
hero.addEventListener( 'mouseleave', resetTimer ); | |||
/* Touch/swipe support */ | |||
var touchX = null; | |||
hero.addEventListener( 'touchstart', function ( e ) { | |||
touchX = e.touches[0].clientX; | |||
}, { passive: true } ); | |||
hero.addEventListener( 'touchend', function ( e ) { | |||
if ( touchX === null ) return; | |||
var dx = e.changedTouches[0].clientX - touchX; | |||
if ( Math.abs( dx ) > 40 ) goTo( dx < 0 ? current + 1 : current - 1 ); | |||
touchX = null; | |||
}, { passive: true } ); | |||
goTo( 0 ); | goTo( 0 ); | ||
} | } | ||
/* ════════════════════════════════════════════════════════════════ | /* ════════════════════════════════════════════════════════════════ | ||
Revision as of 01:50, 14 April 2026
/**
* BattlestarWiki — Portal page JavaScript
* MediaWiki:Common.portal.js (or append to MediaWiki:Common.js)
*
* Handles per-portal widgets on any .portal-page:
* 1. Image carousel
* 2. Newest article (portal-scoped)
* 3. Stats bar (live article count)
*
* Self-contained — does not depend on helpers from the main page JS.
*/
( function () {
'use strict';
/* ── API endpoints ──────────────────────────────────────────────── */
var API = 'https://en.battlestarwiki.org/w/api.php';
var MEDIA_API = 'https://media.battlestarwiki.org/w/api.php';
/* ── Shared helpers ─────────────────────────────────────────────── */
function dailySeed() {
var now = new Date();
return Math.floor( Date.UTC(
now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()
) / 86400000 );
}
function esc( s ) {
return String( s || '' )
.replace( /&/g, '&' ).replace( /</g, '<' )
.replace( />/g, '>' ).replace( /"/g, '"' );
}
function apiGetFrom( baseUrl, params ) {
params.format = 'json';
params.origin = '*';
var qs = Object.keys( params )
.map( function ( k ) { return encodeURIComponent( k ) + '=' + encodeURIComponent( params[ k ] ); } )
.join( '&' );
return fetch( baseUrl + '?' + qs, { headers: { Accept: 'application/json' } } )
.then( function ( r ) {
if ( !r.ok ) throw new Error( 'HTTP ' + r.status );
return r.json();
} );
}
function apiGet( params ) {
return apiGetFrom( API, params );
}
/* ── Portal entry point ───────────────────────────────────────── */
mw.hook( 'wikipage.content' ).add( function () {
var page = document.querySelector( '.portal-page' );
if ( !page ) return;
initPortalSlider( page );
initPortalNewest( page );
initPortalStats( page );
} );
/* ════════════════════════════════════════════════════════════════
1. IMAGE CAROUSEL
Reads Portal:NAME/ImageList for a curated file list, falls back
to querying the category directly. Images are fetched via the
media wiki's imageinfo API for thumbnail URLs.
════════════════════════════════════════════════════════════════ */
function initPortalSlider( page ) {
var hero = page.querySelector( '.portal-hero' );
if ( !hero ) return;
var category = hero.dataset.category || '';
var listPage = hero.dataset.listpage || '';
if ( !listPage && !category ) return;
var seed = dailySeed();
getFileList( listPage, category )
.then( function ( files ) {
if ( !files.length ) throw new Error( 'No files found' );
files = seededShuffle( files, seed );
files = files.slice( 0, 12 );
return fetchThumbnails( files );
} )
.then( function ( slides ) {
if ( !slides.length ) throw new Error( 'No thumbnails' );
buildCarousel( hero, slides );
} )
.catch( function () { /* silent — hero stays dark */ } );
}
/**
* Fetch the curated file list from the /ImageList sub-page.
* Falls back to a category member query if the page is missing.
*/
function getFileList( listPage, category ) {
if ( listPage ) {
return apiGet( {
action: 'query',
titles: listPage,
prop: 'revisions',
rvprop: 'content',
rvslots: 'main',
formatversion: '2'
} ).then( function ( data ) {
var pages = data.query && data.query.pages;
if ( !pages || !pages[0] || pages[0].missing ) {
/* Page doesn't exist yet — fall back to category query */
return category ? getCategoryFiles( category ) : [];
}
var content = pages[0].revisions &&
pages[0].revisions[0] &&
pages[0].revisions[0].slots &&
pages[0].revisions[0].slots.main &&
pages[0].revisions[0].slots.main.content || '';
var files = [];
content.split( '\n' ).forEach( function ( line ) {
line = line.replace( /<!--[\s\S]*?-->/g, '' ).trim();
if ( !line ) return;
/* Format: File:Name.jpg | optional caption */
var parts = line.split( '|' );
var fname = parts[0].trim().replace( /^[Ff]ile:/, '' );
var caption = parts[1] ? parts[1].trim() : '';
if ( fname ) files.push( { name: 'File:' + fname, caption: caption } );
} );
return files.length ? files : ( category ? getCategoryFiles( category ) : [] );
} );
}
return category ? getCategoryFiles( category ) : Promise.resolve( [] );
}
/** Fetch file members of a category from the media wiki */
function getCategoryFiles( category ) {
return apiGetFrom( MEDIA_API, {
action: 'query',
list: 'categorymembers',
cmtitle: 'Category:' + category,
cmtype: 'file',
cmlimit: '50'
} ).then( function ( data ) {
return ( data.query.categorymembers || [] ).map( function ( m ) {
return { name: m.title, caption: '' };
} );
} );
}
/** Fetch thumbnail URLs for a list of file objects via imageinfo */
function fetchThumbnails( files ) {
/* MW API accepts up to 50 titles per call */
var titles = files.map( function ( f ) { return f.name; } ).join( '|' );
var captionMap = {};
files.forEach( function ( f ) { captionMap[ f.name ] = f.caption; } );
return apiGetFrom( MEDIA_API, {
action: 'query',
titles: titles,
prop: 'imageinfo',
iiprop: 'url|extmetadata',
iiurlwidth: '800',
formatversion: '2'
} ).then( function ( data ) {
var result = [];
( data.query.pages || [] ).forEach( function ( p ) {
var ii = p.imageinfo && p.imageinfo[0];
if ( !ii || !ii.thumburl ) return;
/* Caption priority: curated list caption → image description metadata */
var caption = captionMap[ p.title ] || '';
if ( !caption && ii.extmetadata && ii.extmetadata.ImageDescription ) {
caption = ii.extmetadata.ImageDescription.value.replace( /<[^>]+>/g, '' );
}
if ( !caption ) caption = p.title.replace( /^File:/, '' ).replace( /\.[^.]+$/, '' );
result.push( { thumb: ii.thumburl, caption: caption, title: p.title } );
} );
return result;
} );
}
/** Build and wire the carousel DOM — bsw-hero style */
function buildCarousel( hero, slides ) {
var current = 0;
var total = slides.length;
var timer;
var bg = hero.querySelector( '.portal-hero-bg' );
var caption = hero.querySelector( '.portal-hero-caption' );
var dotsEl = hero.querySelector( '.portal-hero-dots' );
var prevBtn = hero.querySelector( '.portal-hero-prev' );
var nextBtn = hero.querySelector( '.portal-hero-next' );
/* Build dot indicators */
if ( dotsEl ) {
dotsEl.innerHTML = '';
slides.forEach( function ( _, i ) {
var dot = document.createElement( 'span' );
dot.className = 'portal-hero-dot' + ( i === 0 ? ' is-active' : '' );
dot.setAttribute( 'role', 'button' );
dot.setAttribute( 'tabindex', '0' );
dot.addEventListener( 'click', function () { goTo( i ); } );
dotsEl.appendChild( dot );
} );
}
function goTo( n ) {
current = ( n + total ) % total;
var s = slides[ current ];
/* Set background image on the bg div — same as bsw-slide-bg */
if ( bg ) {
bg.style.backgroundImage = 'url(' + s.thumb + ')';
}
if ( caption ) {
caption.textContent = s.caption;
}
if ( dotsEl ) {
dotsEl.querySelectorAll( '.portal-hero-dot' ).forEach( function ( d, i ) {
d.classList.toggle( 'is-active', i === current );
} );
}
resetTimer();
}
function resetTimer() {
clearInterval( timer );
timer = setInterval( function () { goTo( current + 1 ); }, 6000 );
}
if ( prevBtn ) {
prevBtn.addEventListener( 'click', function () { goTo( current - 1 ); } );
prevBtn.addEventListener( 'keydown', function ( e ) {
if ( e.key === 'Enter' || e.key === ' ' ) { e.preventDefault(); goTo( current - 1 ); }
} );
}
if ( nextBtn ) {
nextBtn.addEventListener( 'click', function () { goTo( current + 1 ); } );
nextBtn.addEventListener( 'keydown', function ( e ) {
if ( e.key === 'Enter' || e.key === ' ' ) { e.preventDefault(); goTo( current + 1 ); }
} );
}
hero.addEventListener( 'mouseenter', function () { clearInterval( timer ); } );
hero.addEventListener( 'mouseleave', resetTimer );
/* Touch/swipe support */
var touchX = null;
hero.addEventListener( 'touchstart', function ( e ) {
touchX = e.touches[0].clientX;
}, { passive: true } );
hero.addEventListener( 'touchend', function ( e ) {
if ( touchX === null ) return;
var dx = e.changedTouches[0].clientX - touchX;
if ( Math.abs( dx ) > 40 ) goTo( dx < 0 ? current + 1 : current - 1 );
touchX = null;
}, { passive: true } );
goTo( 0 );
}
/* ════════════════════════════════════════════════════════════════
2. NEWEST ARTICLE (portal-scoped)
Same logevents call as the main page newest widget, but filtered
to the portal's category via a follow-up categorymembers check.
════════════════════════════════════════════════════════════════ */
function initPortalNewest( page ) {
var inner = page.querySelector( '.portal-newest-inner' );
if ( !inner ) return;
var category = inner.dataset.category || '';
if ( !category ) return;
/* Fetch the 30 most recently created mainspace pages */
apiGet( {
action: 'query',
list: 'logevents',
letype: 'create',
lenamespace: '0',
lelimit: '30',
leprop: 'title|timestamp'
} ).then( function ( data ) {
var entries = ( data.query.logevents || [] ).filter( function ( e ) {
return e.title.indexOf( '/' ) === -1 && e.title !== 'Main Page';
} );
if ( !entries.length ) throw new Error( 'No entries' );
/* Check which of these titles are in the portal's category */
var titles = entries.map( function ( e ) { return e.title; } );
/* Build a timestamp map for quick lookup */
var tsMap = {};
entries.forEach( function ( e ) { tsMap[ e.title ] = e.timestamp; } );
return apiGet( {
action: 'query',
titles: titles.slice( 0, 20 ).join( '|' ),
prop: 'categories',
clcategories: 'Category:' + category,
cllimit: '1'
} ).then( function ( d ) {
/* Find pages that ARE in the category (have a categories array) */
var pages = Object.values( d.query.pages || {} );
var match = pages.find( function ( p ) {
return p.categories && p.categories.length > 0;
} );
/* If none match in the first 20, fall back to the single most recent */
var title = match ? match.title : entries[0].title;
var ts = tsMap[ title ];
return apiGet( {
action: 'query',
titles: title,
prop: 'extracts|pageimages|pageprops',
exintro: '1',
exchars: '400',
exsectionformat: 'plain',
piprop: 'thumbnail',
pithumbsize: '200',
ppprop: 'disambiguation'
} ).then( function ( d2 ) {
var p = Object.values( d2.query.pages || {} )[0] || {};
/* Skip disambiguation, try plain most-recent as fallback */
if ( p.pageprops && p.pageprops.disambiguation !== undefined ) {
title = entries[0].title;
ts = entries[0].timestamp;
return apiGet( {
action: 'query', titles: title,
prop: 'extracts|pageimages', exintro: '1', exchars: '400',
exsectionformat: 'plain', piprop: 'thumbnail', pithumbsize: '200'
} ).then( function ( d3 ) {
return { page: Object.values( d3.query.pages || {} )[0] || {}, ts: ts };
} );
}
return { page: p, ts: ts };
} );
} );
} ).then( function ( result ) {
renderPortalNewest( inner, result.page, result.ts );
} ).catch( function () {
inner.innerHTML = '<div style="font-size:0.8125rem;color:var(--color-subtle,#888)">Could not load newest article.</div>';
} );
}
function renderPortalNewest( inner, page, ts ) {
var title = page.title || '';
var url = 'https://en.battlestarwiki.org/wiki/' + encodeURIComponent( title.replace( / /g, '_' ) );
var thumb = page.thumbnail ? page.thumbnail.source : '';
var extract = ( page.extract || '' ).replace( /<[^>]+>/g, '' ).slice( 0, 300 );
if ( extract.length === 300 ) extract = extract.replace( /\s\S+$/, '' ) + '\u2026';
var date = ts ? new Date( ts ).toLocaleDateString( 'en-US', { year: 'numeric', month: 'long', day: 'numeric' } ) : '';
var thumbHtml = thumb
? '<img src="' + esc( thumb ) + '" alt="' + esc( title ) + '" class="bsw-fa-thumb" style="width:70px;height:52px;object-fit:cover;border-radius:4px;flex-shrink:0">'
: '';
inner.innerHTML =
'<div style="display:flex;gap:10px;align-items:flex-start">' +
thumbHtml +
'<div>' +
'<div class="portal-newest-title"><a href="' + esc( url ) + '">' + esc( title ) + '</a></div>' +
( date ? '<div class="portal-newest-meta">Created ' + esc( date ) + '</div>' : '' ) +
'<div style="font-size:0.8em;color:var(--color-base--subtle,#666);margin-top:3px;line-height:1.5">' + esc( extract ) + '</div>' +
'<div style="margin-top:4px"><a href="' + esc( url ) + '" style="font-size:0.75rem;color:var(--color-link,#3366cc)">Read more \u2192</a></div>' +
'</div>' +
'</div>';
}
/* ════════════════════════════════════════════════════════════════
3. STATS BAR — live article count
The stat_count span with data-category gets its number filled
in from categoryinfo. All other stats are static wikitext.
════════════════════════════════════════════════════════════════ */
function initPortalStats( page ) {
var countEl = page.querySelector( '.portal-stat-count[data-category]' );
if ( !countEl ) return;
var category = countEl.dataset.category;
apiGet( {
action: 'query',
titles: 'Category:' + category,
prop: 'categoryinfo'
} ).then( function ( data ) {
var pages = Object.values( data.query.pages || {} );
if ( !pages[0] || !pages[0].categoryinfo ) return;
var n = pages[0].categoryinfo.pages || 0;
countEl.textContent = n.toLocaleString();
} ).catch( function () {
countEl.textContent = '\u2014';
} );
}
/* ── Seeded shuffle (stable within a calendar day) ────────────── */
function seededShuffle( arr, seed ) {
var a = arr.slice();
var s = seed;
for ( var i = a.length - 1; i > 0; i-- ) {
/* Xorshift32 */
s ^= s << 13;
s ^= s >> 17;
s ^= s << 5;
var j = ( ( s >>> 0 ) % ( i + 1 ) );
var t = a[i]; a[i] = a[j]; a[j] = t;
}
return a;
}
}() );