Files
bpq_gui/map-refresh-ui.test.mjs

115 lines
9.4 KiB
JavaScript

import test from 'node:test';
import assert from 'node:assert/strict';
import vm from 'node:vm';
import {readFileSync} from 'node:fs';
function element(){
let html='';
return {writes:0,value:'',defaultValue:'',dataset:{},attributes:{},clientWidth:700,clientHeight:440,hidden:false,textContent:'',
get innerHTML(){return html;},set innerHTML(value){html=value;this.writes++;},
querySelector(){return element();},querySelectorAll(){return [];},setAttribute(k,v){this.attributes[k]=v;},
addEventListener(){},append(){},prepend(){},after(){},contains(){return false;},classList:{toggle(){}}};
}
function harness(file,exportCode,api=async()=>{}){
const nodes=new Map(),$=selector=>{if(!nodes.has(selector))nodes.set(selector,element());return nodes.get(selector);};
const context=vm.createContext({$, $$:()=>[],window:{},document:{hidden:false,activeElement:null,createElement:element,addEventListener(){},getElementById(){return null;}},
BPQI18n:{t:s=>s,locale:()=> 'en-GB'},csrf:'test',page:'none',navigate(){},api,fetch:async()=>({ok:true,json:async()=>({features:[]})}),
size:n=>String(n),mailTimezone:()=> 'UTC',esc:s=>String(s??''),toast(){},setInterval(){},setTimeout(){},requestAnimationFrame:f=>f()});
vm.runInContext(readFileSync(new URL('./public/aprs-symbols.js',import.meta.url),'utf8'),context);
const source=readFileSync(new URL('./public/'+file,import.meta.url),'utf8');
vm.runInContext(source.replace(/\}\)\(\);\s*$/,exportCode+'\n})();'),context);
return {context,$,fixture:context.fixture};
}
function leaflet(){
const state={created:[],fits:0,removals:[],zoom:9},map={setView(){return this;},fitBounds(bounds,options){state.fits++;state.bounds=bounds;state.fitOptions=options;return this;},getZoom:()=>state.zoom};
const layers={addTo(){return this;},removeLayer(m){state.removals.push(m);}};
function marker(point,options){
let popup='',tooltip='';const m={point,options,moves:0,popupWrites:0,open:false,
bindTooltip(s){tooltip=s;return this;},bindPopup(s,o){popup=s;this.popupOptions=o;return this;},on(){return this;},addTo(){return this;},
setIcon(icon){this.options.icon=icon;this.iconWrites=(this.iconWrites||0)+1;return this;},getLatLng(){return {lat:this.point[0],lng:this.point[1]};},setLatLng(p){this.point=p;this.moves++;return this;},setStyle(o){Object.assign(this.options,o);},
getPopup(){return {getContent:()=>popup};},setPopupContent(s){popup=s;this.popupWrites++;},
getTooltip(){return {getContent:()=>tooltip};},setTooltipContent(s){tooltip=s;},openPopup(){this.open=true;}};
state.created.push(m);return m;
}
return {state,L:{map:()=>map,tileLayer:()=>({addTo(){}}),layerGroup:()=>layers,circleMarker:marker,marker,divIcon:options=>options,latLngBounds:p=>p}};
}
const station=(call,lat=45)=>({call,transport:'Radio',position:{lat,lon:9,locator:'JN45MM'},lastAt:'2026-01-01T12:00:00Z',status:'On air',lastBody:'',path:'TEST',services:['BBS']});
const aprsData=()=>({stations:[station('N0AAA'),station('N0BBB',46)],own:{call:'N0LOCAL',position:{lat:44,lon:9}}});
test('APRS polling keeps marker identity, popup and viewport; changed positions update in place',()=>{
const h=harness('aprs-activity.js','globalThis.fixture={setData(value){data=value;},renderMap};'),l=leaflet();
h.context.L=l.L;h.context.window.L=l.L;h.context.page='aprs';h.$('#aprs-source').value='Radio';
let data=aprsData();h.fixture.setData(data);h.fixture.renderMap();
const [first,second,own]=l.state.created;first.openPopup();
for(let i=0;i<5;i++){h.fixture.setData(structuredClone(data));h.fixture.renderMap();}
assert.equal(l.state.created.length,3);assert.equal(l.state.fits,1);assert.equal(l.state.removals.length,0);
assert.equal(first.open,true);assert.equal(first.moves,0);assert.equal(first.popupWrites,0);assert.equal(own.moves,0);
data=structuredClone(data);data.stations[0].position.lat=45.1;data.stations[0].status='Updated';h.fixture.setData(data);h.fixture.renderMap();
assert.equal(first.moves,1);assert.equal(first.popupWrites,1);assert.equal(first.open,true);assert.equal(second.moves,0);assert.equal(l.state.fits,1);
assert.equal(first.popupOptions.autoPan,false);
data.stations[0].position.symset='W';data.stations[0].position.symbol='#';h.fixture.setData(data);h.fixture.renderMap();
assert.equal(first.iconWrites,1);assert.match(first.options.icon.html,/alternate.*overlay/);assert.equal(first.open,true);
h.fixture.setData(structuredClone(data));h.fixture.renderMap();assert.equal(first.iconWrites,1);assert.equal(l.state.created.length,3);assert.equal(l.state.fits,1);
});
test('APRS removes only stations outside the filter and retains the local marker',()=>{
const h=harness('aprs-activity.js','globalThis.fixture={setData(value){data=value;},renderMap};'),l=leaflet();
h.context.L=l.L;h.context.window.L=l.L;h.context.page='aprs';const data=aprsData();h.fixture.setData(data);h.fixture.renderMap();
const [first,second]=l.state.created;h.$('#aprs-search').value='N0AAA';h.fixture.renderMap();
assert.deepEqual(l.state.removals,[second]);assert.equal(l.state.created.length,3);assert.equal(first.moves,0);assert.equal(l.state.fits,1);
});
const journalData=()=>({since:'2026-01-01',warnings:['fixture.log: partial tail'],limited:false,own:{call:'N0LOCAL',position:{lat:44,lon:9}},stations:[station('N0AAA')],sessions:[{id:'one',call:'N0AAA',startedAt:new Date().toISOString(),connectedAt:new Date().toISOString(),service:'BBS',direction:'incoming',transport:'Radio',status:'complete',duration:12}]});
test('journal loads without the removed station map and preserves coverage warnings',async()=>{
const h=harness('journal.js','globalThis.fixture={load};',async()=>journalData());
h.context.page='journal';h.$('#journal-period').value='7';await h.fixture.load();
assert.equal(h.$('#journal-warning').hidden,false);assert.match(h.$('#journal-warning-detail').textContent,/partial tail/);
});
test('background API polls stay quiet, while interactive requests finish the busy indicator even on error',async()=>{
let starts=0,finishes=0,request,fail=false;
const context=vm.createContext({FormData,csrf:'test',window:{BPQBusy:{start(){starts++;return ()=>finishes++;}}},
fetch:async(url,options)=>{request=options;if(fail)throw Error('offline');return {ok:true,json:async()=>({ok:true})};}});
const source=readFileSync(new URL('./public/app.js',import.meta.url),'utf8').split('\n').find(line=>line.startsWith('async function api('));
vm.runInContext(source,context);
await context.api('/journal',{busy:false});assert.equal(starts,0);assert.equal(finishes,0);assert.equal('busy' in request,false);
await context.api('/journal');assert.equal(starts,1);assert.equal(finishes,1);
fail=true;await assert.rejects(context.api('/journal'),/offline/);assert.equal(starts,2);assert.equal(finishes,2);
});
test('APRS density fit excludes isolated distant stations and favours a tied group near home',()=>{
const h=harness('aprs-activity.js','globalThis.fixture={densePositions,distanceKm,localBounds};');
const home={lat:45.57,lon:9.13},near=[home,{lat:45.7,lon:9.4},{lat:45.4,lon:9.3}],remote=[{lat:51.5,lon:-.1},{lat:51.6,lon:-.2},{lat:51.4,lon:0}];
const result=h.fixture.densePositions([...remote,...near,{lat:30,lon:120},null,{lat:NaN,lon:4}],home);
assert.equal(result.length,4);assert.ok(result.every(p=>h.fixture.distanceKm(home,p)<100));
assert.equal(h.fixture.densePositions([],null).length,0);
assert.equal(h.fixture.densePositions([],home).length,1);
});
test('APRS opens at a 30 km radius and refresh does not reset a manually selected density fit',()=>{
const h=harness('aprs-activity.js','globalThis.fixture={setData(value){data=value;},renderMap,fit,fitLocal,distanceKm};'),l=leaflet();
h.context.L=l.L;h.context.window.L=l.L;h.context.page='aprs';
const data=aprsData();data.own.position={lat:45.57,lon:9.13};data.stations.push(station('DISTANT',-30));
h.fixture.setData(data);h.fixture.renderMap();
const [southwest,northeast]=l.state.bounds,home=data.own.position;
assert.ok(Math.abs(h.fixture.distanceKm(home,{lat:southwest[0],lon:home.lon})-30)<.001);
assert.ok(Math.abs(h.fixture.distanceKm(home,{lat:home.lat,lon:northeast[1]})-30)<.01);
assert.equal(h.$('#aprs-map-local').attributes['aria-pressed'],'true');assert.equal((southwest[0]+northeast[0])/2,home.lat);assert.equal(h.$('#aprs-map-local').disabled,false);
h.fixture.fit();assert.equal(h.$('#aprs-map-fit').attributes['aria-pressed'],'true');const bounds=JSON.stringify(l.state.bounds);assert.ok(l.state.bounds.every(p=>p[0]>0));
h.fixture.setData(structuredClone(data));h.fixture.renderMap();assert.equal(l.state.fits,2);assert.equal(JSON.stringify(l.state.bounds),bounds);
h.fixture.fitLocal();assert.equal(l.state.fits,3);
data.own.position=null;h.fixture.setData(data);h.fixture.renderMap();assert.equal(h.$('#aprs-map-local').disabled,true);h.fixture.fitLocal();assert.equal(l.state.fits,3);
});
test('APRS popups show decoded Mic-E values and keep encoded bytes only in a collapsed original-packet detail',()=>{
const h=harness('aprs-activity.js','globalThis.fixture={popup,stationDescription};');
const body='`'+String.fromCharCode(127)+'^U!n^>/"5J}';
const s={...station('N0TEST'),status:'',lastBody:body};
const description=h.fixture.stationDescription(s);assert.equal(description,'Mic-E · 107 km/h · 266° · Quota 142 m');
const html=h.fixture.popup(s);assert.match(html,/<details class="aprs-raw-packet"><summary>Pacchetto originale/);
assert.ok(html.includes(String.fromCharCode(92)+'x7f'));assert.ok(!html.includes(String.fromCharCode(127)));
assert.equal(s.lastBody,body);
});