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.
63 lines
16 KiB
JavaScript
63 lines
16 KiB
JavaScript
import {incoming} from '/notifications.js';
|
||
let soundOn=localStorage.getItem('alnode-sound')!=='no',audio=null,chatLastId=0,chatState='offline',chatPollBusy=false;
|
||
const soundButton=document.createElement('button');soundButton.id='sound-toggle';soundButton.className='icon-button sound-toggle';soundButton.setAttribute('aria-label','Attiva o disattiva suoni');$('#refresh').before(soundButton);
|
||
function soundLabel(){soundButton.textContent=soundOn?'♪':'♩';soundButton.classList.toggle('enabled',soundOn);soundButton.title=soundOn?'Suono attivo':'Attiva suono notifiche';soundButton.setAttribute('aria-pressed',String(soundOn))}soundLabel();
|
||
async function prepareAudio(){try{audio??=new (window.AudioContext||window.webkitAudioContext)();if(audio.state!=='running')await audio.resume();return audio.state==='running';}catch{return false}}
|
||
async function chime(force=false){if(!soundOn&&!force)return;if(!await prepareAudio()){soundButton.title='Clicca per attivare l’audio';return;}const t=audio.currentTime+.025;const compressor=audio.createDynamicsCompressor();compressor.threshold.value=-8;compressor.knee.value=10;compressor.ratio.value=3;compressor.connect(audio.destination);for(const [offset,freq]of [[0,659.25],[.23,830.61],[.46,987.77]]){const o=audio.createOscillator(),g=audio.createGain();o.type='triangle';o.frequency.value=freq;g.gain.setValueAtTime(0,t+offset);g.gain.linearRampToValueAtTime(.24,t+offset+.02);g.gain.exponentialRampToValueAtTime(.0001,t+offset+.75);o.connect(g);g.connect(compressor);o.start(t+offset);o.stop(t+offset+.8);}setTimeout(()=>compressor.disconnect(),1700)}
|
||
soundButton.onclick=async()=>{soundOn=!soundOn;localStorage.setItem('alnode-sound',soundOn?'yes':'no');soundLabel();if(soundOn)await chime();};
|
||
for(const event of ['pointerdown','keydown'])document.addEventListener(event,()=>{if(soundOn&&audio?.state!=='running')prepareAudio()},{passive:true});
|
||
const soundTest=document.createElement('button');soundTest.id='notification-test';soundTest.className='icon-button';soundTest.textContent='♬';soundTest.title='Prova notifica e suono';soundTest.setAttribute('aria-label','Prova notifica e suono');soundButton.after(soundTest);soundTest.onclick=async()=>{soundOn=true;localStorage.setItem('alnode-sound','yes');soundLabel();arrival('mail','Notifica di prova','Audio attivato · avviso per nuova posta o bollettini');await chime(true);soundTest.dataset.audioState=audio?.state||'unavailable';if(audio?.state!=='running')toast('Audio non attivato dal browser: verifica i permessi audio del sito.');};
|
||
const stack=document.createElement('div');stack.className='notification-stack';stack.setAttribute('aria-live','polite');document.body.append(stack);
|
||
function arrival(kind,title,detail,ids=[]){const item=document.createElement('div');item.className='arrival-toast '+kind;item.innerHTML=`<span>${kind==='mail'?'✉':'▤'}</span><div><strong>${esc(title)}</strong><small>${esc(detail)}</small></div><button aria-label="Chiudi notifica">×</button>`;item.querySelector('button').onclick=e=>{e.stopPropagation();item.remove()};item.onclick=()=>{navigate('bbs');if(ids.length===1)readMessage(ids[0]);item.remove()};stack.append(item);while(stack.children.length>4)stack.firstChild.remove();setTimeout(()=>item.remove(),12000)}
|
||
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&&!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);
|
||
const oldNavigate=navigate;navigate=function(next){oldNavigate(next);$('#breadcrumb').textContent='Stazione / '+({home:'Panoramica',bbs:'BBS',network:'Rete',chat:'Chat',winlink:'Winlink'}[next]);if(next==='chat')pollChat();window.scrollTo({top:0,behavior:'instant'})};
|
||
let chatFollowing=true,chatUnread=0,chatScrolling=false;
|
||
const chatArea=$('#chat-messages');chatArea.tabIndex=0;chatArea.setAttribute('aria-label','Conversazione chat');
|
||
const chatJump=document.createElement('button');chatJump.id='chat-jump';chatJump.className='chat-jump';chatJump.hidden=true;chatJump.type='button';chatJump.setAttribute('aria-label','Vai agli ultimi messaggi');$('.chat-main').insertBefore(chatJump,$('#chat-form'));
|
||
function updateChatJump(){chatJump.hidden=chatFollowing;chatJump.textContent=chatUnread?`${chatUnread} ${chatUnread===1?'nuovo messaggio':'nuovi messaggi'} ↓`:'Ultimi messaggi ↓';}
|
||
function chatToBottom(){if(page!=='chat')return;chatFollowing=true;chatUnread=0;chatScrolling=true;updateChatJump();requestAnimationFrame(()=>{chatArea.scrollTop=chatArea.scrollHeight;requestAnimationFrame(()=>{chatScrolling=false;});});}
|
||
chatJump.onclick=chatToBottom;
|
||
chatArea.addEventListener('scroll',()=>{if(chatScrolling||page!=='chat')return;chatFollowing=chatArea.scrollHeight-chatArea.scrollTop-chatArea.clientHeight<64;if(chatFollowing)chatUnread=0;updateChatJump();},{passive:true});
|
||
new ResizeObserver(()=>{if(chatFollowing&&page==='chat')chatToBottom();}).observe(chatArea);
|
||
const navigateWithChat=navigate;navigate=function(next){navigateWithChat(next);if(next==='chat'){if(chatFollowing)chatToBottom();else updateChatJump();}};
|
||
function renderChat(data){
|
||
chatState=data.state;const online=data.state==='online';
|
||
$('#chat-state').className='chat-status '+data.state;$('#chat-state').textContent=({offline:'Disconnesso',connecting:'Connessione…',online:'● Connesso · '+station.call,error:'Connessione interrotta'}[data.state]);$('#chat-connect').hidden=online;$('#chat-connect').disabled=data.state==='connecting';$('#chat-disconnect').hidden=!online;$('#chat-input').disabled=!online;$('#chat-send').disabled=!online;$('#chat-input').placeholder=online?'Scrivi alla stanza…':'Connettiti per scrivere…';
|
||
$('#chat-room-name').textContent='# '+data.topic;$('#chat-presence-count').textContent=online?data.users.filter(u=>u.topic.toLowerCase()===data.topic.toLowerCase()).length+' nella stanza':'Non connesso';$('#chat-user-count').textContent=online?data.users.length:'—';
|
||
$('#chat-users').innerHTML=online?data.users.map(u=>`<button class="chat-user" data-call="${esc(u.call)}" title="${esc(u.qth)}" aria-label="Messaggio privato a ${esc(u.call)}"><span class="chat-avatar">${esc(u.call.slice(0,2))}</span><div><b>${esc(u.call)}</b><div class="chat-user-name">${esc(u.name)}</div><small>${esc(u.node)} · ${esc(u.topic)}</small></div><span class="presence-dot ${u.idle>300?'idle':''}" title="${u.idle>300?'Inattivo':'Attivo'}"></span></button>`).join('')||'<p class="empty">Nessun utente rilevato</p>':'<p class="chat-offline-note">Connettiti per vedere chi è presente.</p>';
|
||
const recipient=$('#chat-recipient').value;$('#chat-recipient').innerHTML='<option value="">Tutta la stanza</option>'+data.users.filter(u=>u.call!==station.call).map(u=>`<option value="${esc(u.call)}">Privato · ${esc(u.call)}</option>`).join('');$('#chat-recipient').value=recipient;if(!$('#chat-recipient').value)$('#chat-recipient').value='';$('#chat-recipient').disabled=!online;if(online&&$('#chat-recipient').value)$('#chat-input').placeholder='Messaggio privato a '+$('#chat-recipient').value+'…';
|
||
$$('.chat-user').forEach(b=>b.onclick=()=>{$('#chat-recipient').value=b.dataset.call===station.call?'':b.dataset.call;$('#chat-input').placeholder=b.dataset.call===station.call?'Scrivi alla stanza…':'Messaggio privato a '+b.dataset.call+'…';$('#chat-input').focus();});
|
||
$('#chat-topics').innerHTML=[...new Set(['General',...data.topics,data.topic])].map(t=>`<button class="room-button ${t.toLowerCase()===data.topic.toLowerCase()?'active':''}" data-topic="${esc(t)}"># ${esc(t)}</button>`).join('');
|
||
$$('[data-topic]').forEach(b=>b.onclick=async()=>{try{await api('/chat/topic',{method:'POST',body:JSON.stringify({topic:b.dataset.topic})});chatFollowing=true;chatUnread=0;pollChat();}catch(e){toast(e.message);}});
|
||
$('#chat-links').innerHTML=online?data.links.map(l=>`<div class="chat-link"><span>${esc(l.call)}</span><span class="${l.state==='Open'?'open':'closed'}">${esc(({open:'Attivo',idle:'In attesa',connecting:'Connessione…','connect failed':'Connessione fallita',closed:'Chiuso'})[l.state.toLowerCase()]||l.state)}</span></div>`).join('')||'<div class="chat-link">—</div>':'<div class="chat-link">Non connesso</div>';
|
||
const events=data.events.filter(e=>e.id>chatLastId),initial=chatLastId===0;
|
||
if(events.length){if(chatArea.querySelector('.chat-empty'))chatArea.replaceChildren();const fragment=document.createDocumentFragment();let added=0;
|
||
for(const event of events){chatLastId=Math.max(chatLastId,event.id);if(event.type==='system'&&/^[A-Z0-9]{3,6}(?:\s+[A-Z0-9]{3,6})*$/.test(event.text))continue;
|
||
const element=document.createElement('div');if(event.type==='message'&&!/\*\*\* (?:Joined|Left)/i.test(event.text)){element.className='chat-event '+(event.sender===station.call?'own':'')+(event.to?' private':'');element.innerHTML=`<div class="chat-avatar">${esc(event.sender?.slice(0,2)||'?')}</div><div class="chat-message-content"><div class="chat-message-meta"><strong>${esc(event.sender)}${event.to?` <span class="chat-private-label">→ ${esc(event.to)} · privato</span>`:''}</strong><time datetime="${esc(event.at)}" title="${esc(new Date(event.at).toLocaleString(BPQI18n.locale(),{}))}">${new Date(event.at).toLocaleTimeString(BPQI18n.locale(),{hour:'2-digit',minute:'2-digit'})}</time></div><p>${esc(event.text)}</p></div>`;added++;}else{element.className='chat-system';element.textContent=(event.sender?event.sender+' · ':'')+event.text;}fragment.append(element);}
|
||
chatArea.append(fragment);while(chatArea.children.length>300)chatArea.firstChild.remove();
|
||
if(initial||chatFollowing||events.some(e=>e.sender===station.call&&e.type==='message')){chatFollowing=true;if(page==='chat')chatToBottom();}else{chatUnread+=added;updateChatJump();}
|
||
}
|
||
}
|
||
|
||
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)}};
|
||
setInterval(()=>{if(csrf&&(page==='chat'||chatState==='online'||chatState==='connecting'))pollChat()},2000);
|
||
|
||
const presenceButton=document.createElement('button');presenceButton.className='secondary mobile-presence';presenceButton.textContent='Utenti';presenceButton.setAttribute('aria-expanded','false');presenceButton.onclick=()=>{const open=$('.chat-layout').classList.toggle('users-open');presenceButton.setAttribute('aria-expanded',String(open))};$('.chat-actions').prepend(presenceButton);
|
||
|
||
$('#chat-recipient').addEventListener('change',()=>{$('#chat-input').placeholder=$('#chat-recipient').value?'Messaggio privato a '+$('#chat-recipient').value+'…':'Scrivi alla stanza…';});
|
||
if(location.hash==='#chat')navigate('chat');
|
||
|
||
window.addEventListener('DOMContentLoaded',()=>{for(const target of ['#bbs .mail-list-heading','#winlink .mail-list-heading']){const heading=$(target);if(heading){const tag=document.createElement('small');tag.className='mail-timezone';tag.textContent='Timezone: '+mailTimezone();heading.append(tag);}}});
|
||
|
||
function restoreMailPage(){const target=location.hash.slice(1);if(['home','bbs','winlink','chat','network','monitor','journal','map'].includes(target)&&page!==target&&document.getElementById(target))navigate(target);}
|
||
window.addEventListener('DOMContentLoaded',restoreMailPage);window.addEventListener('hashchange',restoreMailPage);
|