Add detached service windows and selectable terminal themes

Support standalone APRS, Monitor, Chat and Terminal views with courtesy screens, window focus and return controls, shared sessions and suspended embedded polling.

Add five persistent phosphor palettes, remove Console terminal idle disconnections, and display decoded Mic-E movement and altitude with expandable original packets.

Document the new behavior and add regression coverage. Validation: 182 tests passed; the known hanging PowerShell startup readiness test was excluded.
This commit is contained in:
alberto committed 2026-10-19 22:15:15 +02:00
1 parent 8ee4e9636a
commit c98c67e18b
24 files changed
+415 -22

No files matched your search

+3 -3
View File
@@ -5,8 +5,8 @@ let csrf='',allMessages=[],dashboardData=null,filter='all',selected=null,page='h
const esc=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
async function api(url,options={}){const {busy=true,...request}=options;const finish=(busy&&window.BPQBusy?.start())||(()=>{});try{const r=await fetch('/api'+url,{...request,headers:{...(options.body instanceof FormData?{}:{'Content-Type':'application/json'}),...(options.method==='POST'?{'X-CSRF-Token':csrf}:{}),...options.headers}});const data=await r.json();if(!r.ok){if(r.status===401&&url!=='/login')showLogin();throw new Error(data.error||'Richiesta fallita')}return data;}finally{finish();}}
function toast(text){$('#toast').textContent=text;$('#toast').hidden=false;clearTimeout(toast.timer);toast.timer=setTimeout(()=>$('#toast').hidden=true,6500);}
function showLogin(){document.title='BPQ Console';$('#shell').hidden=true;$('#login').hidden=false;csrf='';}
function showShell(user){deletedMessageIds.clear();station=user.config;applyStation(user);csrf=user.csrf;$('#login').hidden=true;$('#shell').hidden=false;loadDashboard();if(station.features.bbs)loadMessages();document.dispatchEvent(new Event('station-ready'));}
function showLogin(){document.dispatchEvent(new Event('bpq-detach-auth-lost'));document.title='BPQ Console';$('#shell').hidden=true;$('#login').hidden=false;csrf='';}
function showShell(user){deletedMessageIds.clear();station=user.config;applyStation(user);csrf=user.csrf;$('#login').hidden=true;$('#shell').hidden=false;if(!window.BPQDetached?.view){loadDashboard();if(station.features.bbs)loadMessages();}document.dispatchEvent(new Event('station-ready'));}
function logTime(value){if(!value)return '—';const m=value.match(/^(\d{2})(\d{2})(\d{2}) (\d{2}:\d{2}:\d{2})$/);if(!m)return value;return new Date(`20${m[1]}-${m[2]}-${m[3]}T${m[4]}Z`).toLocaleTimeString(BPQI18n.locale(),{hour:'2-digit',minute:'2-digit'});}
function categoryLabel(m){return m.type==='P'?BPQI18n.t('PERSONALE'):m.to||BPQI18n.t('BOLLETTINO')}
function friendlyActivity(text){if(/Failure with/.test(text))return 'il nodo remoto non ha risposto alla chiamata';if(/Connecting to BBS/.test(text))return 'Chiamata radio verso il nodo remoto avviata';if(/Incoming Connect/.test(text))return 'il nodo remoto si è collegato alla nostra BBS';if(/Uncompressing Message/.test(text))return 'Ricevuto e salvato un nuovo bollettino';if(/Disconnected/.test(text))return 'Sessione con il nodo remoto terminata';return text;}
@@ -16,7 +16,7 @@ function navigate(next){page=next;$$('.page').forEach(p=>p.hidden=p.id!==next);$
$$('[data-page]').forEach(b=>b.addEventListener('click',()=>navigate(b.dataset.page)));
$('#login-form').addEventListener('submit',async e=>{e.preventDefault();const b=e.target.querySelector('button');b.disabled=true;$('#login-error').textContent='';try{const user=await api('/login',{method:'POST',body:JSON.stringify(Object.fromEntries(new FormData(e.target)))});e.target.password.value='';showShell(user);}catch(err){$('#login-error').textContent=err.message}finally{b.disabled=false}});
$('#logout').onclick=async()=>{try{await api('/logout',{method:'POST',body:'{}'})}finally{showLogin()}};
async function loadDashboard(background=false){try{const d=await api('/dashboard',{busy:!background});dashboardData=d;$('#connection').textContent=d.errors.length?'● Dati parziali':'● BPQ connesso';$('#notice').hidden=!d.errors.length;$('#notice').textContent=d.errors.join(' · ');$('#k-messages').textContent=d.counts.messages;$('#nav-count').textContent=d.counts.messages;$('#k-message-detail').textContent=`${d.counts.bulletins} bollettini · ${d.counts.personal} personali`;$('#k-nodes').textContent=d.nodes.length;$('#k-routes').textContent=d.routes.filter(r=>r.active).length;$('#k-sync').textContent=logTime(d.sync?.at);$('#k-sync-detail').textContent=d.sync?`${d.sync.received} ${d.sync.received===1?'messaggio ricevuto':'messaggi ricevuti'} · ${mailTimezone()}`:'Nessuno rilevato oggi';const r=d.radio;$('#radio-freq').textContent=r?.frequency||'—';$('#radio-status').textContent=r?.connected?'MODEM ONLINE':'NON DISPONIBILE';$('#radio-modem').textContent=r?.connected?(station.radio?.driver||'Modem')+' '+r.mode:'Non collegato';$('#radio-channel').textContent=r?(r.busy?'Occupato':'Libero'):'—';$('#radio-snr').textContent=r?r.snr+' dB':'—';$('#radio-scan').textContent=r?.scanning?'● Scansione attiva':r?.state&&r.state!=='Free'?'● '+r.state:'Scansione non rilevata';$('#updated').textContent='Aggiornato '+new Date(d.updatedAt).toLocaleTimeString(BPQI18n.locale(),{hour:'2-digit',minute:'2-digit'});$('#routes').innerHTML=d.routes.map(r=>`<tr><td>${esc(r.call)}</td><td><span class="tag">${r.active?'ATTIVO':'INATTIVO'}</span></td><td>${esc(r.port)}</td><td>${r.quality}</td><td>${r.nodes}</td><td>${r.frames}</td><td>${r.retries}</td></tr>`).join('')||'<tr><td colspan="7">Nessuna rotta disponibile</td></tr>';$('#nodes').innerHTML=d.nodes.map(n=>{const [alias,call]=n.split(':');return `<div class="node"><strong>${esc(alias)}</strong><small>${esc(call)}</small></div>`}).join('');$('#node-total').textContent=d.nodes.length+' destinazioni';}catch(err){$('#connection').textContent='● Connessione assente';$('#notice').hidden=false;$('#notice').textContent=err.message;}}
async function loadDashboard(background=false){if(window.BPQDetached?.view)return;try{const d=await api('/dashboard',{busy:!background});dashboardData=d;$('#connection').textContent=d.errors.length?'● Dati parziali':'● BPQ connesso';$('#notice').hidden=!d.errors.length;$('#notice').textContent=d.errors.join(' · ');$('#k-messages').textContent=d.counts.messages;$('#nav-count').textContent=d.counts.messages;$('#k-message-detail').textContent=`${d.counts.bulletins} bollettini · ${d.counts.personal} personali`;$('#k-nodes').textContent=d.nodes.length;$('#k-routes').textContent=d.routes.filter(r=>r.active).length;$('#k-sync').textContent=logTime(d.sync?.at);$('#k-sync-detail').textContent=d.sync?`${d.sync.received} ${d.sync.received===1?'messaggio ricevuto':'messaggi ricevuti'} · ${mailTimezone()}`:'Nessuno rilevato oggi';const r=d.radio;$('#radio-freq').textContent=r?.frequency||'—';$('#radio-status').textContent=r?.connected?'MODEM ONLINE':'NON DISPONIBILE';$('#radio-modem').textContent=r?.connected?(station.radio?.driver||'Modem')+' '+r.mode:'Non collegato';$('#radio-channel').textContent=r?(r.busy?'Occupato':'Libero'):'—';$('#radio-snr').textContent=r?r.snr+' dB':'—';$('#radio-scan').textContent=r?.scanning?'● Scansione attiva':r?.state&&r.state!=='Free'?'● '+r.state:'Scansione non rilevata';$('#updated').textContent='Aggiornato '+new Date(d.updatedAt).toLocaleTimeString(BPQI18n.locale(),{hour:'2-digit',minute:'2-digit'});$('#routes').innerHTML=d.routes.map(r=>`<tr><td>${esc(r.call)}</td><td><span class="tag">${r.active?'ATTIVO':'INATTIVO'}</span></td><td>${esc(r.port)}</td><td>${r.quality}</td><td>${r.nodes}</td><td>${r.frames}</td><td>${r.retries}</td></tr>`).join('')||'<tr><td colspan="7">Nessuna rotta disponibile</td></tr>';$('#nodes').innerHTML=d.nodes.map(n=>{const [alias,call]=n.split(':');return `<div class="node"><strong>${esc(alias)}</strong><small>${esc(call)}</small></div>`}).join('');$('#node-total').textContent=d.nodes.length+' destinazioni';}catch(err){$('#connection').textContent='● Connessione assente';$('#notice').hidden=false;$('#notice').textContent=err.message;}}
async function loadMessages(background=false){if(!station.features.bbs)return;try{allMessages=(await api('/messages',{busy:!background})).filter(m=>!deletedMessageIds.has(m.id));const current=$('#category').value;const categories=[...new Set(allMessages.filter(m=>m.type==='B').map(m=>m.to))].sort();$('#category').innerHTML='<option value="">Tutte le categorie</option>'+categories.map(c=>`<option>${esc(c)}</option>`).join('');$('#category').value=current;renderMessages();}catch(err){toast(err.message)}}
function mailDate(m,kind='received'){const value=kind==='sent'?m.createdAt:(m.receivedAt||m.createdAt);if(!value)return m.date||'—';return new Date(value).toLocaleString(BPQI18n.locale(),{day:'2-digit',month:'2-digit',hour:'2-digit',minute:'2-digit'});}
function mailTimezone(){const minutes=-new Date().getTimezoneOffset();return 'UTC'+(minutes>=0?'+':'-')+String(Math.floor(Math.abs(minutes)/60)).padStart(2,'0')+':'+String(Math.abs(minutes)%60).padStart(2,'0');}
+2
View File
@@ -45,3 +45,5 @@
.aprs-map-actions{display:flex;gap:8px;flex-wrap:wrap;justify-content:flex-end}.aprs-map-actions .secondary{white-space:nowrap}@media(max-width:650px){.aprs-map-actions{width:100%;justify-content:flex-start}.aprs-map-actions .secondary{flex:1}}
.aprs-map-actions .secondary[aria-pressed=true]{border-color:#88c7b1;background:#8acbb018;color:#c8ebdf}
.aprs-map-popup p{white-space:pre-line}.aprs-raw-packet summary{font-size:11px;color:#a9c4d8;cursor:pointer}.aprs-raw-packet pre{max-height:120px;overflow:auto;white-space:pre-wrap;overflow-wrap:anywhere;font:11px/1.5 Consolas,monospace;color:#a7becf;margin:6px 0}.aprs-received-station p{white-space:pre-line}
+15 -4
View File
@@ -17,7 +17,18 @@
}
const symbolKey=(s)=>JSON.stringify([s.position?.symset,s.position?.symbol,s.transport]);
function symbolDetail(position){const info=window.BPQAprsSymbols.decode(position);return info?esc(info.name)+' · <code>'+esc(info.code)+'</code>'+(info.overlay?' · '+BPQI18n.t('Sovrapposizione')+' '+esc(info.overlay):''):BPQI18n.t('Simbolo non disponibile');}
function popup(s){return '<div class="aprs-map-popup"><b>'+esc(s.call)+'</b><span class="aprs-symbol-detail">'+symbolDetail(s.position)+'</span><span>'+esc(s.transport)+(s.port?' · Port '+s.port:'')+'</span><span>'+esc(time(s.lastAt))+'</span><span>'+s.position.lat.toFixed(5)+', '+s.position.lon.toFixed(5)+'</span><p>'+esc(s.status||s.lastBody||'')+'</p><small>'+esc(s.path||'')+'</small></div>';}
function stationDescription(s){
const packet=window.BPQAprsPacket.decode(s.lastBody||''),parts=[];
if(packet.format)parts.push(packet.format==='APRS'?BPQI18n.t('Posizione APRS'):packet.format);
if(packet.speedKmh!==null)parts.push(packet.speedKmh+' km/h');
if(packet.course!==null)parts.push(packet.course+'°');
if(packet.altitudeM!==null)parts.push(BPQI18n.t('Quota')+' '+packet.altitudeM+' m');
if(packet.device)parts.push(packet.device);
const status=window.BPQAprsPacket.decode(s.status||'').comment;
return [parts.join(' · '),status||packet.comment].filter(Boolean).join('\n');
}
function rawPacket(s){return s.lastBody?'<details class="aprs-raw-packet"><summary>'+BPQI18n.t('Pacchetto originale')+'</summary><pre>'+esc(s.lastBody.replace(/[\x00-\x1f\x7f-\x9f]/g,c=>String.fromCharCode(92)+'x'+c.charCodeAt(0).toString(16).padStart(2,'0')))+'</pre></details>':'';}
function popup(s){return '<div class="aprs-map-popup"><b>'+esc(s.call)+'</b><span class="aprs-symbol-detail">'+symbolDetail(s.position)+'</span><span>'+esc(s.transport)+(s.port?' · Port '+s.port:'')+'</span><span>'+esc(time(s.lastAt))+'</span><span>'+s.position.lat.toFixed(5)+', '+s.position.lon.toFixed(5)+'</span><p>'+esc(stationDescription(s))+'</p>'+rawPacket(s)+'<small>'+esc(s.path||'')+'</small></div>';}
function initMap(){if(map||!window.L)return;map=L.map('aprs-station-map',{zoomControl:true,scrollWheelZoom:true}).setView([25,0],2);L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png',{maxZoom:19,referrerPolicy:'origin',attribution:'&copy; <a href="https://www.openstreetmap.org/copyright" target="_blank" rel="noopener">OpenStreetMap</a> contributors · <a href="/vendor/aprs-symbols/README.md" target="_blank" rel="noopener">APRS symbols © OH7LZB</a>'}).addTo(map);layers=L.layerGroup().addTo(map);if(typeof ResizeObserver!=='undefined')new ResizeObserver(()=>{if(page==='aprs'&&view==='activity')map.invalidateSize({pan:false});}).observe($('#aprs-station-map'));}
const validPosition=p=>p&&Number.isFinite(p.lat)&&Number.isFinite(p.lon)&&Math.abs(p.lat)<=90&&Math.abs(p.lon)<=180;
function distanceKm(a,b){
@@ -83,15 +94,15 @@
$('#aprs-map-count').textContent=visible.size+' '+BPQI18n.t('sulla mappa')+' · '+(list.length-visible.size)+' '+BPQI18n.t('senza posizione');
if(!fitted&&(visible.size||own?.position)){if(validPosition(own?.position))fitLocal();else fit();fitted=true;}
}
function renderStations(){const list=stations();markup('#aprs-received-stations',list.map(s=>'<button data-aprs-station="'+esc(s.call)+'" class="aprs-received-station '+(s.call===selected?'selected':'')+'"><span><span class="aprs-list-symbol">'+window.BPQAprsSymbols.html(s.position)+'</span><b>'+esc(s.call)+'</b><i class="aprs-source-dot '+s.transport.toLowerCase()+'"></i></span><small>'+esc(s.transport)+(s.port?' · Port '+s.port:'')+' · '+esc(time(s.lastAt))+'</small><small class="aprs-symbol-detail">'+symbolDetail(s.position)+'</small><p>'+esc(s.status||s.lastBody||'—').slice(0,170)+'</p>'+(!s.position?'<small>Senza posizione</small>':'')+'</button>').join('')||'<p class="empty">Nessuna stazione ricevuta con questi filtri.</p>');}
function renderStations(){const list=stations();markup('#aprs-received-stations',list.map(s=>'<button data-aprs-station="'+esc(s.call)+'" class="aprs-received-station '+(s.call===selected?'selected':'')+'"><span><span class="aprs-list-symbol">'+window.BPQAprsSymbols.html(s.position)+'</span><b>'+esc(s.call)+'</b><i class="aprs-source-dot '+s.transport.toLowerCase()+'"></i></span><small>'+esc(s.transport)+(s.port?' · Port '+s.port:'')+' · '+esc(time(s.lastAt))+'</small><small class="aprs-symbol-detail">'+symbolDetail(s.position)+'</small><p>'+esc((stationDescription(s)||'—').slice(0,170))+'</p>'+(!s.position?'<small>Senza posizione</small>':'')+'</button>').join('')||'<p class="empty">Nessuna stazione ricevuta con questi filtri.</p>');}
function render(){if(!data)return;const events=data.events.filter(e=>(!source()||e.transport===source())&&(!$('#aprs-direction').value||e.direction===$('#aprs-direction').value)&&(!query()||(e.packet+' '+e.from).toUpperCase().includes(query()))).slice().reverse();
$('#aprs-live-state').textContent=paused?'Vista in pausa':data.monitor==='online'?'● APRS in tempo reale':'Monitor '+data.monitor;
markup('#aprs-activity-kpis',[['Radio RX',events.filter(e=>e.transport==='Radio'&&e.direction==='RX').length],['Radio TX · BPQ',events.filter(e=>e.transport==='Radio'&&e.direction==='TX').length],['Internet RX',events.filter(e=>e.transport==='Internet'&&e.direction==='RX').length],['Internet TX',events.filter(e=>e.transport==='Internet'&&e.direction==='TX').length],['Stazioni ricevute',stations().length]].map(([k,v])=>'<article><span>'+esc(k)+'</span><strong>'+v+'</strong></article>').join(''));
$('#aprs-traffic-count').textContent=events.length+' '+BPQI18n.t('pacchetti nel registro');markup('#aprs-traffic-rows',events.slice(0,400).map(e=>'<tr data-aprs-event="'+e.id+'" tabindex="0" aria-expanded="'+(selectedEvent===e.id)+'"><td>'+esc(time(e.at))+'</td><td><span class="aprs-packet-direction '+e.direction.toLowerCase()+'">'+e.direction+'</span></td><td>'+esc(e.transport)+(e.port?'<small>Port '+e.port+'</small>':'')+'</td><td><b>'+esc(e.from)+'</b><small>→ '+esc(e.to)+'</small></td><td><span class="aprs-packet-type">'+esc(type(e.type))+'</span><span class="aprs-packet-preview">'+esc(e.body.slice(0,180))+'</span></td></tr>'+(selectedEvent===e.id?'<tr class="aprs-packet-detail"><td colspan="5"><pre>'+esc(e.packet)+'</pre><small>'+esc(e.evidence)+'</small></td></tr>':'')).join('')||'<tr><td colspan="5" class="empty">In attesa di pacchetti APRS ricevuti o inviati.</td></tr>');
$('#aprs-traffic-scope').textContent=BPQI18n.t('Ultimi 2000 pacchetti · TX radio = richieste registrate da BPQ.');$('#aprs-activity-status').textContent=[...data.errors,...(!data.loggingInternet?[BPQI18n.t('Log Internet non disponibile')]:[]),BPQI18n.t('Aggiornato')+' '+time(data.updatedAt)].join(' · ');renderStations();renderMap();
}
async function start(){if(!csrf)return;if(starting||data?.started){if(data)render();return;}starting=true;try{data=await api('/aprs/activity/start',{method:'POST',body:'{}'});render();}catch(e){$('#aprs-activity-status').textContent=e.message;}finally{starting=false;}}
async function poll(background=true){if(!csrf||loading||paused||document.hidden||page!=='aprs'||view!=='activity')return;loading=true;try{const next=await api('/aprs/activity',{busy:!background});data=next;render();if(!data.started)start();}catch(e){$('#aprs-activity-status').textContent=e.message;}finally{loading=false;}}
async function start(){if(!csrf||window.BPQDetached&&!window.BPQDetached.shouldPoll('aprs'))return;if(starting||data?.started){if(data)render();return;}starting=true;try{data=await api('/aprs/activity/start',{method:'POST',body:'{}'});render();}catch(e){$('#aprs-activity-status').textContent=e.message;}finally{starting=false;}}
async function poll(background=true){if(!csrf||loading||paused||document.hidden||window.BPQDetached&&!window.BPQDetached.shouldPoll('aprs')||page!=='aprs'||view!=='activity')return;loading=true;try{const next=await api('/aprs/activity',{busy:!background});data=next;render();if(!data.started)start();}catch(e){$('#aprs-activity-status').textContent=e.message;}finally{loading=false;}}
$('#aprs-map-fit').onclick=fit;$('#aprs-map-local').onclick=fitLocal;$('#aprs-activity-refresh').onclick=()=>{if(paused){render();return;}poll(false);};$('#aprs-activity-pause').onclick=()=>{paused=!paused;$('#aprs-activity-pause').textContent=paused?'Riprendi vista':'Pausa vista';if(!paused)poll();else render();};for(const id of ['aprs-source','aprs-direction','aprs-search'])$('#'+id).addEventListener(id==='aprs-search'?'input':'change',()=>{render();});
$('#aprs-received-stations').onclick=e=>{const call=e.target.closest('[data-aprs-station]')?.dataset.aprsStation;if(!call)return;selected=call;const marker=markers.get(call);if(marker){map.setView(marker.getLatLng(),Math.max(map.getZoom(),13));marker.openPopup();}renderStations();};
$('#aprs-traffic-rows').onclick=e=>{const row=e.target.closest('[data-aprs-event]');if(row){const id=Number(row.dataset.aprsEvent);selectedEvent=selectedEvent===id?null:id;render();}};$('#aprs-traffic-rows').onkeydown=e=>{if(['Enter',' '].includes(e.key)&&e.target.matches('[data-aprs-event]')){e.preventDefault();e.target.click();}};
+36
View File
@@ -13,5 +13,41 @@
const col=info.index%16,row=Math.floor(info.index/16);
return '<span class="aprs-symbol-image aprs-symbol-'+info.table+' aprs-symbol-col-'+col+' aprs-symbol-row-'+row+'" aria-hidden="true">'+(info.overlay?'<span class="aprs-symbol-overlay">'+info.overlay+'</span>':'')+'</span>';
}
// APRS101 chapter 10 and aprs.org/aprs12/mic-e-types.txt.
function packetDetails(body=''){
body=String(body);const result={format:null,comment:body,speedKmh:null,course:null,altitudeM:null,device:null};
if(/^[`']/.test(body)){
result.format='Mic-E';result.comment='';
if(body.length<9||!decode({symset:body[8],symbol:body[7]}))return result;
const [sp,dc,se]=[4,5,6].map(i=>body.charCodeAt(i)-28);
if(sp>=0&&sp<=99&&dc>=0&&dc<=99&&se>=0&&se<=99){
let speed=sp*10+Math.floor(dc/10),course=(dc%10)*100+se;
if(speed>=800)speed-=800;if(course>=400)course-=400;
if(speed>=0&&speed<=799&&course>=0&&course<=360){result.speedKmh=Math.round(speed*1.852);result.course=course||null;}
}
let tail=body.slice(9),prefix=tail[0];
if(prefix==='>'||prefix===']'){
result.device=prefix==='>'?'Kenwood TH-D7':'Kenwood TM-D700';tail=tail.slice(1);
if(tail.endsWith('=')){result.device=prefix==='>'?'Kenwood TH-D72':'Kenwood TM-D710';tail=tail.slice(0,-1);}
else if(prefix==='>'&&tail.endsWith('^')){result.device='Kenwood TH-D74';tail=tail.slice(0,-1);}
}else if(prefix==='`'||prefix==="'"){
tail=tail.slice(1);
const devices={'_ ':'Yaesu VX-8','_"':'Yaesu FTM-350','_#':'Yaesu VX-8G','_$':'Yaesu FT1D','_%':'Yaesu FTM-400DR','_)':'Yaesu FTM-100D','_(':'Yaesu FT2D','_0':'Yaesu FT3D','_3':'Yaesu FT5D','_1':'Yaesu FTM-300D','(5':'AnyTone D578UV','(8':'AnyTone D878UV','|3':'Byonics TinyTrak3','|4':'Byonics TinyTrak4',':4':'SCS DR-7400',':8':'SCS DR-7800'};
const device=devices[tail.slice(-2)];if(device){result.device=device;tail=tail.slice(0,-2);}
}else if(prefix===' ')tail=tail.slice(1);
const altitude=tail.match(/^([!-{]{3})\}/);
if(altitude){result.altitudeM=[...altitude[1]].reduce((n,c)=>n*91+c.charCodeAt(0)-33,0)-10000;tail=tail.slice(4);}
result.comment=tail;
}else if(/^[!=/@]/.test(body)){
result.format='APRS';const payload=body.slice(body[0]==='@'||body[0]==='/'?8:1);
if(/^\d{4}\.\d{2}[NS].\d{5}\.\d{2}[EW]./.test(payload))result.comment=payload.slice(19);
else if(/^[/\A-Z0-9][!-{]{8}[!-~][!-{]{3}/.test(payload))result.comment=payload.slice(13);
else result.comment='';
}else if(body.startsWith('>'))result.comment=body.slice(1).replace(/^\d{6}[zh/]/,'');
// Control bytes belong to the encoded frame, never the operator's description.
result.comment=result.comment.replace(/[\x00-\x1f\x7f-\x9f]/g,' ').trim();return result;
}
window.BPQAprsPacket={decode:packetDetails};
window.BPQAprsSymbols={decode,html};
})();
+6
View File
@@ -0,0 +1,6 @@
.section-detached-away>.detached-placeholder{display:flex;flex:1;min-height:360px;align-items:center;justify-content:center;flex-direction:column;text-align:center;padding:48px 24px;gap:18px;border:1px dashed #3d5368;border-radius:16px;background:radial-gradient(ellipse at top,#233b4c50,transparent 65%)}
.section-detached-away>:not(.detached-placeholder){display:none!important}.section-detached-away>.detached-placeholder[hidden]{display:none!important}.detached-placeholder-icon{display:grid;place-items:center;width:62px;height:62px;background:#8fb5cf10;border:1px solid #8fb5cf35;border-radius:18px;font-size:30px;color:#9fc9e4}.detached-placeholder h2{font-size:24px;letter-spacing:-.4px}.detached-placeholder p{color:#8fa7ba;max-width:420px;line-height:1.7}.detached-placeholder>div{display:flex;gap:10px;flex-wrap:wrap;justify-content:center;margin-top:6px}.detach-button{white-space:nowrap}
html[data-detached-view] #shell>.sidebar,html[data-detached-view] .topbar,html[data-detached-view] #notice{display:none!important}html[data-detached-view] #shell>main{margin:0;padding:0;width:100%;max-width:none}html[data-detached-view] #shell .page{height:100dvh;max-width:none;min-height:0;padding:20px}html[data-detached-view=chat] #chat{height:100dvh}html[data-detached-view=monitor] #monitor{height:100dvh}html[data-detached-view=aprs] #aprs{height:auto;min-height:100dvh;padding:20px}html[data-detached-view=aprs] #aprs-station-map{height:clamp(340px,calc(100dvh - 330px),680px)}html[data-detached-view=aprs] .aprs-stations-card{height:calc(clamp(340px,calc(100dvh - 330px),680px) + 112px)}
@media(max-width:650px){html[data-detached-view] #shell .page{padding:12px}.detached-placeholder>div{width:100%}.detached-placeholder>div button{flex:1}.chat-actions,.monitor-heading>div{flex-wrap:wrap}}
.detached-returned-note{min-height:100dvh;display:flex;align-items:center;justify-content:center;flex-direction:column;gap:20px;text-align:center;padding:30px;color:#cedce8}.detached-returned-note p{color:#8fa7ba}
+87
View File
@@ -0,0 +1,87 @@
/* Window ownership is UI metadata only; authentication stays in the HttpOnly cookie. */
(()=>{
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 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;}};
const write=(id,value)=>{try{value?localStorage.setItem(key(id),JSON.stringify(value)):localStorage.removeItem(key(id));}catch{}};
let initialized=false,authenticated=false,released=false,domReady=document.readyState==='complete';
if(view){document.documentElement.dataset.detachedView=view;window.name=target(view);}
function isAway(id){
if(view===id)return false;
const ref=refs.get(id);
if(ref){if(ref.closed){refs.delete(id);ready.delete(id);write(id,null);return false;}if(ready.has(id))return true;}
const record=read(id);return !!record&&Date.now()-record.at<ttl;
}
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 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;
const note=document.createElement('section');note.className='detached-returned-note';
note.innerHTML='<span class="detached-placeholder-icon" aria-hidden="true">↙</span><h2>Sezione riportata nel pannello</h2><p>Puoi chiudere questa finestra.</p>';
document.body.append(note);window.close();
}
function dock(id){
if(view===id){
try{if(window.opener&&!window.opener.closed){window.opener.location.hash='#'+id;window.opener.focus();}}catch{}
closeView();return;
}
tell(id,'dock');const ref=refs.get(id);if(ref&&!ref.closed)ref.close();refs.delete(id);ready.delete(id);write(id,null);refresh();
if(typeof navigate==='function')navigate(id);
}
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 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();
}
function refresh(){
if(!initialized)return;
for(const id of Object.keys(labels)){
const section=document.getElementById(id);if(!section)continue;
const away=isAway(id);section.classList.toggle('section-detached-away',away);
const placeholder=section.querySelector('.detached-placeholder');if(placeholder)placeholder.hidden=!away;
if(read(id)&&refs.has(id))ready.add(id);
}
}
function setup(){
if(initialized||!domReady)return;initialized=true;
for(const [id,label]of Object.entries(labels)){
const section=document.getElementById(id);if(!section)continue;
const heading=section.querySelector('.terminal-actions,.monitor-heading>div,.chat-actions,.page-heading');
if(id!=='terminal'&&heading){
const button=document.createElement('button');button.type='button';button.className='secondary detach-button';button.dataset.detach=id;
button.textContent=view===id?'↙ Torna al pannello':'↗ Stacca';button.onclick=()=>view===id?dock(id):open(id);heading.append(button);
}
if(!view){
const placeholder=document.createElement('div');placeholder.className='detached-placeholder';placeholder.hidden=true;
placeholder.innerHTML='<span class="detached-placeholder-icon" aria-hidden="true">↗</span><h2></h2><p>Questa sezione è aperta in una finestra separata.</p><div><button type="button" class="primary">Mostra finestra</button><button type="button" class="secondary">Riporta qui</button></div>';
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'){
const previous=navigate;navigate=function(){previous(view);};navigate(view);
document.title='BPQ Console · '+labels[view];
}
refresh();
}
window.BPQDetached={view,open,dock,isAway,shouldPoll};
document.addEventListener('DOMContentLoaded',()=>{domReady=true;setup();});
document.addEventListener('station-ready',()=>{authenticated=true;released=false;setup();claim();refresh();if(view){document.title='BPQ Console · '+labels[view];if(location.pathname!=='/terminal-window')navigate(view);}});
document.addEventListener('bpq-detach-auth-lost',()=>{authenticated=false;release();});
window.addEventListener('storage',event=>{
if(event.key===commandKey&&view){try{const cmd=JSON.parse(event.newValue);if(cmd.id===view&&Date.now()-cmd.at<5000){if(cmd.action==='focus')window.focus();else if(cmd.action==='dock')closeView();}}catch{}}
if(event.key?.startsWith('bpq-detached:'))refresh();
});
window.addEventListener('pagehide',release);window.addEventListener('beforeunload',release);
window.addEventListener('pageshow',()=>{if(view&&authenticated){released=false;claim();}});
setInterval(()=>{claim();refresh();},2000);
})();
+2 -2
View File
@@ -12,7 +12,7 @@ function arrival(kind,title,detail,ids=[]){const item=document.createElement('di
let knownStation=null,knownIds;try{const saved=JSON.parse(localStorage.getItem('bpq-message-ids-'+station.call)||'null');knownIds=Array.isArray(saved)?new Set(saved):null}catch{knownIds=null}
const oldLoadMessages=loadMessages;
loadMessages=async function(...args){await oldLoadMessages(...args);if(!csrf||!allMessages.length)return;if(knownStation!==station.call){knownStation=station.call;try{const saved=JSON.parse(localStorage.getItem('bpq-message-ids-'+station.call)||'null');knownIds=Array.isArray(saved)?new Set(saved):null}catch{knownIds=null}}const arrivals=incoming(allMessages,knownIds,station.call);const fresh=[...arrivals.bulletins,...arrivals.mail];knownIds=new Set(allMessages.map(m=>m.id));localStorage.setItem('bpq-message-ids-'+station.call,JSON.stringify([...knownIds]));if(fresh.length){const bulls=fresh.filter(m=>m.type==='B'),mail=fresh.filter(m=>m.type==='P'||m.type==='T');if(bulls.length)arrival('bulletin',bulls.length===1?'Nuovo bollettino scaricato':`${bulls.length} nuovi bollettini scaricati`,bulls.length===1?bulls[0].subject:'Disponibili nella BBS',bulls.map(m=>m.id));if(mail.length)arrival('mail',mail.length===1?'Nuova mail ricevuta':`${mail.length} nuove mail ricevute`,mail.length===1?'Da '+mail[0].from+' · '+mail[0].subject:'Disponibili nella posta personale',mail.map(m=>m.id));chime();}};
setInterval(()=>{if(csrf&&!document.hidden)loadMessages(true)},15000);
setInterval(()=>{if(csrf&&!document.hidden&&!window.BPQDetached?.view)loadMessages(true)},15000);
const chatNav=document.createElement('button');chatNav.dataset.page='chat';chatNav.innerHTML='<span>◇</span> Chat';chatNav.onclick=()=>navigate('chat');$('nav').append(chatNav);
const chatPage=document.createElement('section');chatPage.id='chat';chatPage.className='page';chatPage.hidden=true;chatPage.innerHTML=`<div class="chat-heading"><h1>Chat</h1><div class="chat-actions"><span id="chat-state" class="chat-status">Disconnesso</span><button id="chat-connect" class="primary">Connetti</button><button id="chat-disconnect" class="secondary" hidden>Esci</button></div></div><div class="chat-layout"><aside class="chat-rooms"><div class="chat-label">STANZE<button id="new-topic" aria-label="Crea stanza">+</button></div><div id="chat-topics"><button class="room-button active"># General</button></div><div class="chat-links"><div class="chat-label">COLLEGAMENTI</div><div id="chat-links"></div></div></aside><div class="chat-main"><header class="chat-room-header"><b id="chat-room-name"># General</b><small id="chat-presence-count">— presenti</small></header><div id="chat-messages" class="chat-messages"><div class="chat-empty"><span>◇</span><h2>Chat BPQ</h2><p>Connettiti con il tuo account per partecipare alla chat.</p></div></div><form id="chat-form" class="chat-compose"><div class="chat-recipient"><label for="chat-recipient">Destinatario</label><select id="chat-recipient"><option value="">Tutta la stanza</option></select></div><div class="chat-input-row"><input id="chat-input" aria-label="Messaggio chat" placeholder="Scrivi un messaggio…" maxlength="500" autocomplete="off" disabled><button id="chat-send" class="primary" disabled>Invia ↗</button></div></form></div><aside class="chat-users"><div class="chat-label">PRESENTI <span id="chat-user-count">0</span></div><div id="chat-users"><p class="empty">Non connesso</p></div></aside></div>`;$('main').append(chatPage);
const topicDialog=document.createElement('dialog');topicDialog.innerHTML='<form id="topic-form"><h2>Crea o apri una stanza</h2><input id="topic-name" aria-label="Nome stanza" placeholder="Nome stanza" required pattern="[A-Za-z0-9_-]{1,24}" maxlength="24"><footer><button type="button" id="topic-cancel" class="secondary">Annulla</button><button class="primary">Entra</button></footer></form>';document.body.append(topicDialog);
@@ -45,7 +45,7 @@ function renderChat(data){
}
}
async function pollChat(){if(!csrf||chatPollBusy)return;chatPollBusy=true;try{renderChat(await api('/chat',{busy:false}))}catch(e){if(page==='chat')toast(e.message)}finally{chatPollBusy=false}}
async function pollChat(){if(!csrf||chatPollBusy||window.BPQDetached&&!window.BPQDetached.shouldPoll('chat'))return;chatPollBusy=true;try{renderChat(await api('/chat',{busy:false}))}catch(e){if(page==='chat')toast(e.message)}finally{chatPollBusy=false}}
$('#chat-connect').onclick=async()=>{try{chatLastId=0;chatFollowing=true;chatUnread=0;$('#chat-messages').innerHTML='';renderChat(await api('/chat/connect',{method:'POST',body:'{}'}))}catch(e){toast(e.message)}};$('#chat-disconnect').onclick=async()=>{try{await api('/chat/disconnect',{method:'POST',body:'{}'});pollChat()}catch(e){toast(e.message)}};
$('#chat-form').onsubmit=async e=>{e.preventDefault();const input=$('#chat-input'),button=$('#chat-send'),text=input.value.trim();if(!text)return;button.disabled=true;try{await api('/chat/send',{method:'POST',body:JSON.stringify({text,to:$('#chat-recipient').value})});input.value='';await pollChat()}catch(err){toast(err.message)}finally{button.disabled=chatState!=='online';input.focus()}};
$('#new-topic').onclick=()=>topicDialog.showModal();$('#topic-cancel').onclick=()=>topicDialog.close();$('#topic-form').onsubmit=async e=>{e.preventDefault();try{await api('/chat/topic',{method:'POST',body:JSON.stringify({topic:$('#topic-name').value})});topicDialog.close();pollChat()}catch(err){toast(err.message)}};
+18
View File
@@ -8,6 +8,24 @@ Zona locale · 30 km|Local area · 30 km
Inquadra il gruppo più denso, ignorando le stazioni isolate|Fit the densest group, excluding isolated stations
Inquadra un raggio di 30 km dalla tua stazione|Show a 30 km radius around your station
Posizione della tua stazione non disponibile|Your station position is unavailable
Questa sezione è aperta in una finestra separata.|This section is open in a separate window.
Sezione riportata nel pannello|Section returned to the dashboard
Puoi chiudere questa finestra.|You can close this window.
Mostra finestra|Show window
Riporta qui|Bring back here
Consenti le finestre popup per aprire la sezione separata.|Allow popups to open the detached section.
Fosfori|Phosphor
Stile del terminale|Terminal theme
Stacca|Detach
Torna al pannello|Back to dashboard
Apri il pannello|Open dashboard
Apri il terminale in una finestra separata|Open the terminal in a separate window
Consenti le finestre popup per aprire il terminale separato.|Allow popups to open the detached terminal.
Sessione scaduta. Accedi nuovamente dal pannello.|Session expired. Sign in again from the dashboard.
Terminale non configurato in BPQ.|Terminal is not configured in BPQ.
Quota|Altitude
Posizione APRS|APRS position
Pacchetto originale|Original packet
Simbolo non disponibile|Symbol unavailable
Sovrapposizione|Overlay
Commenta|Comment
+1 -1
View File
@@ -1,5 +1,5 @@
<!doctype html>
<html lang="it"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="theme-color" content="#101916"><title>BPQ Console</title><link rel="stylesheet" href="/i18n.css"><script src="/ui-config.js"></script><script src="/i18n.js?v=20261019-label-audit"></script><link rel="stylesheet" href="/style.css"><link rel="stylesheet" href="/dark.css"><link rel="stylesheet" href="/mission.css"><link rel="stylesheet" href="/busy.css"><script defer src="/busy.js"></script><script defer src="/app.js"></script><script type="module" src="/enhancements.js"></script><script defer src="/winlink.js"></script><script defer src="/mission.js"></script><script defer src="/attachments.js"></script><link rel="stylesheet" href="/compose-attachments.css"><script defer src="/compose-attachments.js"></script><link rel="stylesheet" href="/monitor.css"><script defer src="/monitor.js"></script><link rel="stylesheet" href="/journal.css"><script defer src="/journal.js"></script><link rel="stylesheet" href="/forwarding.css"><script defer src="/forwarding.js?v=20261017-hourly-2"></script><link rel="stylesheet" href="/winlink-radio.css"><script defer src="/winlink-radio.js"></script><link rel="stylesheet" href="/terminal.css"><script defer src="/terminal.js"></script><link rel="stylesheet" href="/radio-control.css"><link rel="stylesheet" href="/radio-ports.css"><script defer src="/radio-ports.js"></script><link rel="stylesheet" href="/aprs.css"><script defer src="/aprs.js"></script><link rel="stylesheet" href="/vendor/leaflet/leaflet.css"><script defer src="/vendor/leaflet/leaflet.js"></script><link rel="stylesheet" href="/aprs-activity.css?v=20261019-map-fit"><script defer src="/aprs-symbols.js"></script><script defer src="/aprs-activity.js?v=20261019-map-fit"></script><link rel="stylesheet" href="/sync-progress.css"><script type="module" src="/sync-progress.js"></script></head>
<html lang="it"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="theme-color" content="#101916"><title>BPQ Console</title><link rel="stylesheet" href="/i18n.css"><script src="/ui-config.js"></script><script defer src="/detach.js?v=20261019-multi"></script><link rel="stylesheet" href="/detach.css?v=20261019-multi"><script src="/i18n.js?v=20261019-label-audit"></script><link rel="stylesheet" href="/style.css"><link rel="stylesheet" href="/dark.css"><link rel="stylesheet" href="/mission.css"><link rel="stylesheet" href="/busy.css"><script defer src="/busy.js"></script><script defer src="/app.js"></script><script type="module" src="/enhancements.js"></script><script defer src="/winlink.js"></script><script defer src="/mission.js"></script><script defer src="/attachments.js"></script><link rel="stylesheet" href="/compose-attachments.css"><script defer src="/compose-attachments.js"></script><link rel="stylesheet" href="/monitor.css"><script defer src="/monitor.js"></script><link rel="stylesheet" href="/journal.css"><script defer src="/journal.js"></script><link rel="stylesheet" href="/forwarding.css"><script defer src="/forwarding.js?v=20261017-hourly-2"></script><link rel="stylesheet" href="/winlink-radio.css"><script defer src="/winlink-radio.js"></script><link rel="stylesheet" href="/terminal.css?v=20261019-themes"><script defer src="/terminal.js?v=20261019-themes"></script><link rel="stylesheet" href="/radio-control.css"><link rel="stylesheet" href="/radio-ports.css"><script defer src="/radio-ports.js"></script><link rel="stylesheet" href="/aprs.css"><script defer src="/aprs.js"></script><link rel="stylesheet" href="/vendor/leaflet/leaflet.css"><script defer src="/vendor/leaflet/leaflet.js"></script><link rel="stylesheet" href="/aprs-activity.css?v=20261019-packet-text"><script defer src="/aprs-symbols.js"></script><script defer src="/aprs-activity.js?v=20261019-packet-text"></script><link rel="stylesheet" href="/sync-progress.css"><script type="module" src="/sync-progress.js"></script></head>
<body>
<section id="login" class="login-screen"><div class="login-art"><h1>BPQ Console</h1><div class="login-byline" data-no-i18n>by IU2EUG</div><p>La tua stazione, in un unico pannello.</p></div><form id="login-form" class="login-card"><div class="login-brand"><span class="brand">BPQ Console</span><div class="login-byline" data-no-i18n>by IU2EUG</div></div><h2>Benvenuto in stazione.</h2><p>Accedi con l’utente e la password Telnet del tuo BPQ.</p><label>Utente<input name="user" autocomplete="username" required placeholder="Il tuo utente BPQ"></label><label>Password<input name="password" type="password" autocomplete="current-password" required></label><button class="primary" type="submit">Entra nel pannello <span>→</span></button><div id="login-error" class="error" role="alert"></div></form></section>
<div id="shell" hidden><aside class="sidebar"><a class="brand" href="#home">BPQ Console</a><div class="side-label">LA TUA STAZIONE</div><nav><button data-page="home" class="active"><span>▦</span> Panoramica</button><button data-page="bbs"><span>▤</span> BBS <b id="nav-count">—</b></button><button data-page="network"><span>⌘</span> Rete & nodi</button></nav><div class="side-station">Stazione BPQ</div><div class="profile"><div class="avatar">BP</div><div>Sysop<small>BPQ</small></div><button id="logout" title="Esci" aria-label="Esci dal pannello">↗</button></div></aside>
+1 -1
View File
@@ -5,7 +5,7 @@ $('#home .page-heading').replaceWith(missionHead);
function graph(history,keys,id,minimum=1){const width=350,height=85,pad=5;const values=history.flatMap(s=>keys.map(k=>s[k])).filter(v=>typeof v==='number'&&Number.isFinite(v));if(!values.length)return '<div class="graph-empty">Nessun campione disponibile</div>';const min=Math.min(0,...values),max=Math.max(minimum,...values),range=max-min||1;const x=i=>pad+i*(width-pad*2)/Math.max(1,history.length-1),y=v=>height-pad-(v-min)*(height-pad*2)/range;const lines=keys.map((key,j)=>{let path='',breakLine=true;history.forEach((s,i)=>{const value=s[key];if(typeof value!=='number'||!Number.isFinite(value)){breakLine=true;return;}path+=(breakLine?'M':'L')+x(i).toFixed(2)+' '+y(value).toFixed(2)+' ';breakLine=false;});return `<path class="graph-line line-${j}" d="${path}"/>`}).join('');return `<svg viewBox="0 0 ${width} ${height}" preserveAspectRatio="none" role="img" aria-label="Grafico ${esc(id)}"><path class="graph-grid" d="M0 20 H350 M0 45 H350 M0 70 H350"/>${lines}</svg>`;}
function renderTelemetry(data){modemTelemetry=data;const c=data.current;if(!c)return;const history=data.history.slice(-120);$('#radio-status').textContent=window.bpqRadioControl?.txSuspended?'TX SOSPESO':!c.available?'OFFLINE':c.active?'LINK ATTIVO':'IN ASCOLTO';$('#modem-session').classList.toggle('idle',!c.active);$('#modem-session').classList.toggle('connected',!!c.active);$('#session-label').textContent=window.bpqRadioControl?.txSuspended?'PORTE RADIO IN PAUSA':c.connecting?'CHIAMATA IN CORSO':c.active?'CONNESSIONE RADIO':'STAZIONE IN ASCOLTO';$('#caller-call').textContent=c.active?c.caller||'—':station.nodeCall;$('#called-call').textContent=c.active?c.called||'—':station.alias;$('#call-arrow').textContent=c.active?'→':'◉';$('#caller-label').textContent=c.active?'CHIAMANTE':'NODO LOCALE';$('#called-label').textContent=c.active?'CHIAMATO':'ALIAS';$('#session-detail').textContent=c.active?(c.connecting?'Attendo risposta':(c.caller||'').replace(/-\d+$/,'')===station.call.replace(/-\d+$/,'')?'Chiamata in uscita':'Chiamata in ingresso'):station.radio?.name||'Nessuna porta modem configurata';$('#radio-freq').textContent=c.frequency||'—';$('#radio-scan').textContent=c.scan?'● Scansione attiva':c.active?'● Frequenza bloccata':'—';$('#radio-channel').textContent=c.available?(c.busy?'Canale occupato':'Canale libero'):'—';$('#radio-modem').textContent=c.available?station.radio?.name||'Modem BPQ':'Modem non disponibile';$('#radio-snr').textContent=c.lastSnr!=null?c.lastSnr.toFixed(1)+' dB':'—';$('#bps-value').textContent=c.available?Math.round((c.txBps||0)+(c.rxBps||0)).toLocaleString(BPQI18n.locale()):'—';$('#bps-caption').textContent='TX '+Math.round(c.txBps||0).toLocaleString(BPQI18n.locale())+' / RX '+Math.round(c.rxBps||0).toLocaleString(BPQI18n.locale())+' bit/s · dati BPQ';$('#snr-value').textContent=c.snr!=null?c.snr.toFixed(1)+' dB':'—';$('#vara-cpu-value').textContent=c.varaCpu!=null?c.varaCpu.toFixed(1)+'%':'—';$('#system-cpu-value').textContent=c.cpu!=null?c.cpu.toFixed(1)+'%':'—';$('#snr-caption').textContent=c.active?'SNR esposto da BPQ':'In attesa della prossima connessione';$('#modem-traffic').textContent='TX '+size(c.sent||0)+' / RX '+size(c.received||0);$('#bps-chart').innerHTML=graph(history,['txBps','rxBps'],'traffico BPQ TX RX',100);$('#snr-chart').innerHTML=graph(history,['snr'],'SNR',10);$('#vara-cpu-chart').innerHTML=graph(history,['varaCpu'],'CPU VARA',5);$('#system-cpu-chart').innerHTML=graph(history,['cpu'],'CPU sistema',10);}
async function pollTelemetry(){if(!csrf||modemPolling)return;modemPolling=true;try{renderTelemetry(await api('/telemetry',{busy:false}))}catch{}finally{modemPolling=false}}
const missionDashboard=loadDashboard;loadDashboard=async function(...args){await missionDashboard(...args);if(modemTelemetry)renderTelemetry(modemTelemetry);pollTelemetry();};setInterval(()=>{if(csrf&&!document.hidden)pollTelemetry()},2000);pollTelemetry();
const missionDashboard=loadDashboard;loadDashboard=async function(...args){await missionDashboard(...args);if(modemTelemetry)renderTelemetry(modemTelemetry);pollTelemetry();};setInterval(()=>{if(csrf&&!document.hidden&&!window.BPQDetached?.view)pollTelemetry()},2000);pollTelemetry();
const fullscreenButton=document.createElement('button');fullscreenButton.id='fullscreen-toggle';fullscreenButton.className='icon-button';fullscreenButton.textContent='⛶';fullscreenButton.setAttribute('aria-label','Schermo intero');fullscreenButton.title='Schermo intero';$('#refresh').after(fullscreenButton);
fullscreenButton.onclick=async()=>{try{if(document.fullscreenElement)await document.exitFullscreen();else await document.documentElement.requestFullscreen();}catch{toast('Schermo intero non disponibile in questo browser. Prova F11.');}};
document.addEventListener('fullscreenchange',()=>{const active=!!document.fullscreenElement;fullscreenButton.textContent=active?'⊡':'⛶';fullscreenButton.title=active?'Torna alla finestra':'Schermo intero';fullscreenButton.setAttribute('aria-label',fullscreenButton.title);fullscreenButton.setAttribute('aria-pressed',String(active));});
+1 -1
View File
@@ -6,7 +6,7 @@ const originalNavigate=navigate;navigate=function(next){originalNavigate(next);i
function filtered(){const port=$('#monitor-port').value,dir=$('#monitor-direction').value,q=$('#monitor-search').value.toLowerCase();return events.filter(e=>(!port||String(e.port)===port)&&(!dir||e.direction===dir)&&(!q||e.text.toLowerCase().includes(q)));}
function render(){const list=filtered(),area=$('#monitor-console');area.innerHTML=list.map(e=>`<article class="monitor-frame ${e.direction.toLowerCase()}"><div><span class="monitor-direction">${esc(e.direction)}</span><span class="monitor-port">${e.port?'P'+e.port:'BPQ'}</span></div><pre>${esc(e.text)}</pre></article>`).join('')||'<p class="monitor-empty">'+(state==='online'?'In ascolto. Nessun traffico corrispondente ai filtri.':'Avvia il monitor per seguire il traffico BPQ.')+'</p>';$('#monitor-count').textContent=list.length+' frame · '+events.length+' in memoria'+(paused?' · visualizzazione in pausa':'');if($('#monitor-follow').checked)area.scrollTop=area.scrollHeight;displayedCursor=cursor;}
function status(data){state=data.state;$('#monitor-state').className='chat-status '+state;$('#monitor-state').textContent=data.error||({online:'● In ascolto',connecting:'Connessione…',offline:'Disconnesso',error:'Non disponibile'}[state]);$('#monitor-connect').hidden=state==='online';$('#monitor-connect').disabled=state==='connecting';$('#monitor-stop').hidden=!['online','connecting'].includes(state);const current=$('#monitor-port').value;$('#monitor-port').innerHTML='<option value="">Tutte le porte</option>'+data.ports.map(p=>`<option value="${p.id}">${p.id} · ${esc(p.name)}</option>`).join('');$('#monitor-port').value=current;}
async function poll(){if(!csrf||busy)return;busy=true;try{let data=await api('/monitor?after='+cursor,{busy:false});if(data.latest<cursor){cursor=0;events=[];data=await api('/monitor?after=0');}status(data);events.push(...data.events);events=events.slice(-1000);cursor=data.latest;if(!paused&&(cursor!==displayedCursor||!events.length))render();}catch(e){if(page==='monitor')toast(e.message)}finally{busy=false;}}
async function poll(){if(!csrf||busy||window.BPQDetached&&!window.BPQDetached.shouldPoll('monitor'))return;busy=true;try{let data=await api('/monitor?after='+cursor,{busy:false});if(data.latest<cursor){cursor=0;events=[];data=await api('/monitor?after=0');}status(data);events.push(...data.events);events=events.slice(-1000);cursor=data.latest;if(!paused&&(cursor!==displayedCursor||!events.length))render();}catch(e){if(page==='monitor')toast(e.message)}finally{busy=false;}}
$('#monitor-connect').onclick=async()=>{try{status(await api('/monitor/connect',{method:'POST',body:'{}'}));await poll();}catch(e){toast(e.message)}};
$('#monitor-stop').onclick=async()=>{try{await api('/monitor/disconnect',{method:'POST',body:'{}'});await poll()}catch(e){toast(e.message)}};
$('#monitor-pause').onclick=()=>{paused=!paused;$('#monitor-pause').textContent=paused?'Riprendi':'Pausa';if(!paused)render();else $('#monitor-count').textContent+=' · visualizzazione in pausa';};
+16
View File
@@ -0,0 +1,16 @@
<!doctype html>
<html lang="it">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="theme-color" content="#11110e"><title>BPQ Console · Terminal</title>
<script src="/ui-config.js"></script><script src="/i18n.js?v=20261019-terminal-window"></script>
<link rel="stylesheet" href="/style.css"><link rel="stylesheet" href="/dark.css"><link rel="stylesheet" href="/terminal.css?v=20261019-themes">
<link rel="stylesheet" href="/detach.css?v=20261019-multi"><script defer src="/detach.js?v=20261019-multi"></script><script defer src="/terminal-window.js"></script><script defer src="/terminal.js?v=20261019-themes"></script>
</head>
<body class="terminal-detached">
<nav hidden></nav><span id="breadcrumb" hidden></span><button id="logout" hidden></button>
<main></main>
<section id="terminal-window-error" hidden role="status"><h1>Terminale</h1><p id="terminal-window-error-text"></p><a class="secondary" href="/#terminal">Apri il pannello</a></section>
<div id="toast" hidden role="status"></div>
</body>
</html>
+22
View File
@@ -0,0 +1,22 @@
// A detached view shares the authenticated browser session and its existing Telnet socket.
const $=selector=>document.querySelector(selector);
let station={features:{}},csrf='',page='terminal';
function navigate(){page='terminal';$('#terminal').hidden=false;}
function toast(text){$('#toast').textContent=text;$('#toast').hidden=false;clearTimeout(toast.timer);toast.timer=setTimeout(()=>$('#toast').hidden=true,6500);}
function terminalWindowError(text){document.dispatchEvent(new Event('bpq-detach-auth-lost'));csrf='';station={features:{}};$('#terminal').hidden=true;$('#terminal-window-error').hidden=false;$('#terminal-window-error-text').textContent=BPQI18n.t(text);}
async function api(url,options={}){
const {busy,...request}=options;
const response=await fetch('/api'+url,{...request,headers:{'Content-Type':'application/json',...(request.method==='POST'?{'X-CSRF-Token':csrf}:{}),...request.headers}});
const data=await response.json();
if(!response.ok){if(response.status===401)terminalWindowError('Sessione scaduta. Accedi nuovamente dal pannello.');throw new Error(data.error||'Richiesta fallita');}
return data;
}
$('#logout').onclick=async()=>{};
document.addEventListener('DOMContentLoaded',async()=>{
try{
const user=await api('/session');station=user.config;csrf=user.csrf;
if(!station.features.terminal){terminalWindowError('Terminale non configurato in BPQ.');return;}
document.title='BPQ Console · '+station.call+' · Terminal';
document.dispatchEvent(new Event('station-ready'));
}catch(error){if(csrf||!$('#terminal-window-error-text').textContent)terminalWindowError(error.message);}
});
+24
View File
@@ -1,3 +1,27 @@
#terminal{height:calc(100dvh - 76px);display:flex;flex-direction:column;min-height:560px;padding:24px 28px}.terminal-heading{display:flex;align-items:center;justify-content:space-between;gap:18px;margin-bottom:20px;flex-shrink:0}.terminal-heading h1{font-size:28px;font-weight:500}.terminal-heading p{font-size:11px;color:var(--muted);margin-top:5px}.terminal-actions{display:flex;gap:9px}.terminal-actions button{font-size:11px}.phosphor-case{flex:1;min-height:0;display:flex;flex-direction:column;border-radius:16px;border:1px solid #51452b;background:#11110e;padding:7px;box-shadow:0 16px 45px #0005,inset 0 1px #8e774822;overflow:hidden}.phosphor-top,.phosphor-bottom{display:flex;justify-content:space-between;align-items:center;gap:18px;color:#9e844d;font:10px Consolas,'Courier New',monospace;letter-spacing:1px;flex-shrink:0;padding:14px 19px}.phosphor-top{border-bottom:1px solid #4a3a1c}.phosphor-top>span:first-child{display:flex;align-items:center;gap:10px}.phosphor-top i{display:inline-block;width:6px;height:6px;background:#5d5033;border-radius:50%}.phosphor-top i.online{background:#ffd477;box-shadow:0 0 9px #ffbd4d}.phosphor-screen{flex:1;min-height:0;overflow:auto;padding:24px 26px;color:#ffd376;background:radial-gradient(ellipse at center,#241d0d 0%,#131106 70%,#0b0b06 100%);box-shadow:inset 0 0 55px #000a;scrollbar-color:#72572a #151207;position:relative;isolation:isolate}.phosphor-screen:before{content:'';position:absolute;inset:0;min-height:100%;pointer-events:none;background:repeating-linear-gradient(0deg,transparent 0 2px,#0002 2px 3px);z-index:1}.phosphor-screen pre{font:14px/1.55 Consolas,'Courier New',monospace;white-space:pre-wrap;overflow-wrap:anywhere;tab-size:8;letter-spacing:.2px;text-shadow:0 0 5px #ffc14b66;margin:0;position:relative;z-index:2;user-select:text}.phosphor-screen pre::selection{background:#94702f;color:#fff2c4}.phosphor-cursor{display:inline-block;color:#ffda84;font:16px Consolas,monospace;animation:phosphor-blink 1.1s steps(1) infinite;text-shadow:0 0 8px #ffc354}#terminal-form{display:flex;align-items:center;gap:12px;margin:0;padding:12px 20px;border-top:1px solid #4a3a1c;background:#1c180e;color:#ffd376;flex-shrink:0}#terminal-form label{font:18px Consolas,monospace}#terminal-input{flex:1;width:0;min-width:0;background:transparent;border:0;border-radius:0;box-shadow:none;color:#ffda8a;font:14px Consolas,'Courier New',monospace;padding:10px 0;caret-color:#ffe2a2}#terminal-input::placeholder{color:#82704b}#terminal-input:focus-visible{outline:0;box-shadow:0 1px #c09c4a}#terminal-send{background:#30250f;border:1px solid #665126;color:#e9c779;font:11px Consolas,monospace;padding:10px 13px;border-radius:5px}.phosphor-bottom{font-size:9px;padding:12px 18px;letter-spacing:.5px;flex-wrap:wrap}.phosphor-bottom button{background:transparent;border:0;color:#ffda84;font:inherit;padding:0}@keyframes phosphor-blink{50%{opacity:0}}@media(prefers-reduced-motion:reduce){.phosphor-cursor{animation:none}}@media(max-width:850px){.terminal-heading{align-items:flex-start;flex-direction:column}.terminal-actions{flex-wrap:wrap}.phosphor-screen{padding:16px}.phosphor-screen pre{font-size:12px}.phosphor-top{font-size:9px;letter-spacing:.3px}}@media(max-width:600px){#terminal{padding:20px 14px;height:calc(100dvh - 175px);min-height:510px}.terminal-heading h1{font-size:25px}.terminal-actions button{padding:8px 10px}.phosphor-top{padding:12px 10px}#terminal-form{padding:10px 12px}.phosphor-bottom>span:nth-child(2){display:none}nav{flex-wrap:wrap}}
@media(min-width:601px){.sidebar:has([data-page=terminal]) nav{min-height:100px;overflow-y:auto;flex-shrink:1;scrollbar-width:thin}.sidebar:has([data-page=terminal])>.brand,.sidebar:has([data-page=terminal])>.side-label,.sidebar:has([data-page=terminal])>.profile{flex-shrink:0}.sidebar:has([data-page=terminal])>.side-station{padding-block:14px;flex-shrink:0}}
/* Coordinated phosphor palettes shared by embedded and detached terminal views. */
#terminal{--phosphor:#ffd376;--phosphor-rgb:255,193,75;--phosphor-muted:#a78c57;--phosphor-bg:#100e08;--phosphor-surface:#1c180e}
#terminal[data-theme=green]{--phosphor:#9cf7ad;--phosphor-rgb:109,244,139;--phosphor-muted:#71a781;--phosphor-bg:#070f0a;--phosphor-surface:#101c14}
#terminal[data-theme=ice]{--phosphor:#b3edff;--phosphor-rgb:113,212,255;--phosphor-muted:#779eaf;--phosphor-bg:#080f15;--phosphor-surface:#101c26}
#terminal[data-theme=violet]{--phosphor:#ddbcff;--phosphor-rgb:186,132,255;--phosphor-muted:#a38bb6;--phosphor-bg:#100a16;--phosphor-surface:#1b1325}
#terminal[data-theme=white]{--phosphor:#e8eee9;--phosphor-rgb:216,230,222;--phosphor-muted:#91a29a;--phosphor-bg:#0c100f;--phosphor-surface:#171e1b}
#terminal .phosphor-case{border-color:rgba(var(--phosphor-rgb),.28);background:var(--phosphor-bg);box-shadow:0 16px 45px #0005,inset 0 1px rgba(var(--phosphor-rgb),.12)}
#terminal .phosphor-top,#terminal .phosphor-bottom{color:var(--phosphor-muted);border-color:rgba(var(--phosphor-rgb),.2)}
#terminal .phosphor-top i.online{background:var(--phosphor);box-shadow:0 0 9px rgba(var(--phosphor-rgb),.8)}
#terminal .phosphor-screen{color:var(--phosphor);background:radial-gradient(ellipse at center,rgba(var(--phosphor-rgb),.075),transparent 80%),var(--phosphor-bg);scrollbar-color:var(--phosphor-muted) var(--phosphor-bg)}
#terminal .phosphor-screen pre{color:var(--phosphor);text-shadow:0 0 5px rgba(var(--phosphor-rgb),.32)}
#terminal .phosphor-screen pre::selection{background:rgba(var(--phosphor-rgb),.35);color:var(--phosphor)}
#terminal .phosphor-cursor{color:var(--phosphor);text-shadow:0 0 8px rgba(var(--phosphor-rgb),.65)}
#terminal-form{background:var(--phosphor-surface);color:var(--phosphor);border-color:rgba(var(--phosphor-rgb),.22)}
#terminal-input{color:var(--phosphor);caret-color:var(--phosphor)}#terminal-input::placeholder{color:var(--phosphor-muted)}#terminal-input:focus-visible{box-shadow:0 1px var(--phosphor-muted)}
#terminal-send{color:var(--phosphor);background:rgba(var(--phosphor-rgb),.08);border-color:rgba(var(--phosphor-rgb),.3)}#terminal .phosphor-bottom button{color:var(--phosphor)}
.terminal-actions{flex-wrap:wrap;justify-content:flex-end}.terminal-theme-bar{display:flex;align-items:center;gap:18px;margin:-5px 0 14px;flex-shrink:0}.terminal-theme-bar>span{color:#8396a6;font-size:10px;letter-spacing:1.5px;text-transform:uppercase}.terminal-theme-bar>div{display:flex;gap:5px;flex-wrap:wrap}
.terminal-theme-bar button{display:inline-flex;align-items:center;gap:7px;padding:6px 10px;border:1px solid transparent;border-radius:6px;background:transparent;color:#899dad;font-size:11px;line-height:1.3}.terminal-theme-bar button::before{content:'';width:7px;height:7px;border-radius:50%;background:var(--theme-dot)}
[data-terminal-theme=amber]{--theme-dot:#ffd376}[data-terminal-theme=green]{--theme-dot:#9cf7ad}[data-terminal-theme=ice]{--theme-dot:#b3edff}[data-terminal-theme=violet]{--theme-dot:#ddbcff}[data-terminal-theme=white]{--theme-dot:#e8eee9}
.terminal-theme-bar button:hover{background:#abc4d40a;color:#cddde8}.terminal-theme-bar button[aria-pressed=true]{color:var(--theme-dot);border-color:#8ba6bc35;background:#abc4d40c}
body.terminal-detached{background:#0d141c;color:#d7e3ec;overflow:hidden}.terminal-detached main{margin:0;padding:0;max-width:none;width:100%;height:100dvh}.terminal-detached #terminal{height:100dvh;min-height:0;padding:20px}.terminal-detached .terminal-heading{margin-bottom:15px}.terminal-detached .terminal-heading h1{font-size:23px}.terminal-detached .phosphor-screen{padding:20px 23px}
#terminal-window-error{margin:10vh auto;max-width:460px;padding:28px;border:1px solid #354656;border-radius:14px;background:#172330}#terminal-window-error p{margin:15px 0 22px;color:#a5bbcc}#terminal-window-error a{text-decoration:none}
@media(max-width:650px){.terminal-detached #terminal{padding:12px}.terminal-theme-bar{gap:10px;align-items:flex-start}.terminal-theme-bar button{padding:6px 7px}.terminal-actions{justify-content:flex-start}.terminal-detached .phosphor-screen{padding:15px}.terminal-theme-bar>span{padding-top:6px}}
+12 -2
View File
@@ -1,13 +1,23 @@
(() => {
const detached=document.body.classList.contains('terminal-detached');
const nav=document.createElement('button');nav.dataset.page='terminal';nav.innerHTML='<span>▸_</span> Terminale';nav.onclick=()=>navigate('terminal');$('nav').append(nav);
const section=document.createElement('section');section.id='terminal';section.className='page';section.hidden=true;section.innerHTML=`<div class="terminal-heading"><div><h1>Terminale</h1><p>BPQ · Telnet</p></div><div class="terminal-actions"><button id="terminal-clear" class="secondary">Pulisci</button><button id="terminal-export" class="secondary">Salva testo</button><button id="terminal-connect" class="primary">Collega</button><button id="terminal-stop" class="secondary" hidden>Disconnetti</button></div></div><div class="phosphor-case"><div class="phosphor-top"><span><i id="terminal-led"></i> BPQ / REMOTE TERMINAL</span><span id="terminal-state" role="status">OFFLINE</span></div><div class="phosphor-screen" id="terminal-screen" tabindex="0" aria-label="Terminale Telnet BPQ"><pre id="terminal-output" aria-live="off"></pre><span class="phosphor-cursor" aria-hidden="true">▌</span></div><form id="terminal-form" autocomplete="off"><label for="terminal-input">&gt;</label><input id="terminal-input" aria-label="Comando Telnet" placeholder="Collega il terminale per iniziare" spellcheck="false" autocapitalize="off" maxlength="1000" disabled><button type="submit" id="terminal-send" disabled aria-label="Invia comando">INVIO ↵</button></form><div class="phosphor-bottom"><span id="terminal-endpoint">TELNET · BPQ LOCALE</span><span>↑ ↓ cronologia · Invio per inviare</span><button type="button" id="terminal-follow" hidden>↓ Torna al fondo</button></div></div>`;$('main').append(section);
const section=document.createElement('section');section.id='terminal';section.className='page';section.hidden=true;section.innerHTML=`<div class="terminal-heading"><div><h1>Terminale</h1><p>BPQ · Telnet</p></div><div class="terminal-actions"><button id="terminal-detach" class="secondary" title="Apri il terminale in una finestra separata">↗ Stacca</button><button id="terminal-dock" class="secondary" hidden>↙ Torna al pannello</button><button id="terminal-clear" class="secondary">Pulisci</button><button id="terminal-export" class="secondary">Salva testo</button><button id="terminal-connect" class="primary">Collega</button><button id="terminal-stop" class="secondary" hidden>Disconnetti</button></div></div><div class="terminal-theme-bar"><span>Fosfori</span><div role="group" aria-label="Stile del terminale"><button type="button" data-terminal-theme="amber" aria-pressed="true">Amber</button><button type="button" data-terminal-theme="green" aria-pressed="false">Green</button><button type="button" data-terminal-theme="ice" aria-pressed="false">Ice</button><button type="button" data-terminal-theme="violet" aria-pressed="false">Violet</button><button type="button" data-terminal-theme="white" aria-pressed="false">White</button></div></div><div class="phosphor-case"><div class="phosphor-top"><span><i id="terminal-led"></i> BPQ / REMOTE TERMINAL</span><span id="terminal-state" role="status">OFFLINE</span></div><div class="phosphor-screen" id="terminal-screen" tabindex="0" aria-label="Terminale Telnet BPQ"><pre id="terminal-output" aria-live="off"></pre><span class="phosphor-cursor" aria-hidden="true">▌</span></div><form id="terminal-form" autocomplete="off"><label for="terminal-input">&gt;</label><input id="terminal-input" aria-label="Comando Telnet" placeholder="Collega il terminale per iniziare" spellcheck="false" autocapitalize="off" maxlength="1000" disabled><button type="submit" id="terminal-send" disabled aria-label="Invia comando">INVIO ↵</button></form><div class="phosphor-bottom"><span id="terminal-endpoint">TELNET · BPQ LOCALE</span><span>↑ ↓ cronologia · Invio per inviare</span><button type="button" id="terminal-follow" hidden>↓ Torna al fondo</button></div></div>`;$('main').append(section);if(detached)section.hidden=false;
const themes=['amber','green','ice','violet','white'];
function applyTheme(value){const theme=themes.includes(value)?value:'amber';section.dataset.theme=theme;section.querySelectorAll('[data-terminal-theme]').forEach(button=>button.setAttribute('aria-pressed',String(button.dataset.terminalTheme===theme)));}
function savedTheme(){try{return localStorage.getItem('bpq-terminal-theme');}catch{return 'amber';}}
applyTheme(savedTheme());
section.querySelector('.terminal-theme-bar').onclick=event=>{const theme=event.target.closest('[data-terminal-theme]')?.dataset.terminalTheme;if(!themes.includes(theme))return;applyTheme(theme);try{localStorage.setItem('bpq-terminal-theme',theme);}catch{}};
window.addEventListener('storage',event=>{if(event.key==='bpq-terminal-theme')applyTheme(event.newValue);});
$('#terminal-detach').hidden=detached;$('#terminal-dock').hidden=!detached;
$('#terminal-detach').onclick=()=>{if(window.BPQDetached){window.BPQDetached.open('terminal');return;}const popup=window.open('/terminal-window','bpq-console-terminal','popup=yes,width=1120,height=780,resizable=yes,scrollbars=yes');if(popup)popup.focus();else toast(BPQI18n.t('Consenti le finestre popup per aprire il terminale separato.'));};
$('#terminal-dock').onclick=()=>{if(window.BPQDetached){window.BPQDetached.dock('terminal');return;}try{if(window.opener&&!window.opener.closed){window.opener.location.hash='#terminal';window.opener.focus();window.close();return;}}catch{}window.location.assign('/#terminal');};
let cursor=0,busy=false,state='offline',buffer='',following=true,history=[],historyIndex=0,draft='',sending=false,generation=0;
const area=$('#terminal-screen'),output=$('#terminal-output'),input=$('#terminal-input');
const previousNavigate=navigate;navigate=function(next){previousNavigate(next);if(next==='terminal'){$('#breadcrumb').textContent='Stazione / Terminale';poll();}};
function bottom(){area.scrollTop=area.scrollHeight;following=true;$('#terminal-follow').hidden=true;}
function append(text){buffer=(buffer+text).slice(-200000);output.textContent=buffer;if(following)bottom();}
function status(data){const wasOnline=state==='online';state=data.state;const online=state==='online',connecting=state==='connecting';$('#terminal-state').textContent=data.error||({online:'ONLINE',connecting:'COLLEGAMENTO…',offline:'OFFLINE',error:'ERRORE'}[state]||state);$('#terminal-led').classList.toggle('online',online);$('#terminal-connect').hidden=online||connecting;$('#terminal-stop').hidden=!online&&!connecting;input.disabled=!online;$('#terminal-send').disabled=!online||sending;input.placeholder=online?'Scrivi un comando…':'Collega il terminale per iniziare';$('#terminal-endpoint').textContent='TELNET · 127.0.0.1:'+data.port;if(online&&!wasOnline&&page==='terminal')input.focus();}
async function poll(){if(!csrf||busy||!station.features.terminal)return;busy=true;const current=generation;try{const d=await api('/terminal?after='+cursor,{busy:false});if(current!==generation)return;if(d.latest<cursor){cursor=0;buffer='';}status(d);for(const e of d.events)append(e.text);cursor=d.latest;}catch(e){if(page==='terminal')$('#terminal-state').textContent=e.message;}finally{busy=false;}}
async function poll(){if(!csrf||busy||!station.features.terminal||window.BPQDetached&&!window.BPQDetached.shouldPoll('terminal'))return;busy=true;const current=generation;try{const d=await api('/terminal?after='+cursor,{busy:false});if(current!==generation)return;if(d.latest<cursor){cursor=0;buffer='';}status(d);for(const e of d.events)append(e.text);cursor=d.latest;}catch(e){if(page==='terminal')$('#terminal-state').textContent=e.message;}finally{busy=false;}}
$('#terminal-connect').onclick=async()=>{const button=$('#terminal-connect');button.disabled=true;try{const d=await api('/terminal/connect',{method:'POST',body:'{}'});buffer='';output.textContent='';following=true;cursor=0;status(d);await poll();}catch(e){toast(e.message);}finally{button.disabled=false;}};
$('#terminal-stop').onclick=async()=>{try{status(await api('/terminal/disconnect',{method:'POST',body:'{}'}));await poll();}catch(e){toast(e.message);}};
$('#terminal-form').onsubmit=async e=>{e.preventDefault();if(sending||state!=='online')return;const text=input.value;sending=true;$('#terminal-send').disabled=true;try{await api('/terminal/send',{method:'POST',body:JSON.stringify({text})});if(text&&history.at(-1)!==text)history.push(text);history=history.slice(-100);historyIndex=history.length;draft='';input.value='';await poll();}catch(e){toast(e.message);}finally{sending=false;$('#terminal-send').disabled=state!=='online';if(state==='online')input.focus();}};