MediaWiki:FacetBrowser.js
MediaWiki interface page
More actions
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.
/**
* MediaWiki:FacetBrowser.js
*
* Faceted browsing for landrace.wiki record portals (News items, Research items,
* sources, people, places), the Browse landings and All accessions.
*
* WHY THIS EXISTS
* Semantic Result Formats is not installed on this wiki, so SMW's `format=filtered`
* is unavailable, and Page Forms' Special:Drilldown 404s. The remaining route to real
* faceted browsing is to do the faceting client side over the SMW ask API, which
* Common.js already talks to for the maps.
*
* HOW IT WORKS
* A portal renders {{FacetBrowser}}, which emits a configured
* `<div class="lw-facets" data-lwf-*>` wrapper around the ordinary server-rendered
* `#ask` feed. Common.js sees that class and loads this file. This file then:
*
* 1. issues ONE `action=ask` request for the whole record set (plus one small
* lookup ask per joined facet, see parseFacets),
* 2. indexes every facet value in memory,
* 3. replaces the server feed with a filter bar plus its own result grid.
*
* Filtering after that is pure DOM work with no further requests, so every click is
* instant. Measured payloads, gzipped, 2026-08-11: News 363 records = 145 KB,
* Research 79 records = 35 KB. The server-rendered feed stays visible until the
* fetch resolves, so the reader never waits on this script (Common.js itself lands
* around 4.8s in on a cold load).
*
* PROGRESSIVE ENHANCEMENT
* Nothing here is required for the portal to work. If the request fails, the script
* errors, or JS is off entirely, the server-rendered feed is left exactly as the
* parser produced it and only a dismissible notice is added.
*
* CARD MARKUP
* The renderers below emit the same DOM as Template:PortalNewsCard,
* Template:PortalResearchCard, Template:PortalPlaceCard and Template:Browse/TileCard
* so the deployed card CSS applies unchanged. If any of those templates' markup
* changes, change the matching renderer here. The accession card has no template:
* All accessions keeps its table as the server-rendered feed, and the card's
* styles are Template:FacetBrowser/accession.css.
*
* QUERY
* The record set is [[Category:<category>]] plus [[<require>::+]]. Either may be
* left empty, but not both (a tally browser may leave both empty: Browse by
* appellation lists the values the accessions name, and no category holds them). Portal:Geography leaves the category out: its records
* are the pages that carry Has place type, and no single category holds them all.
*
* TALLY (the Browse landings)
* With tally=<Category>:<Property>, the record set becomes the landing's own
* [[Category:<category>]] OR [[-<Property>::<q>[[Category:<Category>]]</q>]], so a
* value the accessions name before its page joins the category still gets a
* tile. One more paged ask over those accessions counts them per record, which
* gives the "Most accessions" sort and the @tally facet. With link=<prefix>, a
* tile opens <prefix><title> when that page exists (one allpages request).
* An appellation's title carries the suffix " (appellation)", which a tile does
* not show (Module:Appellation|name does the same on the server).
*
* Deployed as part of authored/Faceted_Browsing_2026-08-11/.
*/
( function () {
'use strict';
var MAX_PAGES = 6; // hard stop on ask paging, 6 x 500 = 3000 records
var PAGE_SIZE = 500; // SMW $smwgQMaxInlineLimit on this wiki
var RESULT_STEP = 24; // cards revealed per "Show more"
var LIST_PREVIEW = 8; // facet values shown before "Show all"
var SEARCH_DEBOUNCE = 160;
var MONTHS = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ];
/* ---------------------------------------------------------------- utils */
function esc( s ) {
return String( s == null ? '' : s ).replace( /[&<>"']/g, function ( c ) {
return ( {
'&': '&', '<': '<', '>': '>', '"': '"', "'": '''
} )[ c ];
} );
}
function el( tag, cls, text ) {
var n = document.createElement( tag );
if ( cls ) { n.className = cls; }
if ( text != null ) { n.textContent = text; }
return n;
}
function scriptPath() {
return ( window.mw && mw.config && mw.config.get( 'wgScriptPath' ) ) || '';
}
function articleUrl( title ) {
return scriptPath() + '/index.php?title=' + encodeURIComponent(
String( title ).replace( / /g, '_' ) );
}
/**
* SMW returns Page values as objects, Text values as bare strings and Date
* values as { timestamp, raw } where raw is "<calendarmodel>/YYYY/M/D".
*/
function valueToString( v ) {
if ( v == null ) { return ''; }
if ( typeof v === 'object' ) {
if ( v.fulltext ) { return String( v.fulltext ); }
if ( v.raw ) { return String( v.raw ); }
if ( v.value !== undefined ) { return String( v.value ); }
return '';
}
return String( v );
}
function yearOf( v ) {
if ( v && typeof v === 'object' && v.raw ) {
var parts = String( v.raw ).split( '/' );
if ( parts.length > 1 && /^-?\d{1,4}$/.test( parts[ 1 ] ) ) {
return parts[ 1 ];
}
}
var s = valueToString( v );
var m = s.match( /(-?\d{4})/ );
return m ? m[ 1 ] : '';
}
function stampOf( v ) {
if ( v && typeof v === 'object' && v.timestamp !== undefined ) {
return parseInt( v.timestamp, 10 );
}
var y = yearOf( v );
return y ? ( parseInt( y, 10 ) - 1970 ) * 31557600 : -Infinity;
}
function formatDate( v ) {
if ( v && typeof v === 'object' && v.raw ) {
var p = String( v.raw ).split( '/' );
if ( p.length >= 4 ) {
var mi = parseInt( p[ 2 ], 10 ) - 1;
return parseInt( p[ 3 ], 10 ) + ' ' +
( MONTHS[ mi ] || '' ) + ' ' + p[ 1 ];
}
}
return valueToString( v );
}
/**
* Several Page-typed location and agency fields on this wiki hold two or more
* names crammed into ONE value with a semicolon ("Ilocos Sur; Benguet"), which
* would otherwise become a bogus single facet value. Split them for faceting.
* This is a reader-side workaround: the underlying records still need fixing,
* see Data_Quality_Findings_2026-08-11.md.
*/
function splitCrammed( s ) {
if ( s.indexOf( ';' ) === -1 ) { return [ s ]; }
var out = [];
s.split( ';' ).forEach( function ( part ) {
var t = part.replace( /^\s+|\s+$/g, '' );
if ( t ) { out.push( t ); }
} );
return out.length ? out : [ s ];
}
/* --------------------------------------------------------------- config */
/**
* "Has country:Country:list;Has event date:Year:year" -> [{prop,label,type,key}]
*
* A property written "Has country.Has landrace tier" is a JOINED facet: the
* record's own Has country values are looked up in a second, small ask over
* the pages carrying Has landrace tier, and the facet holds what those pages
* say. That avoids a chain printout over the whole record set.
*
* An optional fourth part names the value a record gets when it has none,
* so it can still be chosen: "...:Countries:enum:Other countries".
*
* "@tally" is not a property: it is the With accessions / None yet facet a
* tally browser computes from its counts.
*
* "A+B" pools two properties into one facet: All accessions' Holder reads a
* seed lot's Has seed storage location and a specimen's Has specimen repository.
*/
function parseFacets( spec ) {
var out = [];
( spec || '' ).split( ';' ).forEach( function ( chunk ) {
var bits = chunk.split( ':' );
if ( bits.length < 2 ) { return; }
var prop = bits[ 0 ].replace( /^\s+|\s+$/g, '' );
var label = bits[ 1 ].replace( /^\s+|\s+$/g, '' );
var type = ( bits[ 2 ] || 'list' ).replace( /^\s+|\s+$/g, '' );
var none = ( bits[ 3 ] || '' ).replace( /^\s+|\s+$/g, '' );
if ( !prop || !label ) { return; }
var dot = prop.indexOf( '.' );
out.push( {
prop: prop,
props: dot === -1 && !isComputed( prop ) ? prop.split( '+' ) : [ prop ],
via: dot === -1 ? '' : prop.slice( 0, dot ),
joinProp: dot === -1 ? '' : prop.slice( dot + 1 ),
label: label,
type: type,
none: none,
key: 'f' + out.length
} );
} );
return out;
}
/** "headline:Has event headline;summary:Has event summary" -> {headline:'Has ...'} */
function parseFields( spec ) {
var out = {};
( spec || '' ).split( ';' ).forEach( function ( chunk ) {
var i = chunk.indexOf( ':' );
if ( i === -1 ) { return; }
var name = chunk.slice( 0, i ).replace( /^\s+|\s+$/g, '' );
var prop = chunk.slice( i + 1 ).replace( /^\s+|\s+$/g, '' );
if ( name && prop ) { out[ name ] = prop; }
} );
return out;
}
function readConfig( node ) {
var d = node.dataset || {};
var cfg = {
node: node,
category: d.lwfCategory || '',
require: d.lwfRequire || '',
sortProp: d.lwfSort || '',
card: d.lwfCard || 'news',
facets: parseFacets( d.lwfFacets ),
fields: parseFields( d.lwfFields ),
search: ( d.lwfSearch || '' ).split( ',' )
.map( function ( s ) { return s.replace( /^\s+|\s+$/g, '' ); } )
.filter( Boolean ),
noun: d.lwfNoun || 'records',
helpLink: d.lwfHelp || '',
lead: d.lwfLead === '1',
// The selection a reader starts from, written like the URL fragment
// ("f6=Landrace-growing"). Empty means start unfiltered.
defaults: ( d.lwfDefault || '' ).replace( /^[\s#]+|\s+$/g, '' ),
tally: parseTally( d.lwfTally ),
linkPrefix: d.lwfLink || ''
};
// A tile placeholder names the kind of place, read off the link prefix:
// "Browse by growing area/" -> "Growing area".
var kind = cfg.linkPrefix.replace( /^Browse by\s+|\/$/g, '' );
cfg.typeLabel = kind.charAt( 0 ).toUpperCase() + kind.slice( 1 );
// Appellation pages are titled "<Name> (appellation)"; the tile shows the bare name.
cfg.nameStrip = kind === 'appellation' ? ' (appellation)' : '';
// A to Z sits beside the counts on a tally browser and beside the dates on
// All accessions, whose records are named by their accession IDs.
cfg.azSort = !!cfg.tally || cfg.card === 'accession';
if ( ( !cfg.category && !cfg.require && !cfg.tally ) || !cfg.facets.length ) { return null; }
return cfg;
}
/** "Accessions:Has growing area" -> { category, prop }, or null. */
function parseTally( spec ) {
var i = ( spec || '' ).indexOf( ':' );
if ( i === -1 ) { return null; }
var category = spec.slice( 0, i ).replace( /^\s+|\s+$/g, '' );
var prop = spec.slice( i + 1 ).replace( /^\s+|\s+$/g, '' );
return category && prop ? { category: category, prop: prop } : null;
}
function isComputed( prop ) {
return prop.charAt( 0 ) === '@';
}
/**
* The bands of Browse by elevation (Template:Browse/ElevationCard), in metres,
* lower bound included, upper bound not. A facet of type "elevation" puts each
* record's Has elevation in one of them; keep the two in step.
*/
var ELEVATION_BANDS = [
[ 0, 500, 'Lowland (below 500 m)' ],
[ 500, 1500, 'Highland (500–1,500 m)' ],
[ 1500, 2500, 'Subalpine (1,500–2,500 m)' ],
[ 2500, 3500, 'Alpine (2,500–3,500 m)' ],
[ 3500, Infinity, 'High altitude (3,500 m and above)' ]
];
function elevationBand( v ) {
var n = Number( v && typeof v === 'object' ? v.value : v );
if ( v === null || v === undefined || v === '' || isNaN( n ) ) { return ''; }
for ( var i = 0; i < ELEVATION_BANDS.length; i++ ) {
if ( n < ELEVATION_BANDS[ i ][ 1 ] ) { return ELEVATION_BANDS[ i ][ 2 ]; }
}
return '';
}
function bandIndex( label ) {
for ( var i = 0; i < ELEVATION_BANDS.length; i++ ) {
if ( ELEVATION_BANDS[ i ][ 2 ] === label ) { return i; }
}
return ELEVATION_BANDS.length;
}
/**
* A place belongs to its own country, state and growing region, but its page
* cannot say so: India's infobox stores no Has country, because that property
* points AT India from the pages below it. Without this table the Country facet
* would list every Indian place except India itself. Each rule adds the record's
* own title to the facet on prop when every condition in `when` holds. Only the
* place card's records are the targets of their own facet properties, so the
* rules are keyed by card.
*/
var SELF_FACETS = {
place: [
{ prop: 'Has country', when: { 'Has place type': 'Country' } },
{ prop: 'Has province', when: {
'Has place type': 'Administrative subdivision', 'Has admin level': '1' } },
{ prop: 'Has growing region', when: { 'Has place type': 'Growing region' } }
]
};
function selfRules( cfg ) {
return SELF_FACETS[ cfg.card ] || [];
}
/* ------------------------------------------------------------ ask fetch */
function buildQuery( cfg, offset ) {
var props = {};
cfg.facets.forEach( function ( f ) {
if ( isComputed( f.prop ) ) { return; }
if ( f.via ) { props[ f.via ] = 1; return; }
f.props.forEach( function ( p ) { props[ p ] = 1; } );
} );
Object.keys( cfg.fields ).forEach( function ( k ) {
props[ cfg.fields[ k ] ] = 1;
} );
cfg.search.forEach( function ( p ) { props[ p ] = 1; } );
if ( cfg.sortProp ) { props[ cfg.sortProp ] = 1; }
selfRules( cfg ).forEach( function ( rule ) {
Object.keys( rule.when ).forEach( function ( p ) { props[ p ] = 1; } );
} );
var q = cfg.category ? '[[Category:' + cfg.category + ']]' : '';
if ( cfg.tally ) {
q = ( q ? q + ' OR ' : '' ) + '[[-' + cfg.tally.prop + '::<q>[[Category:' +
cfg.tally.category + ']]</q>]]';
} else if ( cfg.require ) {
q += '[[' + cfg.require + '::+]]';
}
Object.keys( props ).forEach( function ( p ) { q += '|?' + p; } );
q += '|limit=' + PAGE_SIZE + '|offset=' + offset;
return q;
}
function askJson( query ) {
var url = scriptPath() + '/api.php?action=ask&format=json&formatversion=1' +
'&query=' + encodeURIComponent( query );
return fetch( url, { credentials: 'same-origin' } )
.then( function ( r ) {
if ( !r.ok ) { throw new Error( 'HTTP ' + r.status ); }
return r.json();
} )
.then( function ( json ) {
if ( json.error ) {
throw new Error( json.error.info || 'ask error' );
}
return json;
} );
}
/**
* Pages through one ask; queryAt( offset ) returns the query string. When the
* first page comes back full, one format=count ask on the same conditions says
* how many pages remain, and those are fetched side by side and merged in
* offset order (each page of All accessions takes seconds on the server, so
* fetching them one after another kept the filters waiting). If the count
* fails, the pages are fetched one after another as before.
*/
function askAll( queryAt, done, fail ) {
var rows = {};
function take( json ) {
var res = ( json.query && json.query.results ) || {};
var keys = Object.keys( res );
keys.forEach( function ( k ) { rows[ k ] = res[ k ]; } );
return keys.length;
}
function sequential( offset, page ) {
askJson( queryAt( offset ) ).then( function ( json ) {
if ( take( json ) === PAGE_SIZE && page + 1 < MAX_PAGES ) {
sequential( offset + PAGE_SIZE, page + 1 );
} else {
done( rows );
}
} ).catch( fail );
}
askJson( queryAt( 0 ) ).then( function ( json ) {
if ( take( json ) < PAGE_SIZE || MAX_PAGES < 2 ) { done( rows ); return; }
var conditions = queryAt( 0 ).split( '|' )[ 0 ];
askJson( conditions + '|format=count' ).then( function ( cj ) {
var total = parseInt( cj.query && cj.query.count, 10 );
return isNaN( total ) ? null : total;
}, function () { return null; } ).then( function ( total ) {
if ( total === null ) { sequential( PAGE_SIZE, 1 ); return; }
var pages = Math.min( Math.ceil( total / PAGE_SIZE ), MAX_PAGES );
var asks = [];
for ( var p = 1; p < pages; p++ ) {
asks.push( askJson( queryAt( p * PAGE_SIZE ) ) );
}
Promise.all( asks ).then( function ( list ) {
list.forEach( take );
done( rows );
} ).catch( fail );
} );
} ).catch( fail );
}
/**
* The record set, then one small ask per joined facet property mapping each
* page that carries it to its values: joins[ joinProp ][ title ] = [ ... ].
*/
function fetchAll( cfg, done, fail ) {
askAll( function ( offset ) { return buildQuery( cfg, offset ); }, function ( rows ) {
var wanted = [];
cfg.facets.forEach( function ( f ) {
if ( f.joinProp && wanted.indexOf( f.joinProp ) === -1 ) {
wanted.push( f.joinProp );
}
} );
var joins = {};
function nextJoin( i ) {
if ( i >= wanted.length ) {
fetchTally( cfg, function ( tally ) {
fetchLinks( cfg, function ( links ) {
done( rows, joins, { tally: tally, links: links } );
}, fail );
}, fail );
return;
}
var jp = wanted[ i ];
askAll( function ( offset ) {
return '[[' + jp + '::+]]|?' + jp + '|limit=' + PAGE_SIZE +
'|offset=' + offset;
}, function ( jrows ) {
var map = {};
Object.keys( jrows ).forEach( function ( t ) {
var po = ( jrows[ t ] && jrows[ t ].printouts ) || {};
map[ t ] = ( po[ jp ] || [] ).map( valueToString ).filter( Boolean );
} );
joins[ jp ] = map;
nextJoin( i + 1 );
}, fail );
}
nextJoin( 0 );
}, fail );
}
/**
* The tally: every record named by the tally category's pages, with how many
* name it and what those pages say for each facet property:
* tally[ title ] = { n, props: { 'Has country': [ ... ], ... } }.
*/
function fetchTally( cfg, done, fail ) {
if ( !cfg.tally ) { done( null ); return; }
var tp = cfg.tally.prop;
var props = [];
cfg.facets.forEach( function ( f ) {
if ( !f.via && !isComputed( f.prop ) && f.prop !== tp ) { props.push( f.prop ); }
} );
askAll( function ( offset ) {
return '[[Category:' + cfg.tally.category + ']][[' + tp + '::+]]|?' + tp +
props.map( function ( p ) { return '|?' + p; } ).join( '' ) +
'|limit=' + PAGE_SIZE + '|offset=' + offset;
}, function ( arows ) {
var tally = {};
Object.keys( arows ).forEach( function ( t ) {
var po = ( arows[ t ] && arows[ t ].printouts ) || {};
( po[ tp ] || [] ).map( valueToString ).filter( Boolean ).forEach( function ( v ) {
var e = tally[ v ] || ( tally[ v ] = { n: 0, props: {} } );
e.n++;
props.forEach( function ( p ) {
var list = e.props[ p ] || ( e.props[ p ] = [] );
( po[ p ] || [] ).map( valueToString ).forEach( function ( s ) {
if ( s && list.indexOf( s ) === -1 ) { list.push( s ); }
} );
} );
} );
} );
done( tally );
}, fail );
}
/** The pages under linkPrefix, as a set of their titles minus the prefix. */
function fetchLinks( cfg, done, fail ) {
if ( !cfg.linkPrefix ) { done( null ); return; }
var links = {};
function next( cont ) {
var url = scriptPath() + '/api.php?action=query&format=json&formatversion=2' +
'&list=allpages&aplimit=500&apprefix=' + encodeURIComponent( cfg.linkPrefix ) +
( cont ? '&apcontinue=' + encodeURIComponent( cont ) : '' );
fetch( url, { credentials: 'same-origin' } )
.then( function ( r ) {
if ( !r.ok ) { throw new Error( 'HTTP ' + r.status ); }
return r.json();
} )
.then( function ( json ) {
( ( json.query && json.query.allpages ) || [] ).forEach( function ( p ) {
links[ p.title.slice( cfg.linkPrefix.length ) ] = 1;
} );
var c = json[ 'continue' ] && json[ 'continue' ].apcontinue;
if ( c ) { next( c ); } else { done( links ); }
} )
.catch( fail );
}
next( '' );
}
/* ---------------------------------------------------------------- index */
/**
* A tally record whose page says nothing about where it is (no value for any
* facet property the tally carries) is placed by its accessions instead, as
* the Browse cards do for a value named before its page exists.
*/
function inheritPlace( po, entry ) {
var keys = Object.keys( entry.props );
var own = keys.some( function ( p ) { return ( po[ p ] || [] ).length; } );
if ( own ) { return po; }
var out = {};
Object.keys( po ).forEach( function ( p ) { out[ p ] = po[ p ]; } );
keys.forEach( function ( p ) { out[ p ] = entry.props[ p ]; } );
return out;
}
/** Where a tally record's tile goes: its Browse subpage, as Template:Browse/TileCard. */
function tallyTarget( cfg, title, n, links, url ) {
if ( !n || !cfg.linkPrefix ) { return url; }
if ( links && links[ title ] ) { return articleUrl( cfg.linkPrefix + title ); }
var q = '[[Category:' + cfg.tally.category + ']] [[' + cfg.tally.prop + '::' + title + ']]';
var po = [ 'Has descriptive name', 'Has classification', 'Has growing region',
'Has country', 'Has collection date' ].map( function ( p ) {
return encodeURIComponent( '?' + p );
} ).join( '%0A' );
return scriptPath() + '/index.php?title=Special:Ask&q=' + encodeURIComponent( q ) +
'&po=' + po + '&p%5Blimit%5D=500&eq=no';
}
function indexRecords( raw, cfg, joins, extra ) {
var records = [];
joins = joins || {};
var tally = extra && extra.tally;
var links = extra && extra.links;
Object.keys( raw ).forEach( function ( title ) {
var po = ( raw[ title ] && raw[ title ].printouts ) || {};
var rec = {
title: title,
url: ( raw[ title ] && raw[ title ].fullurl ) || articleUrl( title ),
facets: {},
fields: {},
sortKey: 0,
searchText: ''
};
rec.name = cfg.nameStrip && title.slice( -cfg.nameStrip.length ) === cfg.nameStrip ?
title.slice( 0, -cfg.nameStrip.length ) : title;
if ( tally ) {
var entry = tally[ title ] || { n: 0, props: {} };
po = inheritPlace( po, entry );
rec.count = entry.n;
rec.sortKey = entry.n;
rec.target = tallyTarget( cfg, title, entry.n, links, rec.url );
}
cfg.facets.forEach( function ( f ) {
var out = [];
if ( f.prop === '@tally' ) {
rec.facets[ f.key ] = [ rec.count ? 'With accessions' : 'None yet' ];
return;
}
if ( f.joinProp ) {
var map = joins[ f.joinProp ] || {};
( po[ f.via ] || [] ).forEach( function ( v ) {
( map[ valueToString( v ) ] || [] ).forEach( function ( s ) {
if ( out.indexOf( s ) === -1 ) { out.push( s ); }
} );
} );
if ( !out.length && f.none ) { out.push( f.none ); }
rec.facets[ f.key ] = out;
return;
}
var vals = [];
f.props.forEach( function ( p ) { vals = vals.concat( po[ p ] || [] ); } );
vals.forEach( function ( v ) {
if ( f.type === 'year' ) {
var y = yearOf( v );
if ( y ) { out.push( y ); }
return;
}
if ( f.type === 'elevation' ) {
var band = elevationBand( v );
if ( band && out.indexOf( band ) === -1 ) { out.push( band ); }
return;
}
var s = valueToString( v );
if ( !s ) { return; }
splitCrammed( s ).forEach( function ( part ) {
if ( out.indexOf( part ) === -1 ) { out.push( part ); }
} );
} );
selfRules( cfg ).forEach( function ( rule ) {
if ( rule.prop !== f.prop || out.indexOf( title ) !== -1 ) { return; }
var holds = Object.keys( rule.when ).every( function ( p ) {
var w = po[ p ] || [];
return w.length && valueToString( w[ 0 ] ) === rule.when[ p ];
} );
if ( holds ) { out.push( title ); }
} );
if ( !out.length && f.none ) { out.push( f.none ); }
rec.facets[ f.key ] = out;
} );
// fields keeps the first value, which is all the news and research cards
// show; fieldsAll keeps every value for a card that lists them (place).
rec.fieldsAll = {};
Object.keys( cfg.fields ).forEach( function ( name ) {
var vals = po[ cfg.fields[ name ] ] || [];
rec.fields[ name ] = vals.length ? vals[ 0 ] : null;
rec.fieldsAll[ name ] = vals;
} );
if ( cfg.sortProp ) {
var sv = po[ cfg.sortProp ] || [];
rec.sortKey = sv.length ? stampOf( sv[ 0 ] ) : -Infinity;
}
var bag = [ rec.name ];
cfg.search.forEach( function ( p ) {
( po[ p ] || [] ).forEach( function ( v ) {
bag.push( valueToString( v ) );
} );
} );
rec.searchText = bag.join( ' ' ).toLowerCase();
records.push( rec );
} );
// Ties on the count keep A to Z order: the sort below is stable.
if ( tally ) {
records.sort( function ( a, b ) { return a.title.localeCompare( b.title ); } );
}
return records;
}
/* ---------------------------------------------------------------- state */
function makeState( cfg ) {
var sel = {};
cfg.facets.forEach( function ( f ) { sel[ f.key ] = []; } );
return { sel: sel, q: '', order: 'desc', shown: RESULT_STEP };
}
/** AND across facets, OR within a facet. skipKey is used for facet counts. */
function matches( rec, state, skipKey ) {
var ok = true;
Object.keys( state.sel ).forEach( function ( k ) {
if ( !ok || k === skipKey ) { return; }
var chosen = state.sel[ k ];
if ( !chosen.length ) { return; }
var vals = rec.facets[ k ] || [];
var hit = false;
for ( var i = 0; i < chosen.length; i++ ) {
if ( vals.indexOf( chosen[ i ] ) !== -1 ) { hit = true; break; }
}
if ( !hit ) { ok = false; }
} );
if ( !ok ) { return false; }
if ( state.q && rec.searchText.indexOf( state.q ) === -1 ) { return false; }
return true;
}
function filterRecords( records, state, cfg ) {
var out = records.filter( function ( r ) {
return matches( r, state, null );
} );
// An accession with no collection date goes last in both date orders, not
// first in "Oldest". (Ties, including two undated, keep the ask's A to Z order:
// the sort is stable and a NaN comparison counts as a tie.)
var undatedLast = cfg && cfg.card === 'accession';
out.sort( function ( a, b ) {
if ( state.order === 'az' ) { return a.title.localeCompare( b.title ); }
if ( undatedLast && a.sortKey !== b.sortKey &&
( a.sortKey === -Infinity || b.sortKey === -Infinity ) ) {
return a.sortKey === -Infinity ? 1 : -1;
}
return state.order === 'asc' ? a.sortKey - b.sortKey : b.sortKey - a.sortKey;
} );
return out;
}
/**
* Counts for one facet are computed against the set filtered by every OTHER
* facet, so a reader can always widen within the facet they are looking at.
*/
function countsFor( records, state, facet ) {
var counts = {};
records.forEach( function ( r ) {
if ( !matches( r, state, facet.key ) ) { return; }
( r.facets[ facet.key ] || [] ).forEach( function ( v ) {
counts[ v ] = ( counts[ v ] || 0 ) + 1;
} );
} );
return counts;
}
function sortedValues( counts, facet ) {
var keys = Object.keys( counts );
if ( facet.type === 'year' ) {
// Newest first; a "none" value such as "Not recorded" goes last.
keys.sort( function ( a, b ) {
var ya = parseInt( a, 10 ), yb = parseInt( b, 10 );
if ( isNaN( ya ) !== isNaN( yb ) ) { return isNaN( ya ) ? 1 : -1; }
return yb - ya;
} );
} else if ( facet.type === 'elevation' ) {
keys.sort( function ( a, b ) { return bandIndex( a ) - bandIndex( b ); } );
} else {
keys.sort( function ( a, b ) {
if ( counts[ b ] !== counts[ a ] ) { return counts[ b ] - counts[ a ]; }
return a.localeCompare( b );
} );
}
return keys;
}
/* ------------------------------------------------------------ hash sync */
/** The selection as a fragment string, without the '#'. */
function serialise( cfg, state ) {
var parts = [];
cfg.facets.forEach( function ( f ) {
var chosen = state.sel[ f.key ];
if ( chosen.length ) {
parts.push( f.key + '=' + chosen.map( encodeURIComponent ).join( '|' ) );
}
} );
if ( state.q ) { parts.push( 'q=' + encodeURIComponent( state.q ) ); }
if ( state.order === 'asc' || state.order === 'az' ) {
parts.push( 'order=' + state.order );
}
return parts.join( '&' );
}
/**
* A browser with a default selection keeps the bare URL for that default, so
* the portal's own address does not change on load. A reader who clears it
* gets "#all", which readHash takes as "start from nothing" on a reload or a
* shared link.
*/
function writeHash( cfg, state ) {
var s = serialise( cfg, state );
if ( cfg.defaults ) {
if ( s === cfg.defaultHash ) { s = ''; } else if ( !s ) { s = 'all'; }
}
var hash = s ? '#' + s : '';
var url = window.location.pathname + window.location.search + hash;
try {
window.history.replaceState( null, '', url );
} catch ( e ) { /* file:// and some embedded views reject this */ }
}
/* A wikilink cannot carry a space in its fragment: MediaWiki rewrites
* [[Portal:Current Events#f1=Sri Lanka]] to #f1=Sri_Lanka (and does the same
* to an explicit %20), so a hand-written deep link arrives underscored and
* matches no facet value. Restore the space. Facet values on this wiki come
* from page titles and controlled vocabularies, which use spaces and never
* underscores; a value that already contains a space is left untouched so a
* genuine underscore in a mixed value survives. writeHash still emits the
* encoded space, so the round trip is unaffected. */
function hashValue( s ) {
return s.indexOf( ' ' ) === -1 ? s.replace( /_/g, ' ' ) : s;
}
function readHash( cfg, state ) {
applyHash( cfg, state, window.location.hash.replace( /^#/, '' ) || cfg.defaults );
}
function applyHash( cfg, state, hash ) {
if ( !hash || hash === 'all' ) { return; }
hash.split( '&' ).forEach( function ( pair ) {
var i = pair.indexOf( '=' );
if ( i === -1 ) { return; }
var k = pair.slice( 0, i );
var v = pair.slice( i + 1 );
if ( k === 'q' ) {
state.q = decodeURIComponent( v ).toLowerCase();
} else if ( k === 'order' ) {
// A to Z is a tally browser's order and All accessions'; the others sort on a date.
state.order = v === 'asc' ? 'asc' : v === 'az' && cfg.azSort ? 'az' : 'desc';
} else if ( state.sel[ k ] !== undefined ) {
state.sel[ k ] = v.split( '|' ).map( decodeURIComponent )
.map( hashValue ).filter( Boolean );
}
} );
}
/* -------------------------------------------------------------- renderers */
function catSlug( s ) {
return String( s || 'none' ).toLowerCase().replace( /[^a-z0-9]+/g, '' );
}
function renderNewsCard( rec ) {
var card = el( 'div', 'pn-card' );
var cat = valueToString( rec.fields.cat );
var thumb = el( 'div', 'pn-card__thumb pn-thumb--' + catSlug( cat ) );
var img = valueToString( rec.fields.img );
if ( img ) {
var i = document.createElement( 'img' );
i.src = img;
i.alt = '';
i.loading = 'lazy';
i.referrerPolicy = 'same-origin';
i.onerror = function () { thumb.removeChild( i ); };
thumb.appendChild( i );
}
card.appendChild( thumb );
var text = el( 'div', 'pn-card__text' );
var meta = el( 'div', 'pn-card__meta' );
meta.appendChild( el( 'span', 'pn-card__date', formatDate( rec.fields.date ) ) );
if ( cat ) {
meta.appendChild( el( 'span', 'pn-cat pn-cat--' + catSlug( cat ), cat ) );
}
text.appendChild( meta );
var head = el( 'div', 'pn-card__headline' );
var a = el( 'a', null, valueToString( rec.fields.headline ) || rec.title );
a.href = rec.url;
head.appendChild( a );
text.appendChild( head );
var summary = valueToString( rec.fields.summary );
if ( summary ) {
text.appendChild( el( 'div', 'pn-card__summary', summary ) );
}
var where = [ 'country', 'admin1', 'admin2', 'locality', 'region' ]
.map( function ( k ) { return valueToString( rec.fields[ k ] ); } )
.filter( Boolean ).join( ' · ' );
if ( where ) {
text.appendChild( el( 'div', 'pn-card__where', where ) );
}
var foot = el( 'div', 'pn-card__foot' );
var src = valueToString( rec.fields.source );
if ( src ) {
var wrap = el( 'span', 'pn-card__source plainlinks' );
var sa = el( 'a', 'external text', 'Source' );
sa.href = src;
sa.rel = 'nofollow noreferrer';
wrap.appendChild( sa );
foot.appendChild( wrap );
}
var campaign = valueToString( rec.fields.campaign );
if ( campaign ) {
var cwrap = el( 'span', 'pn-card__campaign' );
var ca = el( 'a', null, campaign );
ca.href = articleUrl( campaign );
cwrap.appendChild( ca );
foot.appendChild( cwrap );
}
text.appendChild( foot );
card.appendChild( text );
return card;
}
function renderResearchCard( rec ) {
var card = el( 'div', 'news-card news-card--research' );
var header = el( 'div', 'news-card__header' );
header.appendChild( el( 'span', 'news-card__date', formatDate( rec.fields.date ) ) );
var kind = valueToString( rec.fields.paper_kind );
if ( kind ) {
header.appendChild( el( 'span', 'news-card__badge', kind ) );
}
card.appendChild( header );
var region = [ 'country', 'growing_region' ]
.map( function ( k ) { return valueToString( rec.fields[ k ] ); } )
.filter( Boolean ).join( ' · ' );
if ( region ) {
card.appendChild( el( 'div', 'news-card__region', region ) );
}
var title = el( 'div', 'news-card__title' );
var ta = el( 'a', null, valueToString( rec.fields.paper_name ) || rec.title );
ta.href = rec.url;
title.appendChild( ta );
card.appendChild( title );
var authors = valueToString( rec.fields.authors );
if ( authors ) {
card.appendChild( el( 'div', 'news-card__byline', authors ) );
}
var pub = [ 'venue', 'year' ]
.map( function ( k ) { return valueToString( rec.fields[ k ] ); } )
.filter( Boolean ).join( ' · ' );
if ( pub ) {
card.appendChild( el( 'div', 'news-card__publine', pub ) );
}
var summary = valueToString( rec.fields.summary );
if ( summary ) {
card.appendChild( el( 'div', 'news-card__summary', summary ) );
}
var foot = el( 'div', 'news-card__footer' );
var doi = valueToString( rec.fields.doi );
var src = valueToString( rec.fields.source );
// Mirrors PortalResearchCard: suppress Source when it is just the DOI resolver.
if ( src && ( !doi || src !== 'https://doi.org/' + doi ) ) {
foot.appendChild( linkBtn( src, 'Source' ) );
}
if ( doi ) { foot.appendChild( linkBtn( 'https://doi.org/' + doi, 'DOI' ) ); }
var pdf = valueToString( rec.fields.pdf );
if ( pdf ) { foot.appendChild( linkBtn( pdf, 'PDF' ) ); }
if ( foot.childNodes.length ) { card.appendChild( foot ); }
return card;
}
function linkBtn( href, label ) {
var span = el( 'span', 'news-card__btn news-card__btn--source' );
var a = el( 'a', 'external text', label );
a.href = href;
a.rel = 'nofollow noreferrer';
span.appendChild( a );
return span;
}
/** A Quantity value ({ value, unit }) printed as SMW prints it: "2,631 m". */
function quantityText( v ) {
if ( v && typeof v === 'object' && v.value !== undefined ) {
var n = Number( v.value );
var s = isNaN( n ) ? String( v.value ) : n.toLocaleString( 'en-GB' );
return v.unit ? s + ' ' + v.unit : s;
}
return valueToString( v );
}
/** Page titles of a multi-valued field, the first `max` of them, then "+N". */
function listText( vals, max ) {
var names = ( vals || [] ).map( valueToString ).filter( Boolean );
if ( names.length <= max ) { return names.join( ', ' ); }
return names.slice( 0, max ).join( ', ' ) + ' +' + ( names.length - max );
}
function renderPlaceCard( rec ) {
var card = el( 'div', 'lw-place-card' );
var type = valueToString( rec.fields.type );
var thumb = el( 'a', 'lw-place-card__thumb' );
thumb.href = rec.url;
thumb.tabIndex = -1;
thumb.setAttribute( 'aria-hidden', 'true' );
var img = valueToString( rec.fields.img );
if ( img ) {
var i = document.createElement( 'img' );
i.src = scriptPath() + '/index.php?title=Special:Redirect/file/' +
encodeURIComponent( img.replace( / /g, '_' ) ) + '&width=240';
i.alt = '';
i.loading = 'lazy';
i.onerror = function () {
thumb.removeChild( i );
thumb.className += ' lw-place-card__thumb--none';
};
thumb.appendChild( i );
} else {
thumb.className += ' lw-place-card__thumb--none';
}
card.appendChild( thumb );
var text = el( 'div', 'lw-place-card__text' );
if ( type ) {
text.appendChild( el( 'span', 'lw-place-card__type', type ) );
}
var name = el( 'div', 'lw-place-card__name' );
var a = el( 'a', null, rec.title );
a.href = rec.url;
name.appendChild( a );
text.appendChild( name );
// A country is placed by its subregion; anything below it by the places
// above it. A growing region does not repeat its own name.
var where = type === 'Country' ?
valueToString( rec.fields.subregion ) :
[
listText( rec.fieldsAll.country, 3 ),
listText( rec.fieldsAll.admin1, 2 ),
type === 'Growing region' ? '' : valueToString( rec.fields.region )
].filter( Boolean ).join( ' · ' );
if ( where ) {
text.appendChild( el( 'div', 'lw-place-card__where', where ) );
}
var lo = quantityText( rec.fields.min_elev );
var hi = quantityText( rec.fields.max_elev );
var elev = lo && hi ? ( lo === hi ? lo : lo + ' – ' + hi ) :
hi ? 'up to ' + hi : lo ? 'from ' + lo : '';
if ( elev ) {
var e = el( 'div', 'lw-place-card__elev' );
e.appendChild( el( 'span', 'lw-place-card__label', 'Elevation' ) );
e.appendChild( document.createTextNode( ' ' + elev ) );
text.appendChild( e );
}
card.appendChild( text );
return card;
}
function fileUrl( name, width ) {
return scriptPath() + '/index.php?title=Special:Redirect/file/' +
encodeURIComponent( name.replace( / /g, '_' ) ) + '&width=' + width;
}
/**
* A photo tile for a Browse landing: the picture fills a 4:3 box, the name and
* the place line sit on a dark band across the bottom, the accession count is a
* badge. No picture gives the lettered placeholder. The name's link covers the
* whole tile (CSS), so the tile is one link and one tab stop.
*/
function renderTile( rec, cfg ) {
var tile = el( 'div', 'lw-tile' );
var img = valueToString( rec.fields.img );
function placeholder() {
tile.className += ' lw-tile--none';
var ph = el( 'span', 'lw-tile__ph' );
ph.setAttribute( 'aria-hidden', 'true' );
ph.appendChild( el( 'span', 'lw-tile__initial', rec.name.charAt( 0 ) ) );
ph.appendChild( el( 'span', 'lw-tile__type', cfg.typeLabel ) );
return ph;
}
if ( img ) {
var media = el( 'span', 'lw-tile__media' );
var i = document.createElement( 'img' );
i.src = fileUrl( img, 320 );
i.srcset = fileUrl( img, 640 ) + ' 2x';
i.alt = '';
i.loading = 'lazy';
i.decoding = 'async';
i.onerror = function () { tile.replaceChild( placeholder(), media ); };
media.appendChild( i );
tile.appendChild( media );
} else {
tile.appendChild( placeholder() );
}
var n = rec.count || 0;
tile.appendChild( el( 'span', 'lw-tile__n' + ( n ? '' : ' lw-tile__n--zero' ),
n ? n + ( n === 1 ? ' accession' : ' accessions' ) : 'No accessions yet' ) );
var cap = el( 'span', 'lw-tile__cap' );
var title = el( 'span', 'lw-tile__title' );
var a = el( 'a', null, rec.name );
a.href = rec.target || rec.url;
title.appendChild( a );
cap.appendChild( title );
// Its growing region (or, with none, its state) and its country.
var names = function ( k ) {
return ( rec.fieldsAll[ k ] || [] ).map( valueToString ).filter( Boolean ).join( ', ' );
};
var where = [ names( 'region' ) || names( 'admin1' ), names( 'country' ) ]
.filter( Boolean ).join( ' · ' );
cap.appendChild( el( 'span', 'lw-tile__meta', where ) );
tile.appendChild( cap );
return tile;
}
/**
* One accession on All accessions: a small square photo (or the lettered
* placeholder), the accession ID, the descriptive name, the classification, where
* it comes from (growing area, growing region or state, country) and the year it
* was collected. The name's link covers the card (CSS): one link, one tab stop.
*/
function renderAccession( rec ) {
var card = el( 'div', 'lw-acc' );
var name = valueToString( rec.fields.name ) || rec.title;
var img = valueToString( rec.fields.img );
var thumb = el( 'span', 'lw-acc__thumb' );
thumb.setAttribute( 'aria-hidden', 'true' );
function placeholder() {
thumb.textContent = '';
thumb.className += ' lw-acc__thumb--none';
thumb.appendChild( el( 'span', 'lw-acc__initial', name.charAt( 0 ) ) );
}
if ( img ) {
var i = document.createElement( 'img' );
i.src = fileUrl( img, 240 );
i.alt = '';
i.loading = 'lazy';
i.decoding = 'async';
i.onerror = placeholder;
thumb.appendChild( i );
} else {
placeholder();
}
card.appendChild( thumb );
var text = el( 'div', 'lw-acc__text' );
var top = el( 'div', 'lw-acc__top' );
if ( name !== rec.title ) {
top.appendChild( el( 'span', 'lw-acc__id', rec.title ) );
}
var year = rec.fields.date ? yearOf( rec.fields.date ) : '';
if ( year ) {
top.appendChild( el( 'span', 'lw-acc__year', 'Collected ' + year ) );
}
if ( top.childNodes.length ) { text.appendChild( top ); }
var title = el( 'div', 'lw-acc__name' );
var a = el( 'a', null, name );
a.href = rec.url;
title.appendChild( a );
text.appendChild( title );
var meta = el( 'div', 'lw-acc__meta' );
var cls = valueToString( rec.fields.cls );
if ( cls ) {
meta.appendChild( el( 'span', 'lw-acc__cls lw-acc__cls--' + catSlug( cls ), cls ) );
}
var where = [];
[ 'area', 'region', 'country' ].forEach( function ( k ) {
var s = valueToString( rec.fields[ k ] ) ||
( k === 'region' ? valueToString( rec.fields.admin1 ) : '' );
if ( s && where.indexOf( s ) === -1 ) { where.push( s ); }
} );
if ( where.length ) {
meta.appendChild( el( 'span', 'lw-acc__where', where.join( ' · ' ) ) );
}
text.appendChild( meta );
card.appendChild( text );
return card;
}
var RENDERERS = {
news: renderNewsCard,
research: renderResearchCard,
place: renderPlaceCard,
tile: renderTile,
accession: renderAccession
};
/** Extra class on the results grid, by renderer. */
var GRID_CLASS = {
tile: 'lw-tiles',
accession: 'lw-accs'
};
/* ------------------------------------------------------------------- ui */
function build( cfg, records ) {
// The default in the same canonical form serialise() writes, so that
// writeHash and the lead card can recognise it.
var dflt = makeState( cfg );
applyHash( cfg, dflt, cfg.defaults );
cfg.defaultHash = serialise( cfg, dflt );
var state = makeState( cfg );
readHash( cfg, state );
var root = el( 'div', 'lwf' );
var bar = el( 'div', 'lwf__bar' );
/* row 1: search, count, sort */
var row1 = el( 'div', 'lwf__row lwf__row--top' );
var searchWrap = el( 'div', 'lwf__search' );
var searchInput = document.createElement( 'input' );
searchInput.type = 'search';
searchInput.className = 'lwf__search-input';
searchInput.placeholder = 'Search ' + records.length + ' ' + cfg.noun +
' by keyword';
searchInput.setAttribute( 'aria-label',
'Search ' + cfg.noun + ' by keyword' );
searchInput.value = state.q;
searchWrap.appendChild( searchInput );
row1.appendChild( searchWrap );
var count = el( 'div', 'lwf__count' );
count.setAttribute( 'aria-live', 'polite' );
row1.appendChild( count );
var sortWrap = el( 'label', 'lwf__sort' );
sortWrap.appendChild( el( 'span', 'lwf__sort-label', 'Sort' ) );
var sortSel = document.createElement( 'select' );
sortSel.className = 'lwf__sort-select';
( cfg.tally ? [ [ 'desc', 'Most accessions' ], [ 'az', 'A to Z' ] ] :
cfg.azSort ? [ [ 'desc', 'Latest collected' ], [ 'asc', 'Earliest collected' ],
[ 'az', 'A to Z' ] ] :
[ [ 'desc', 'Newest first' ], [ 'asc', 'Oldest first' ] ] )
.forEach( function ( pair ) {
var o = document.createElement( 'option' );
o.value = pair[ 0 ];
o.textContent = pair[ 1 ];
sortSel.appendChild( o );
} );
sortSel.value = state.order;
sortWrap.appendChild( sortSel );
/* The sort control offers newest/oldest, which only means something
when a date property was configured. A browser without one (people
and organisations, sorted by name) leaves it out. sortSel itself is
still created and wired up, because later handlers reference it. */
if ( cfg.sortProp || cfg.tally ) {
row1.appendChild( sortWrap );
}
bar.appendChild( row1 );
/* row 2: the facet controls */
var row2 = el( 'div', 'lwf__row lwf__row--facets' );
bar.appendChild( row2 );
/* row 3: active filter pills */
var row3 = el( 'div', 'lwf__row lwf__row--active' );
bar.appendChild( row3 );
root.appendChild( bar );
var results = el( 'div', 'lwf__results pn-feed__grid' +
( GRID_CLASS[ cfg.card ] ? ' ' + GRID_CLASS[ cfg.card ] : '' ) );
root.appendChild( results );
var more = el( 'div', 'lwf__more' );
var moreBtn = el( 'button', 'lwf__more-btn' );
moreBtn.type = 'button';
more.appendChild( moreBtn );
root.appendChild( more );
var empty = el( 'div', 'lwf__empty' );
root.appendChild( empty );
var renderCard = RENDERERS[ cfg.card ] || renderNewsCard;
var openPanel = null;
function closePanels( except ) {
row2.querySelectorAll( '.lwf-facet' ).forEach( function ( f ) {
if ( f === except ) { return; }
f.classList.remove( 'is-open' );
var b = f.querySelector( '.lwf-facet__toggle' );
if ( b ) { b.setAttribute( 'aria-expanded', 'false' ); }
} );
if ( except === null ) { openPanel = null; }
}
function toggleValue( key, value ) {
var arr = state.sel[ key ];
var i = arr.indexOf( value );
if ( i === -1 ) { arr.push( value ); } else { arr.splice( i, 1 ); }
state.shown = RESULT_STEP;
update();
}
function clearAll() {
Object.keys( state.sel ).forEach( function ( k ) { state.sel[ k ] = []; } );
state.q = '';
searchInput.value = '';
state.shown = RESULT_STEP;
update();
}
/* ---- facet controls ---- */
var facetNodes = [];
cfg.facets.forEach( function ( facet ) {
var wrap = el( 'div', 'lwf-facet lwf-facet--' + facet.type );
if ( facet.type === 'enum' ) {
wrap.appendChild( el( 'span', 'lwf-facet__label', facet.label ) );
var chips = el( 'div', 'lwf-facet__chips' );
wrap.appendChild( chips );
facetNodes.push( { facet: facet, wrap: wrap, chips: chips } );
} else {
var toggle = el( 'button', 'lwf-facet__toggle' );
toggle.type = 'button';
toggle.setAttribute( 'aria-expanded', 'false' );
toggle.setAttribute( 'aria-haspopup', 'true' );
wrap.appendChild( toggle );
var panel = el( 'div', 'lwf-facet__panel' );
var filterBox = null;
var list = el( 'div', 'lwf-facet__list' );
if ( facet.type !== 'year' && facet.type !== 'elevation' ) {
filterBox = document.createElement( 'input' );
filterBox.type = 'search';
filterBox.className = 'lwf-facet__filter';
filterBox.placeholder = 'Filter ' + facet.label.toLowerCase();
filterBox.setAttribute( 'aria-label',
'Filter the ' + facet.label.toLowerCase() + ' list' );
panel.appendChild( filterBox );
}
panel.appendChild( list );
wrap.appendChild( panel );
toggle.addEventListener( 'click', function ( e ) {
e.stopPropagation();
var isOpen = wrap.classList.contains( 'is-open' );
closePanels( null );
if ( !isOpen ) {
wrap.classList.add( 'is-open' );
toggle.setAttribute( 'aria-expanded', 'true' );
openPanel = wrap;
if ( filterBox ) { filterBox.focus(); }
}
} );
panel.addEventListener( 'click', function ( e ) { e.stopPropagation(); } );
if ( filterBox ) {
filterBox.addEventListener( 'input', function () {
var needle = filterBox.value.toLowerCase();
list.querySelectorAll( '.lwf-opt' ).forEach( function ( o ) {
var hit = o.dataset.value.toLowerCase().indexOf( needle ) !== -1;
o.style.display = hit ? '' : 'none';
} );
} );
}
facetNodes.push( {
facet: facet, wrap: wrap, toggle: toggle,
list: list, filterBox: filterBox, expanded: false
} );
}
row2.appendChild( wrap );
} );
if ( cfg.helpLink ) {
var help = el( 'a', 'lwf__help', 'How to query the database' );
help.href = articleUrl( cfg.helpLink );
row2.appendChild( help );
}
document.addEventListener( 'click', function () { closePanels( null ); } );
document.addEventListener( 'keydown', function ( e ) {
if ( e.key === 'Escape' && openPanel ) {
var t = openPanel.querySelector( '.lwf-facet__toggle' );
closePanels( null );
if ( t ) { t.focus(); }
}
} );
/* ---- painting ---- */
function paintFacets() {
facetNodes.forEach( function ( fn ) {
var counts = countsFor( records, state, fn.facet );
var values = sortedValues( counts, fn.facet );
var chosen = state.sel[ fn.facet.key ];
if ( fn.facet.type === 'enum' ) {
fn.chips.textContent = '';
values.forEach( function ( v ) {
var b = el( 'button',
'lwf-chip' + ( chosen.indexOf( v ) !== -1 ? ' is-on' : '' ) );
b.type = 'button';
b.setAttribute( 'aria-pressed',
chosen.indexOf( v ) !== -1 ? 'true' : 'false' );
b.appendChild( el( 'span', 'lwf-chip__dot lwf-chip__dot--' +
catSlug( v ) ) );
b.appendChild( el( 'span', 'lwf-chip__text', v ) );
b.appendChild( el( 'span', 'lwf-chip__n', String( counts[ v ] ) ) );
b.addEventListener( 'click', function () {
toggleValue( fn.facet.key, v );
} );
fn.chips.appendChild( b );
} );
return;
}
fn.toggle.textContent = '';
fn.toggle.appendChild( el( 'span', 'lwf-facet__name', fn.facet.label ) );
if ( chosen.length ) {
fn.toggle.appendChild(
el( 'span', 'lwf-facet__badge', String( chosen.length ) ) );
fn.wrap.classList.add( 'has-selection' );
} else {
fn.wrap.classList.remove( 'has-selection' );
}
fn.toggle.appendChild( el( 'span', 'lwf-facet__caret', '▾' ) );
fn.list.textContent = '';
var limit = fn.expanded ? values.length :
Math.max( LIST_PREVIEW, chosen.length );
values.slice( 0, limit ).forEach( function ( v ) {
var opt = el( 'label', 'lwf-opt' );
opt.dataset.value = v;
var cb = document.createElement( 'input' );
cb.type = 'checkbox';
cb.className = 'lwf-opt__box';
cb.checked = chosen.indexOf( v ) !== -1;
cb.addEventListener( 'change', function () {
toggleValue( fn.facet.key, v );
} );
opt.appendChild( cb );
opt.appendChild( el( 'span', 'lwf-opt__text', v ) );
opt.appendChild( el( 'span', 'lwf-opt__n', String( counts[ v ] ) ) );
fn.list.appendChild( opt );
} );
if ( values.length > limit ) {
var showAll = el( 'button', 'lwf-facet__all',
'Show all ' + values.length );
showAll.type = 'button';
showAll.addEventListener( 'click', function () {
fn.expanded = true;
paintFacets();
} );
fn.list.appendChild( showAll );
}
if ( !values.length ) {
fn.list.appendChild( el( 'div', 'lwf-facet__none',
'No values in the current selection' ) );
}
} );
}
function paintActive() {
row3.textContent = '';
var any = false;
cfg.facets.forEach( function ( facet ) {
state.sel[ facet.key ].forEach( function ( v ) {
any = true;
var pill = el( 'button', 'lwf-pill' );
pill.type = 'button';
pill.setAttribute( 'aria-label',
'Remove filter ' + facet.label + ' ' + v );
pill.appendChild( el( 'span', 'lwf-pill__k', facet.label ) );
pill.appendChild( el( 'span', 'lwf-pill__v', v ) );
pill.appendChild( el( 'span', 'lwf-pill__x', '×' ) );
pill.addEventListener( 'click', function () {
toggleValue( facet.key, v );
} );
row3.appendChild( pill );
} );
} );
if ( state.q ) {
any = true;
var qp = el( 'button', 'lwf-pill' );
qp.type = 'button';
qp.setAttribute( 'aria-label', 'Clear the keyword search' );
qp.appendChild( el( 'span', 'lwf-pill__k', 'Keyword' ) );
qp.appendChild( el( 'span', 'lwf-pill__v', state.q ) );
qp.appendChild( el( 'span', 'lwf-pill__x', '×' ) );
qp.addEventListener( 'click', function () {
state.q = '';
searchInput.value = '';
state.shown = RESULT_STEP;
update();
} );
row3.appendChild( qp );
}
if ( any ) {
var clear = el( 'button', 'lwf-clear', 'Clear all' );
clear.type = 'button';
clear.addEventListener( 'click', clearAll );
row3.appendChild( clear );
}
row3.style.display = any ? '' : 'none';
}
function paintResults() {
var hits = filterRecords( records, state, cfg );
count.textContent = hits.length === records.length ?
String( records.length ) + ' ' + cfg.noun :
String( hits.length ) + ' of ' + records.length + ' ' + cfg.noun;
/*
* In the starting view (no filters, or exactly the configured
* default) the newest record keeps the lead-card treatment the
* portal design gives it, spanning both grid columns. Once the
* reader filters or flips the order there is no "top story" any
* more, so every card renders the same.
*/
var now = serialise( cfg, state );
var lead = cfg.lead && ( now === '' || now === cfg.defaultHash );
results.textContent = '';
hits.slice( 0, state.shown ).forEach( function ( rec, i ) {
var card = renderCard( rec, cfg );
if ( lead && i === 0 ) { card.classList.add( 'pn-card--lead' ); }
results.appendChild( card );
} );
if ( hits.length > state.shown ) {
var remaining = hits.length - state.shown;
moreBtn.textContent = 'Show ' +
Math.min( RESULT_STEP, remaining ) + ' more';
more.style.display = '';
} else {
more.style.display = 'none';
}
if ( !hits.length ) {
empty.textContent = '';
empty.appendChild( el( 'p', null,
'No ' + cfg.noun + ' match the current filters.' ) );
var reset = el( 'button', 'lwf-clear', 'Clear all filters' );
reset.type = 'button';
reset.addEventListener( 'click', clearAll );
empty.appendChild( reset );
// Explicit value, not '': the sheet's base rule is display:none,
// so clearing the inline style would re-hide it.
empty.style.display = 'block';
} else {
empty.style.display = 'none';
}
}
function update() {
paintFacets();
paintActive();
paintResults();
writeHash( cfg, state );
}
moreBtn.addEventListener( 'click', function () {
state.shown += RESULT_STEP;
paintResults();
} );
sortSel.addEventListener( 'change', function () {
state.order = sortSel.value === 'asc' || sortSel.value === 'az' ?
sortSel.value : 'desc';
paintResults();
} );
var debounce = null;
searchInput.addEventListener( 'input', function () {
clearTimeout( debounce );
debounce = setTimeout( function () {
state.q = searchInput.value.toLowerCase().replace( /^\s+|\s+$/g, '' );
state.shown = RESULT_STEP;
update();
}, SEARCH_DEBOUNCE );
} );
window.addEventListener( 'hashchange', function () {
var fresh = makeState( cfg );
readHash( cfg, fresh );
state.sel = fresh.sel;
state.q = fresh.q;
state.order = fresh.order;
state.shown = RESULT_STEP;
searchInput.value = state.q;
sortSel.value = state.order;
update();
} );
update();
return root;
}
/* ----------------------------------------------------------------- boot */
function activate( node ) {
if ( node.dataset.lwfReady === '1' ) { return; }
node.dataset.lwfReady = '1';
var cfg = readConfig( node );
if ( !cfg ) {
return; // misconfigured: leave the server-rendered feed alone
}
var fallback = node.querySelector( '.lwf-fallback' );
var status = el( 'div', 'lwf__status', 'Loading filters…' );
node.insertBefore( status, node.firstChild );
fetchAll( cfg, function ( raw, joins, extra ) {
var records = indexRecords( raw, cfg, joins, extra );
if ( !records.length ) {
status.parentNode.removeChild( status );
return;
}
var ui = build( cfg, records );
if ( fallback ) { fallback.style.display = 'none'; }
status.parentNode.replaceChild( ui, status );
}, function ( err ) {
// The parser-rendered feed is still on the page and still correct.
status.className = 'lwf__status lwf__status--error';
status.textContent = 'Filters are unavailable right now. ' +
'The latest ' + cfg.noun + ' are listed below.';
if ( window.console ) {
console.warn( '[lw-facets] ' + ( err && err.message ? err.message : err ) );
}
} );
}
function init() {
var nodes = document.querySelectorAll( '.lw-facets' );
for ( var i = 0; i < nodes.length; i++ ) { activate( nodes[ i ] ); }
}
if ( document.readyState === 'loading' ) {
document.addEventListener( 'DOMContentLoaded', init );
} else {
init();
}
}() );