MediaWiki:Common.js: Difference between revisions
MediaWiki interface page
More actions
Created page with "→Any JavaScript here will be loaded for all users on every page load.: →Avatarverse timeline browser. Installed by an interface administrator in * MediaWiki:Common.js. No external dependencies, account access or writes. * Only runs on the two timeline explorer pages. Calendar constants match Time.java.: (function (factory) { 'use strict'; var model = factory(); if (typeof window !== 'undefined' && typeof mw !== 'undefined') mw.loader.using('mediawiki.util')..." |
Fix timeline text encoding and deploy the managed character-lifetime browser |
||
| Line 1: | Line 1: | ||
/* Any JavaScript here will be loaded for all users on every page load. */ | /* Any JavaScript here will be loaded for all users on every page load. */ | ||
/* Avatarverse timeline browser. | // BEGIN AV TIMELINE (managed by A2TL) | ||
/* Avatarverse timeline browser. Maintained through the A2TL wiki MCP in | |||
* MediaWiki:Common.js. No external dependencies, account access or writes. | * MediaWiki:Common.js. No external dependencies, account access or writes. | ||
* Only runs on the two timeline explorer pages. Calendar constants match Time.java. | * Only runs on the two timeline explorer pages. Calendar constants match Time.java. | ||
| Line 24: | Line 25: | ||
// Some legacy records retain real-world heading labels in DateText. Those | // Some legacy records retain real-world heading labels in DateText. Those | ||
// are provenance, not in-world dates; keep the stored value, show AG instead. | // are provenance, not in-world dates; keep the stored value, show AG instead. | ||
if (!/\bAG\b/.test(date)) date=start===end?start+' AG':start+' | if (!/\bAG\b/.test(date)) date=start===end?start+' AG':start+'\u2013'+end+' AG'; | ||
return { id:row.EventID, start:start, end:end, date:date, | return { id:row.EventID, start:start, end:end, date:date, | ||
title:plain(row.Title), prose:plain(row.Description) || plain(row.Title), | title:plain(row.Title), prose:plain(row.Description) || plain(row.Title), | ||
| Line 54: | Line 55: | ||
'hikari':'Fire Nation','caldera city':'Fire Nation','ember island':'Fire Nation','takemi':'Fire Nation','takemaru':'Fire Nation','furushiki':'Fire Nation','noriko village':'Fire Nation','kayamoto island':'Fire Nation','hiseki':'Fire Nation','crescent island':'Fire Nation','imagawa':'Fire Nation', | 'hikari':'Fire Nation','caldera city':'Fire Nation','ember island':'Fire Nation','takemi':'Fire Nation','takemaru':'Fire Nation','furushiki':'Fire Nation','noriko village':'Fire Nation','kayamoto island':'Fire Nation','hiseki':'Fire Nation','crescent island':'Fire Nation','imagawa':'Fire Nation', | ||
'northern air temple':'Air Nation','southern air temple':'Air Nation','western air temple':'Air Nation','eastern air temple':'Air Nation','air temple island':'Air Nation','floating sands':'Air Nation','whale tail island':'Air Nation', | 'northern air temple':'Air Nation','southern air temple':'Air Nation','western air temple':'Air Nation','eastern air temple':'Air Nation','air temple island':'Air Nation','floating sands':'Air Nation','whale tail island':'Air Nation', | ||
'agna | 'agna qel\u2019a':'Northern Water Tribe','nunatak':'Northern Water Tribe','ikiaq':'Northern Water Tribe','anana tun\u2019ila':'Southern Water Tribe', | ||
'masked village':'Foggy Swamp Tribe','hanging village':'Foggy Swamp Tribe','banyan grove':'Foggy Swamp Tribe','radish lotus village':'Foggy Swamp Tribe','bao grove':'Foggy Swamp Tribe', | 'masked village':'Foggy Swamp Tribe','hanging village':'Foggy Swamp Tribe','banyan grove':'Foggy Swamp Tribe','radish lotus village':'Foggy Swamp Tribe','bao grove':'Foggy Swamp Tribe', | ||
'ninuno':'Sun Warriors','la | 'ninuno':'Sun Warriors','la bay\u0101n':'Sun Warriors','hortezuca':'Sun Warriors','bianqui':'Sun Warriors','rakanet':'Sun Warriors','arangoy':'Sun Warriors', | ||
'misty palms oasis':'Sand Tribes','si wong desert':'Sand Tribes','itgel':'Sand Tribes','kherdu arena':'Sand Tribes' | 'misty palms oasis':'Sand Tribes','si wong desert':'Sand Tribes','itgel':'Sand Tribes','kherdu arena':'Sand Tribes' | ||
}; | }; | ||
| Line 88: | Line 89: | ||
function ageLabel(row, age, currentYear) { | function ageLabel(row, age, currentYear) { | ||
var low = Math.max(0,row.start-(currentYear-age)-1), high = Math.min(age,Math.max(0,row.end-(currentYear-age-1))); | var low = Math.max(0,row.start-(currentYear-age)-1), high = Math.min(age,Math.max(0,row.end-(currentYear-age-1))); | ||
return high<=1?'Around your birth':low===high?'About age '+low:'About age '+low+' | return high<=1?'Around your birth':low===high?'About age '+low:'About age '+low+'\u2013'+high; | ||
} | } | ||
async function collect(request) { | async function collect(request) { | ||
| Line 111: | Line 112: | ||
var lifetime=page==='Timeline/Character_lifetime', currentYear=worldYear(Date.now()); | var lifetime=page==='Timeline/Character_lifetime', currentYear=worldYear(Date.now()); | ||
var fallback=document.getElementById('av-timeline-fallback'); | var fallback=document.getElementById('av-timeline-fallback'); | ||
var loading=document.createElement('p');loading.setAttribute('role','status');loading.textContent='Loading | var loading=document.createElement('p');loading.setAttribute('role','status');loading.textContent='Loading history\u2026';root.appendChild(loading); | ||
var endpoint=new URL(mw.util.wikiScript('api'),location.origin); | var endpoint=new URL(mw.util.wikiScript('api'),location.origin); | ||
collect(async function (offset) { | collect(async function (offset) { | ||
| Line 134: | Line 135: | ||
root.replaceChildren(); | root.replaceChildren(); | ||
function el(tag,text,parent) {var node=document.createElement(tag);if(text)node.textContent=text;if(parent)parent.appendChild(node);return node;} | function el(tag,text,parent) {var node=document.createElement(tag);if(text)node.textContent=text;if(parent)parent.appendChild(node);return node;} | ||
var form=el('form',null,root);form.setAttribute('aria-label',lifetime?'Your | var form=el('form',null,root);form.setAttribute('aria-label',lifetime?'Your character\u2019s lifetime':'Explore history'); | ||
form.style.cssText='display:flex;flex-wrap:wrap;gap:1rem;padding:1rem;border:1px solid var(--border-color-base,#777);border-radius:.6rem;margin-block:1rem'; | form.style.cssText='display:flex;flex-wrap:wrap;gap:1rem;padding:1rem;border:1px solid var(--border-color-base,#777);border-radius:.6rem;margin-block:1rem'; | ||
function field(label,key,type) { | function field(label,key,type) { | ||
var box=el('label',label,form);box.style.cssText='display:flex;flex-direction:column;gap:.35rem;min-width:10rem;flex:1'; | var box=el('label',label,form);box.style.cssText='display:flex;flex-direction:column;gap:.35rem;min-width:10rem;flex:1'; | ||
var input=el(type==='select'?'select':'input',null,box);input.id='av-timeline-'+key; | var input=el(type==='select'?'select':'input',null,box);input.id='av-timeline-'+key; | ||
input.setAttribute('aria-label',label); | |||
if(type!=='select')input.type=type; | if(type!=='select')input.type=type; | ||
input.style.cssText='font:inherit;padding:.55rem;border:1px solid #888;border-radius:.3rem;background:var(--color-surface-1,#fff);color:var(--color-base,#222);max-width:100%'; | input.style.cssText='font:inherit;padding:.55rem;border:1px solid #888;border-radius:.3rem;background:var(--color-surface-1,#fff);color:var(--color-base,#222);max-width:100%'; | ||
| Line 182: | Line 184: | ||
var matched; | var matched; | ||
try{matched=select(rows,state,currentYear);}catch(error){summary.textContent=error.message;results.replaceChildren();more.hidden=true;return;} | try{matched=select(rows,state,currentYear);}catch(error){summary.textContent=error.message;results.replaceChildren();more.hidden=true;return;} | ||
summary.textContent=(lifetime?'Current year: '+currentYear+' AG. Approximate birth year: '+(currentYear-Number(state.age)-1)+' | summary.textContent=(lifetime?'Current year: '+currentYear+' AG. Approximate birth year: '+(currentYear-Number(state.age)-1)+'\u2013'+(currentYear-Number(state.age))+' AG. ':'')+matched.length+' events match; showing '+Math.min(shown,matched.length)+'.'; | ||
help.textContent='Worldwide events stay included alongside relevant national and hometown history. Ages are approximate because birthdays and many event dates are unknown. '+(state.publicOnly?'Private and later-revealed information is excluded.':'Some results contain private or later-revealed information; these are not automatic character knowledge.')+' These are backstory possibilities, not events your character necessarily witnessed.'; | help.textContent='Worldwide events stay included alongside relevant national and hometown history. Ages are approximate because birthdays and many event dates are unknown. '+(state.publicOnly?'Private and later-revealed information is excluded.':'Some results contain private or later-revealed information; these are not automatic character knowledge.')+' These are backstory possibilities, not events your character necessarily witnessed.'; | ||
if(!state.majorOnly)help.textContent+=' Smaller gatherings and announced plans are also included.'; | if(!state.majorOnly)help.textContent+=' Smaller gatherings and announced plans are also included.'; | ||
| Line 190: | Line 192: | ||
matched.slice(0,shown).forEach(function(r){ | matched.slice(0,shown).forEach(function(r){ | ||
var card=el('div',null,results);card.className='av-timeline-result';card.style.cssText='border-inline-start:3px solid var(--color-progressive,#648dd8);padding:.6rem 1rem;margin-block:1rem'; | var card=el('div',null,results);card.className='av-timeline-result';card.style.cssText='border-inline-start:3px solid var(--color-progressive,#648dd8);padding:.6rem 1rem;margin-block:1rem'; | ||
var date=el('p',r.date+(lifetime?' | var date=el('p',r.date+(lifetime?' \u00b7 '+ageLabel(r,Number(state.age),currentYear):''),card);date.style.cssText='font-weight:600;margin-block:.15rem .5rem'; | ||
el('p',r.prose,card).style.marginBlock='.4rem'; | el('p',r.prose,card).style.marginBlock='.4rem'; | ||
if(r.visibility!=='public')el('p',r.visibility==='secret-at-time'?'Private at the time; do not assume your character knew this.':r.visibility==='later-revealed'?'Revealed later; the public disclosure date is not established here.':'Public knowledge has not been established for this account.',card); | if(r.visibility!=='public')el('p',r.visibility==='secret-at-time'?'Private at the time; do not assume your character knew this.':r.visibility==='later-revealed'?'Revealed later; the public disclosure date is not established here.':'Public knowledge has not been established for this account.',card); | ||
var context=[r.scope==='global'?'Worldwide':r.polities.join(' | var context=[r.scope==='global'?'Worldwide':r.polities.join(' \u00b7 '),r.towns.join(' \u00b7 '),r.arcs.join(' \u00b7 ')].filter(Boolean).join(' \u2014 '); | ||
if(context)el('small',context,card); | if(context)el('small',context,card); | ||
var line=el('div',null,card), link=el('a','Source record',line);link.href=mw.util.getUrl(r.page);link.setAttribute('aria-label','Source record for '+r.title); | var line=el('div',null,card), link=el('a','Source record',line);link.href=mw.util.getUrl(r.page);link.setAttribute('aria-label','Source record for '+r.title); | ||
| Line 203: | Line 205: | ||
return {worldYear:worldYear,normalise:normalise,nationMatch:nationMatch,hometownNations:hometownNations,select:select,ageLabel:ageLabel,collect:collect,mount:mount}; | return {worldYear:worldYear,normalise:normalise,nationMatch:nationMatch,hometownNations:hometownNations,select:select,ageLabel:ageLabel,collect:collect,mount:mount}; | ||
})); | })); | ||
// END AV TIMELINE (managed by A2TL) | |||
Latest revision as of 12:41, 17 November 2026
/* Any JavaScript here will be loaded for all users on every page load. */
// BEGIN AV TIMELINE (managed by A2TL)
/* Avatarverse timeline browser. Maintained through the A2TL wiki MCP in
* MediaWiki:Common.js. No external dependencies, account access or writes.
* Only runs on the two timeline explorer pages. Calendar constants match Time.java.
*/
(function (factory) {
'use strict';
var model = factory();
if (typeof window !== 'undefined' && typeof mw !== 'undefined') mw.loader.using('mediawiki.util').then(function () {mw.hook('wikipage.content').add(function () { model.mount(); });});
else if (typeof module === 'object' && module.exports) module.exports = model;
}(function () {
'use strict';
var EPOCH = 1711339200000, YEAR_MS = 4838400000;
var PAGE_SIZE = 20;
function worldYear(now) { return 164 + Math.floor((now - EPOCH) / YEAR_MS); }
function list(value) { return String(value || '').split(';').map(function (s) { return s.trim(); }).filter(Boolean); }
function plain(value) {
return String(value || '').replace(/\[\[([^\]|]+)\|([^\]]+)\]\]/g, '$2').replace(/\[\[([^\]]+)\]\]/g, '$1').replace(/'{2,3}/g, '');
}
function normalise(row) {
var start = Number(row.YearStart), end = Number(row.YearEnd || row.YearStart);
if (!row.EventID || !Number.isInteger(start) || !Number.isInteger(end) || end < start) throw new Error('Invalid timeline record.');
var date=plain(row.DateText);
// Some legacy records retain real-world heading labels in DateText. Those
// are provenance, not in-world dates; keep the stored value, show AG instead.
if (!/\bAG\b/.test(date)) date=start===end?start+' AG':start+'\u2013'+end+' AG';
return { id:row.EventID, start:start, end:end, date:date,
title:plain(row.Title), prose:plain(row.Description) || plain(row.Title),
polities:list(row.Polities), towns:list(row.Locations), arcs:list(row.Arcs), tags:list(row.Subtags),
scope:row.Scope, visibility:row.Visibility, status:row.Status, type:row.PrimaryType,
major:/\bBackstory importance: major\./.test(row.EditorialNotes || ''),
unverified:/\bBackstory importance: unverified\./.test(row.EditorialNotes || ''),
page:row.Page || row._pageName || 'Timeline/Data/'+start, index:Number(row.SourceIndex) || 0 };
}
function nationMatch(polities, nation) {
if (!nation) return true;
if (polities.indexOf(nation)>=0) return true;
// An undivided Water Tribe record concerns both poles. A record explicitly
// assigned to only one pole does not automatically concern the other.
return /^(Northern|Southern) Water Tribe$/.test(nation) && polities.indexOf('Water Tribe')>=0
&& !polities.some(function (p) { return /^(Northern|Southern) Water Tribe$/.test(p); });
}
function hometownNations(town, year) {
town=String(town || '').trim().toLocaleLowerCase();
if (town==='republic city') {
if (year>=168 || year<110) return ['Earth Kingdom'];
if (year===121 || year===122) return ['United Republic of Nations','Fire Nation'];
if (year===134 || year===135) return ['United Republic of Nations','Sun Warriors'];
return ['United Republic of Nations'];
}
if (town==='nuuna' && year>=176) return ['Air Nation','Fire Nation'];
var homes={
'ba sing se':'Earth Kingdom','omashu':'Earth Kingdom','gaoling':'Earth Kingdom','zaofu':'Earth Kingdom','senlin':'Earth Kingdom','bei da feng':'Earth Kingdom','zeizhou':'Earth Kingdom','kyoshi island':'Earth Kingdom','yu dao':'Earth Kingdom',
'hikari':'Fire Nation','caldera city':'Fire Nation','ember island':'Fire Nation','takemi':'Fire Nation','takemaru':'Fire Nation','furushiki':'Fire Nation','noriko village':'Fire Nation','kayamoto island':'Fire Nation','hiseki':'Fire Nation','crescent island':'Fire Nation','imagawa':'Fire Nation',
'northern air temple':'Air Nation','southern air temple':'Air Nation','western air temple':'Air Nation','eastern air temple':'Air Nation','air temple island':'Air Nation','floating sands':'Air Nation','whale tail island':'Air Nation',
'agna qel\u2019a':'Northern Water Tribe','nunatak':'Northern Water Tribe','ikiaq':'Northern Water Tribe','anana tun\u2019ila':'Southern Water Tribe',
'masked village':'Foggy Swamp Tribe','hanging village':'Foggy Swamp Tribe','banyan grove':'Foggy Swamp Tribe','radish lotus village':'Foggy Swamp Tribe','bao grove':'Foggy Swamp Tribe',
'ninuno':'Sun Warriors','la bay\u0101n':'Sun Warriors','hortezuca':'Sun Warriors','bianqui':'Sun Warriors','rakanet':'Sun Warriors','arangoy':'Sun Warriors',
'misty palms oasis':'Sand Tribes','si wong desert':'Sand Tribes','itgel':'Sand Tribes','kherdu arena':'Sand Tribes'
};
return homes[town]?[homes[town]]:[];
}
function select(rows, state, currentYear) {
var age = Number(state.age);
if (state.mode==='lifetime' && (!Number.isInteger(age) || age<0 || age>130 || state.age==='')) throw new Error('Enter a whole-number age from 0 to 130.');
var from = state.mode==='lifetime'?currentYear-age-1:Number(state.from);
var to = state.mode==='lifetime'?currentYear:Number(state.to);
if (!Number.isInteger(from) || !Number.isInteger(to) || from>to) throw new Error('The first year must be no later than the last year.');
var query = (state.search || '').trim().toLocaleLowerCase();
var hometown = rows.flatMap(function(r){return r.towns;}).find(function(t){return t.toLocaleLowerCase()===(state.town || '').trim().toLocaleLowerCase();}) || (state.town || '').trim();
return rows.filter(function (r) {
if (r.unverified || r.start>Math.min(to,currentYear) || r.end<from) return false;
if (state.publicOnly && r.visibility!=='public') return false;
if (state.majorOnly && !r.major) return false;
if (state.arc && r.arcs.indexOf(state.arc)<0) return false;
if (state.type && state.type!==r.type) return false;
if (state.nation || state.town) {
var global = r.scope==='global';
var town = !!hometown && r.towns.indexOf(hometown)>=0;
var national = r.scope!=='local' && (state.nation?nationMatch(r.polities,state.nation):!state.town);
var historical = r.scope!=='local' && hometownNations(hometown,r.start).some(function (p) { return nationMatch(r.polities,p); });
var nearby = !state.town && state.nation && nationMatch(r.polities,state.nation);
if (!global && !town && !national && !historical && !nearby) return false;
}
return !query || [r.title,r.prose,r.date,r.polities.join(' '),r.towns.join(' '),r.arcs.join(' '),r.tags.join(' ')].join(' ').toLocaleLowerCase().indexOf(query)>=0;
}).sort(function (a,b) { return a.start-b.start || a.index-b.index || a.id.localeCompare(b.id); });
}
function ageLabel(row, age, currentYear) {
var low = Math.max(0,row.start-(currentYear-age)-1), high = Math.min(age,Math.max(0,row.end-(currentYear-age-1)));
return high<=1?'Around your birth':low===high?'About age '+low:'About age '+low+'\u2013'+high;
}
async function collect(request) {
var rows=[], seen=new Set();
for (var offset=0;;offset+=500) {
var data=await request(offset);
if (!data || !Array.isArray(data.cargoquery)) throw new Error('Timeline data could not be read.');
for (var entry of data.cargoquery) {
var row=normalise(entry.title);
if(seen.has(row.id)) throw new Error('Duplicate timeline records; loading stopped.');
seen.add(row.id);rows.push(row);
}
if(data.cargoquery.length<500) return rows;
}
}
function mount() {
var page = mw.config.get('wgPageName');
if (page!=='Timeline/Character_lifetime' && page!=='Timeline/Cargo_draft' && page!=='Timeline/Cargo draft') return;
var root=document.getElementById('av-timeline-explorer');
if (!root || root.dataset.mounted) return;
root.dataset.mounted='true';
var lifetime=page==='Timeline/Character_lifetime', currentYear=worldYear(Date.now());
var fallback=document.getElementById('av-timeline-fallback');
var loading=document.createElement('p');loading.setAttribute('role','status');loading.textContent='Loading history\u2026';root.appendChild(loading);
var endpoint=new URL(mw.util.wikiScript('api'),location.origin);
collect(async function (offset) {
var url=new URL(endpoint);
Object.entries({action:'cargoquery',format:'json',formatversion:'2',tables:'TimelineEvents',
fields:'EventID,YearStart,YearEnd,DateText,Title,Description,PrimaryType,Subtags,Arcs,Polities,Locations,Scope,Visibility,Status,EditorialNotes,SourceIndex',
order_by:'EventID',limit:'500',offset:String(offset)}).forEach(function (pair) {url.searchParams.set(pair[0],pair[1]);});
// Public data needs no account or bot session. Do not log API diagnostics.
var response=await fetch(url,{credentials:'omit',signal:AbortSignal.timeout(30000)});
if(!response.ok) throw new Error('Timeline data is temporarily unavailable.');
var result=await response.json();return {cargoquery:result.cargoquery};
}).then(function (rows) {build(rows);}).catch(function () {
loading.textContent='The interactive view could not load. Use the searchable table below, or try again later.';
});
function build(rows) {
var state={mode:lifetime?'lifetime':'all',age:'20',from:'100',to:String(currentYear),nation:'',town:'',majorOnly:lifetime,publicOnly:true,search:'',arc:'',type:''};
var params=new URLSearchParams(location.search);
['age','nation','town','search','from','to','arc','type'].forEach(function (key) {if(params.has(key))state[key]=params.get(key);});
if(params.has('major'))state.majorOnly=params.get('major')!=='0';
if(params.has('public'))state.publicOnly=params.get('public')!=='0';
var shown=PAGE_SIZE;
root.replaceChildren();
function el(tag,text,parent) {var node=document.createElement(tag);if(text)node.textContent=text;if(parent)parent.appendChild(node);return node;}
var form=el('form',null,root);form.setAttribute('aria-label',lifetime?'Your character\u2019s lifetime':'Explore history');
form.style.cssText='display:flex;flex-wrap:wrap;gap:1rem;padding:1rem;border:1px solid var(--border-color-base,#777);border-radius:.6rem;margin-block:1rem';
function field(label,key,type) {
var box=el('label',label,form);box.style.cssText='display:flex;flex-direction:column;gap:.35rem;min-width:10rem;flex:1';
var input=el(type==='select'?'select':'input',null,box);input.id='av-timeline-'+key;
input.setAttribute('aria-label',label);
if(type!=='select')input.type=type;
input.style.cssText='font:inherit;padding:.55rem;border:1px solid #888;border-radius:.3rem;background:var(--color-surface-1,#fff);color:var(--color-base,#222);max-width:100%';
input.value=state[key];input.addEventListener('input',function () {state[key]=input.value;shown=PAGE_SIZE;render();});return input;
}
if(lifetime){var age=field('Character age','age','number');age.min='0';age.max='130';age.step='1';age.required=true;}
else {field('From year AG','from','number');field('Through year AG','to','number');}
var nation=field('Home nation / tribe (optional)','nation','select');
option(nation,'','Anywhere');
Array.from(new Set(rows.flatMap(function(r){return r.polities;}))).sort().forEach(function(p){option(nation,p,p);});nation.value=state.nation;
var town=field('Home town / place (optional)','town','text');town.setAttribute('list','av-timeline-towns');
var towns=el('datalist',null,form);towns.id='av-timeline-towns';
Array.from(new Set(rows.flatMap(function(r){return r.towns;}))).sort().forEach(function(p){option(towns,p,p);});
var major=checkbox('Major events only','majorOnly',form);
checkbox('Public knowledge only','publicOnly',form);
var advanced=el('details',null,root);el('summary','Search and more filters',advanced);
var advancedBox=el('div',null,advanced);advancedBox.style.cssText='display:flex;flex-wrap:wrap;gap:1rem;margin-block:1rem';
// Reuse the same field builder, then move each label into the disclosure.
var search=field('Search people, events or places','search','search');advancedBox.appendChild(search.parentElement);
var arc=field('Storyline','arc','select');option(arc,'','All storylines');
Array.from(new Set(rows.flatMap(function(r){return r.arcs;}))).sort().forEach(function(p){option(arc,p,p);});arc.value=state.arc;advancedBox.appendChild(arc.parentElement);
var type=field('Event category','type','select');option(type,'','All categories');
var types={GOV:'Government',DIP:'Diplomacy',TERR:'Borders and territory',CONFLICT:'Conflict',LAW:'Law and crime',CULT:'Culture',SPIRIT:'Spiritual affairs',TECH:'Technology',ENV:'Environment',SOC:'Society',PERS:'Personal history',UNCLASSIFIED:'Other'};
Object.entries(types).forEach(function(p){option(type,p[0],p[1]);});type.value=state.type;advancedBox.appendChild(type.parentElement);
var reset=el('button','Reset filters',advancedBox);reset.type='button';reset.addEventListener('click',function(){location.href=mw.util.getUrl(page);});
var share=el('button','Copy link to this view',advancedBox);share.type='button';
share.addEventListener('click',async function(){
var url=new URL(location.href);url.search='';
['age','nation','town','search','from','to','arc','type'].forEach(function(k){if(state[k])url.searchParams.set(k,state[k]);});
url.searchParams.set('major',state.majorOnly?'1':'0');url.searchParams.set('public',state.publicOnly?'1':'0');
try{await navigator.clipboard.writeText(url.href);share.textContent='Link copied';}catch(e){share.textContent='Select and copy this link';var link=el('input',null,advancedBox);link.value=url.href;link.readOnly=true;link.select();}
});
form.addEventListener('submit',function(e){e.preventDefault();render();});
var summary=el('p',null,root);summary.setAttribute('role','status');summary.setAttribute('aria-live','polite');
var help=el('p',null,root);help.style.cssText='font-size:.9em;opacity:.85';
var results=el('div',null,root);results.id='av-timeline-results';
var more=el('button','Show 20 more events',root);more.type='button';more.addEventListener('click',function(){shown+=PAGE_SIZE;render();});
if(fallback)fallback.hidden=true;
render();
function option(select,value,label){var o=el('option',label,select);o.value=value;}
function checkbox(label,key,parent){var box=el('label',null,parent);box.style.cssText='align-self:end;padding-block:.6rem';var input=el('input',null,box);input.type='checkbox';input.checked=state[key];box.appendChild(document.createTextNode(' '+label));input.addEventListener('change',function(){state[key]=input.checked;shown=PAGE_SIZE;render();});return input;}
function render(){
var matched;
try{matched=select(rows,state,currentYear);}catch(error){summary.textContent=error.message;results.replaceChildren();more.hidden=true;return;}
summary.textContent=(lifetime?'Current year: '+currentYear+' AG. Approximate birth year: '+(currentYear-Number(state.age)-1)+'\u2013'+(currentYear-Number(state.age))+' AG. ':'')+matched.length+' events match; showing '+Math.min(shown,matched.length)+'.';
help.textContent='Worldwide events stay included alongside relevant national and hometown history. Ages are approximate because birthdays and many event dates are unknown. '+(state.publicOnly?'Private and later-revealed information is excluded.':'Some results contain private or later-revealed information; these are not automatic character knowledge.')+' These are backstory possibilities, not events your character necessarily witnessed.';
if(!state.majorOnly)help.textContent+=' Smaller gatherings and announced plans are also included.';
if(lifetime&¤tYear-Number(state.age)-1<100)help.textContent+=' This archive begins in 100 AG; earlier history is not covered here.';
results.replaceChildren();
if(!matched.length){el('p','No matching events. Try clearing the town or nation, broadening the search, or including smaller events.',results);}
matched.slice(0,shown).forEach(function(r){
var card=el('div',null,results);card.className='av-timeline-result';card.style.cssText='border-inline-start:3px solid var(--color-progressive,#648dd8);padding:.6rem 1rem;margin-block:1rem';
var date=el('p',r.date+(lifetime?' \u00b7 '+ageLabel(r,Number(state.age),currentYear):''),card);date.style.cssText='font-weight:600;margin-block:.15rem .5rem';
el('p',r.prose,card).style.marginBlock='.4rem';
if(r.visibility!=='public')el('p',r.visibility==='secret-at-time'?'Private at the time; do not assume your character knew this.':r.visibility==='later-revealed'?'Revealed later; the public disclosure date is not established here.':'Public knowledge has not been established for this account.',card);
var context=[r.scope==='global'?'Worldwide':r.polities.join(' \u00b7 '),r.towns.join(' \u00b7 '),r.arcs.join(' \u00b7 ')].filter(Boolean).join(' \u2014 ');
if(context)el('small',context,card);
var line=el('div',null,card), link=el('a','Source record',line);link.href=mw.util.getUrl(r.page);link.setAttribute('aria-label','Source record for '+r.title);
});
more.hidden=shown>=matched.length;
}
}
}
return {worldYear:worldYear,normalise:normalise,nationMatch:nationMatch,hometownNations:hometownNations,select:select,ageLabel:ageLabel,collect:collect,mount:mount};
}));
// END AV TIMELINE (managed by A2TL)