From bd8e521711fda943fa8f0f96c6aac13eb7abd9c5 Mon Sep 17 00:00:00 2001 From: alberto Date: Thu, 29 Oct 2026 17:14:53 +0100 Subject: [PATCH] Fix detached controls on LAN HTTP and late-loaded views --- detach.test.mjs | 114 +++++++++++++++++++++++++--------------------- public/detach.js | 17 ++++--- public/index.html | 2 +- 3 files changed, 74 insertions(+), 59 deletions(-) diff --git a/detach.test.mjs b/detach.test.mjs index 9bfd577..a711b2d 100644 --- a/detach.test.mjs +++ b/detach.test.mjs @@ -1,52 +1,64 @@ -import test from 'node:test'; -import assert from 'node:assert/strict'; -import vm from 'node:vm'; -import {readFileSync} from 'node:fs'; -const source=readFileSync(new URL('./public/detach.js',import.meta.url),'utf8'); -function harness(search='',shared=new Map()){ - const docEvents={},events={},sections={},calls=[];let serial=0,tick,popup; - function element(){const children=new Map();return {hidden:false,dataset:{},textContent:'',className:'',innerHTML:'',classes:new Set(), +import test from 'node:test'; +import assert from 'node:assert/strict'; +import vm from 'node:vm'; +import {readFileSync} from 'node:fs'; +const source=readFileSync(new URL('./public/detach.js',import.meta.url),'utf8'); +function harness(search='',shared=new Map(),options={}){ + const docEvents={},events={},sections={},calls=[];let serial=0,tick,popup; + function element(){const children=new Map();return {hidden:false,dataset:{},textContent:'',className:'',innerHTML:'',classes:new Set(), setAttribute(name,value){this[name]=value;},classList:{toggle(name,on){this.owner.classes[on?'add':'delete'](name);}},append(child){this.child=child;}, - querySelector(selector){if(selector==='.detached-placeholder')return this.child||null;if(!children.has(selector))children.set(selector,element());return children.get(selector);}, - querySelectorAll(){return [this.querySelector('first'),this.querySelector('second')];}};} - for(const id of ['terminal','aprs','monitor','chat']){sections[id]=element();sections[id].classList.owner=sections[id];} - const main={hidden:false};const document={body:{append(node){calls.push(['notice',node.className]);}},querySelector:()=>main,readyState:'complete',documentElement:{dataset:{}},getElementById:id=>sections[id],createElement:element,addEventListener:(name,fn)=>docEvents[name]=fn}; - const window={name:'',addEventListener:(name,fn)=>events[name]=fn,focus:()=>calls.push('focus'),close:()=>calls.push('close'), - open:(...args)=>{calls.push(args);popup={closed:false,focus(){},close(){this.closed=true;}};return popup;}}; - const location={pathname:'/',search,hash:'',assign:url=>calls.push(['assign',url])}; - const context=vm.createContext({window,document,location,URLSearchParams,crypto:{randomUUID:()=>String(++serial)}, - localStorage:{getItem:key=>shared.get(key)||null,setItem:(key,value)=>shared.set(key,value),removeItem:key=>shared.delete(key)}, - Date,Set,Map,BPQI18n:{t:s=>s},toast:text=>calls.push(['toast',text]),navigate:id=>calls.push(['navigate',id]),setInterval:fn=>{tick=fn;}}); - vm.runInContext(source,context);docEvents.DOMContentLoaded(); - return {api:window.BPQDetached,window,document,docEvents,events,sections,calls,shared,main,tick:()=>tick(),popup:()=>popup}; -} -test('a page shows courtesy only after its detached view is ready, and another page stays usable',()=>{ - const h=harness();h.api.open('aprs');assert.equal(h.api.isAway('aprs'),false); - assert.match(h.calls[0][0],/^\/\?detached=aprs&window=\d+#aprs$/); - h.shared.set('bpq-detached:aprs',JSON.stringify({owner:'2',at:Date.now()}));h.tick(); - assert.equal(h.sections.aprs.child.hidden,false);assert.equal(h.api.shouldPoll('aprs'),false);assert.equal(h.api.shouldPoll('chat'),true); - assert.equal(h.sections.aprs.classes.has('section-detached-away'),true); - h.api.dock('aprs');assert.equal(h.sections.aprs.child.hidden,true);assert.equal(h.api.shouldPoll('aprs'),true);assert.equal(h.popup().closed,true); -}); -test('closing a child restores its parent and stale records cannot strand a page on the courtesy screen',()=>{ - const h=harness();h.api.open('monitor');h.shared.set('bpq-detached:monitor',JSON.stringify({owner:'2',at:Date.now()}));h.tick(); - h.popup().closed=true;h.tick();assert.equal(h.api.isAway('monitor'),false);assert.equal(h.sections.monitor.child.hidden,true); - h.shared.set('bpq-detached:chat',JSON.stringify({owner:'old',at:Date.now()-130000}));h.tick();assert.equal(h.api.isAway('chat'),false); -}); -test('blocked popups keep the embedded view and never claim a detached session',()=>{ - const h=harness();h.window.open=()=>null;h.api.open('chat');assert.equal(h.api.isAway('chat'),false);assert.equal(h.shared.has('bpq-detached:chat'),false);assert.match(h.calls[0][1],/popup/); -}); -test('a standalone page claims just its service, releases on close and never reconnects or disconnects BPQ',()=>{ - const shared=new Map(),h=harness('?detached=chat&window=child',shared);h.docEvents['station-ready'](); - assert.equal(h.api.view,'chat');assert.equal(h.api.shouldPoll('chat'),true);assert.equal(h.api.shouldPoll('aprs'),false); - assert.equal(JSON.parse(shared.get('bpq-detached:chat')).owner,'child');assert.equal(h.document.documentElement.dataset.detachedView,'chat'); - h.events.pagehide();assert.equal(shared.has('bpq-detached:chat'),false);h.tick();assert.equal(shared.has('bpq-detached:chat'),false); - assert.ok(h.calls.every(call=>call[0]==='navigate')); -}); - - -test('a dock request stops the detached view even when its browser refuses scripted window closing',()=>{ - const h=harness('?detached=monitor&window=child');h.docEvents['station-ready'](); - h.events.storage({key:'bpq-detached-command',newValue:JSON.stringify({id:'monitor',action:'dock',at:Date.now()})}); - assert.equal(h.shared.has('bpq-detached:monitor'),false);assert.equal(h.api.shouldPoll('monitor'),false);assert.equal(h.main.hidden,true);assert.ok(h.calls.includes('close')); -}); + querySelector(selector){if(selector==='.detached-placeholder')return this.child||null;if(!children.has(selector))children.set(selector,element());return children.get(selector);}, + querySelectorAll(){return [this.querySelector('first'),this.querySelector('second')];}};} + for(const id of ['terminal','aprs','monitor','chat']){sections[id]=element();sections[id].classList.owner=sections[id];} + const main={hidden:false};const document={body:{append(node){calls.push(['notice',node.className]);}},querySelector:()=>main,readyState:'complete',documentElement:{dataset:{}},getElementById:id=>options.late?.includes(id)?null:sections[id],createElement:element,addEventListener:(name,fn)=>docEvents[name]=fn}; + const window={name:'',addEventListener:(name,fn)=>events[name]=fn,focus:()=>calls.push('focus'),close:()=>calls.push('close'), + open:(...args)=>{calls.push(args);popup={closed:false,focus(){},close(){this.closed=true;}};return popup;}}; + const location={pathname:'/',search,hash:'',assign:url=>calls.push(['assign',url])}; + const context=vm.createContext({window,document,location,URLSearchParams,crypto:options.insecure?{}:{randomUUID:()=>String(++serial)}, + localStorage:{getItem:key=>shared.get(key)||null,setItem:(key,value)=>shared.set(key,value),removeItem:key=>shared.delete(key)}, + Date,Set,Map,BPQI18n:{t:s=>s},toast:text=>calls.push(['toast',text]),navigate:id=>calls.push(['navigate',id]),setInterval:fn=>{tick=fn;}}); + vm.runInContext(source,context);docEvents.DOMContentLoaded(); + return {api:window.BPQDetached,window,document,docEvents,events,sections,calls,shared,main,tick:()=>tick(),popup:()=>popup}; +} +test('a page shows courtesy only after its detached view is ready, and another page stays usable',()=>{ + const h=harness();h.api.open('aprs');assert.equal(h.api.isAway('aprs'),false); + assert.match(h.calls[0][0],/^\/\?detached=aprs&window=\d+#aprs$/); + h.shared.set('bpq-detached:aprs',JSON.stringify({owner:'2',at:Date.now()}));h.tick(); + assert.equal(h.sections.aprs.child.hidden,false);assert.equal(h.api.shouldPoll('aprs'),false);assert.equal(h.api.shouldPoll('chat'),true); + assert.equal(h.sections.aprs.classes.has('section-detached-away'),true); + h.api.dock('aprs');assert.equal(h.sections.aprs.child.hidden,true);assert.equal(h.api.shouldPoll('aprs'),true);assert.equal(h.popup().closed,true); +}); +test('closing a child restores its parent and stale records cannot strand a page on the courtesy screen',()=>{ + const h=harness();h.api.open('monitor');h.shared.set('bpq-detached:monitor',JSON.stringify({owner:'2',at:Date.now()}));h.tick(); + h.popup().closed=true;h.tick();assert.equal(h.api.isAway('monitor'),false);assert.equal(h.sections.monitor.child.hidden,true); + h.shared.set('bpq-detached:chat',JSON.stringify({owner:'old',at:Date.now()-130000}));h.tick();assert.equal(h.api.isAway('chat'),false); +}); +test('blocked popups keep the embedded view and never claim a detached session',()=>{ + const h=harness();h.window.open=()=>null;h.api.open('chat');assert.equal(h.api.isAway('chat'),false);assert.equal(h.shared.has('bpq-detached:chat'),false);assert.match(h.calls[0][1],/popup/); +}); +test('a standalone page claims just its service, releases on close and never reconnects or disconnects BPQ',()=>{ + const shared=new Map(),h=harness('?detached=chat&window=child',shared);h.docEvents['station-ready'](); + assert.equal(h.api.view,'chat');assert.equal(h.api.shouldPoll('chat'),true);assert.equal(h.api.shouldPoll('aprs'),false); + assert.equal(JSON.parse(shared.get('bpq-detached:chat')).owner,'child');assert.equal(h.document.documentElement.dataset.detachedView,'chat'); + h.events.pagehide();assert.equal(shared.has('bpq-detached:chat'),false);h.tick();assert.equal(shared.has('bpq-detached:chat'),false); + assert.ok(h.calls.every(call=>call[0]==='navigate')); +}); + + +test('a dock request stops the detached view even when its browser refuses scripted window closing',()=>{ + const h=harness('?detached=monitor&window=child');h.docEvents['station-ready'](); + h.events.storage({key:'bpq-detached-command',newValue:JSON.stringify({id:'monitor',action:'dock',at:Date.now()})}); + assert.equal(h.shared.has('bpq-detached:monitor'),false);assert.equal(h.api.shouldPoll('monitor'),false);assert.equal(h.main.hidden,true);assert.ok(h.calls.includes('close')); +}); + +test('LAN HTTP without randomUUID supports all detached services',()=>{ + const h=harness('',new Map(),{insecure:true}); + for(const id of ['terminal','aprs','monitor','chat'])h.api.open(id); + assert.equal(h.calls.filter(c=>Array.isArray(c)&&typeof c[0]==='string'&&c[0].includes('window=')).length,4); +}); +test('late sections receive controls and courtesy placeholders on the next setup pass',()=>{ + const options={late:['chat','monitor','aprs']},h=harness('',new Map(),options); + assert.equal(h.sections.chat.child,undefined);options.late=[];h.tick(); + for(const id of ['chat','monitor','aprs'])assert.ok(h.sections[id].child); + const placeholder=h.sections.chat.child;h.tick();assert.equal(h.sections.chat.child,placeholder); +}); diff --git a/public/detach.js b/public/detach.js index 20367a7..7191a3e 100644 --- a/public/detach.js +++ b/public/detach.js @@ -3,7 +3,9 @@ const labels={terminal:'Terminale',aprs:'APRS',monitor:'Monitor',chat:'Chat'},params=new URLSearchParams(location.search); const requested=location.pathname==='/terminal-window'?'terminal':params.get('detached'); const view=Object.hasOwn(labels,requested)?requested:null; - const owner=params.get('window')||crypto.randomUUID(),refs=new Map(),ready=new Set(),ttl=120000; + const uuid=()=>globalThis.crypto?.randomUUID?.()||'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,c=>{const n=Math.floor(Math.random()*16);return(c==='x'?n:(n&3)|8).toString(16);}); + const mounted=new WeakSet(); + const owner=params.get('window')||uuid(),refs=new Map(),ready=new Set(),ttl=120000; const key=id=>'bpq-detached:'+id,commandKey='bpq-detached-command'; const target=id=>'bpq-console-'+id; const read=id=>{try{const value=JSON.parse(localStorage.getItem(key(id)));return value&&typeof value.owner==='string'&&Number.isFinite(value.at)?value:null;}catch{return null;}}; @@ -19,7 +21,7 @@ function shouldPoll(id){return (!view||!released&&view===id)&&!isAway(id);} function release(){if(!view)return;released=true;const record=read(view);if(record?.owner===owner)write(view,null);} function claim(){if(!view||!authenticated||released)return;write(view,{owner,at:Date.now()});} - function tell(id,action){try{localStorage.setItem(commandKey,JSON.stringify({id,action,at:Date.now(),nonce:crypto.randomUUID()}));}catch{}} + function tell(id,action){try{localStorage.setItem(commandKey,JSON.stringify({id,action,at:Date.now(),nonce:uuid()}));}catch{}} function focus(id){const ref=refs.get(id);if(ref&&!ref.closed){ref.focus();return;}tell(id,'focus');const popup=window.open('',target(id),'popup=yes,width=1180,height=820,resizable=yes,scrollbars=yes');if(popup)popup.focus();} function closeView(){ release();const main=document.querySelector('main');if(main)main.hidden=true; @@ -38,7 +40,7 @@ function open(id){ if(!Object.hasOwn(labels,id))return; if(isAway(id)){focus(id);return;} - const nonce=crypto.randomUUID(),url=id==='terminal'?'/terminal-window?window='+nonce:'/?detached='+id+'&window='+nonce+'#'+id; + const nonce=uuid(),url=id==='terminal'?'/terminal-window?window='+nonce:'/?detached='+id+'&window='+nonce+'#'+id; const popup=window.open(url,target(id),'popup=yes,width=1180,height=820,resizable=yes,scrollbars=yes'); if(!popup){if(typeof toast==='function')toast(BPQI18n.t('Consenti le finestre popup per aprire la sezione separata.'));return;} refs.set(id,popup);popup.focus(); @@ -53,10 +55,11 @@ } } function setup(){ - if(initialized||!domReady)return;initialized=true; + if(!domReady)return;const first=!initialized;initialized=true; for(const [id,label]of Object.entries(labels)){ - const section=document.getElementById(id);if(!section)continue; + const section=document.getElementById(id);if(!section||mounted.has(section))continue; const heading=section.querySelector('.terminal-actions,.monitor-heading>div,.chat-actions,.page-heading'); + if(!heading)continue;mounted.add(section); if(view===id&&heading){ const fullscreen=document.createElement('button');fullscreen.type='button';fullscreen.className='secondary detach-button'; const update=()=>{const active=!!document.fullscreenElement;fullscreen.textContent=(active?'⊡ ':'⛶ ')+BPQI18n.t(active?'Torna alla finestra':'Schermo intero');fullscreen.setAttribute('aria-pressed',String(active));}; @@ -73,7 +76,7 @@ placeholder.querySelector('h2').textContent=label;const buttons=placeholder.querySelectorAll('button');buttons[0].onclick=()=>focus(id);buttons[1].onclick=()=>dock(id);section.append(placeholder); } } - if(view&&location.pathname!=='/terminal-window'){ + if(first&&view&&location.pathname!=='/terminal-window'){ const previous=navigate;navigate=function(){previous(view);};navigate(view); document.title='BPQ Console · '+labels[view]; } @@ -89,5 +92,5 @@ }); window.addEventListener('pagehide',release);window.addEventListener('beforeunload',release); window.addEventListener('pageshow',()=>{if(view&&authenticated){released=false;claim();}}); - setInterval(()=>{claim();refresh();},2000); + setInterval(()=>{setup();claim();refresh();},2000); })(); diff --git a/public/index.html b/public/index.html index 0923629..d295e19 100644 --- a/public/index.html +++ b/public/index.html @@ -1,5 +1,5 @@ -BPQ Console +BPQ Console