// recentActivity/panel.js — Recent activity table logic
'use strict';
(function() {
var tbody = document.getElementById('ra-table');
var entries = {}; // id → {entry, row, timer}
var order = []; // ids, oldest first
var MAX_ROWS = 50; // lines shown: calls, or (compact) callers
var KEEP = 500; // calls kept here: all MCP sends (its activity_cache, at most 500)
// Compact: one line per caller (their callsign, without any suffix,
// in one mode, and for DMR one timeslot: the same callsign on the two
// slots is two people), their latest call; "×N" on it shows the rest.
// This browser's choice (off unless turned on), as the theme is.
var COMPACT_KEY = 'pistar-activity-compact';
var compact = false;
try { compact = localStorage.getItem(COMPACT_KEY) === '1'; } catch (e) {}
var expanded = {}; // caller key → their calls shown
var batching = false;
// --- Helpers ---
function formatDuration(seconds) {
if (!seconds || seconds <= 0) return '';
if (seconds < 60) return seconds.toFixed(1) + 's';
var m = Math.floor(seconds / 60);
var s = (seconds % 60).toFixed(0);
return m + ':' + (s.length < 2 ? '0' : '') + s;
}
function formatLoss(loss) {
if (!loss && loss !== 0) return '';
return loss.toFixed(1) + '%';
}
// RSSI (dBm) as MMDVM-Host reports it from the modem: only RF calls,
// and only when the modem sends it.
// S-meter reading on the VHF/UHF scale (IARU Region 1: S9 = -93 dBm,
// 6 dB an S unit): "S7" below S9 (to the nearest S unit), "S9+40"
// above (down to the 10 dB step, as a meter is marked)
var S9_DBM = -93, S_UNIT_DB = 6;
function sMeter(rssi) {
var dbm = Math.round(rssi);
if (dbm >= S9_DBM) {
var over = Math.floor((dbm - S9_DBM) / 10) * 10;
return over > 0 ? 'S9+' + over : 'S9';
}
var s = Math.round(9 - (S9_DBM - dbm) / S_UNIT_DB);
return 'S' + Math.max(0, s);
}
// The meter: a segment for each S unit to S9, then one for each 10 dB
// above. An MMDVM_HS board reports -47 dBm at most (its ADF7021's RSSI
// tops out there, S9+46), so its meter ends at +40, full there; a
// repeater modem (MMDVM) reads higher, to +60.
var modemClass = '';
function overSteps() {
return modemClass === 'mmdvm_hs' ? 4 : 6;
}
// meterHTML is the segments for a reading: lit to it (an S unit lit
// from half a unit below it, as the reading rounds), rising in height,
// green to S9 then the warning and danger colours
function meterHTML(dbm) {
var over = overSteps(), n = 9 + over, html = '';
for (var i = 0; i < n; i++) {
var lit, cls;
if (i < 9) {
lit = dbm >= S9_DBM - S_UNIT_DB * (8 - i) - S_UNIT_DB / 2;
cls = 'ra-seg-s';
} else {
var step = (i - 8) * 10;
lit = dbm >= S9_DBM + step;
cls = step >= 30 ? 'ra-seg-hot' : 'ra-seg-over';
}
var h = Math.round(35 + 65 * i / (n - 1));
html += '';
}
return html;
}
// setRSSI fills the RSSI cell: the S reading and a small meter, the dBm
// under them (as a talkgroup's name is under its number)
function setRSSI(cell, rssi) {
if (!rssi) {
cell.textContent = '';
cell.removeAttribute('title');
cell.removeAttribute('data-rssi');
return;
}
var dbm = Math.round(rssi);
var s = sMeter(rssi);
cell.setAttribute('data-rssi', rssi);
cell.innerHTML = '
' + escapeHtml(s) + '' +
'' + meterHTML(dbm) + '
' +
'' + escapeHtml(dbm + ' dBm') + '
';
cell.title = i18n('recentActivity.rssiTitle', '{dbm} dBm: {s} on the VHF/UHF scale (S9 = -93 dBm)')
.replace('{dbm}', dbm).replace('{s}', s);
}
// The RSSI column shows once any call has an RSSI: a modem that sends
// none never gets an empty column.
function showRSSI(entry) {
if (entry && entry.rssi) {
var t = document.getElementById('ra-table-full');
if (t) t.classList.add('ra-has-rssi');
}
}
function formatBER(ber) {
if (!ber && ber !== 0) return '';
return ber.toFixed(2) + '%';
}
// The station's time and 12/24-hour format (Radio Setup, Location)
function formatTime(ts) {
if (!ts) return '';
return PiStar.formatTime(ts);
}
// The time, and the day and date under it: a quiet hotspot's last
// calls may be days old
function setTime(cell, ts) {
cell.textContent = formatTime(ts);
var day = ts && window.PiStar && PiStar.formatDay ? PiStar.formatDay(ts) : '';
if (day) {
var div = document.createElement('div');
div.className = 'ra-tgname ra-day';
div.textContent = day;
cell.appendChild(div);
}
}
function modeClass(mode) {
if (!mode) return '';
return 'ra-mode-' + mode.toLowerCase().replace(/[^a-z0-9]/g, '');
}
function sourceLabel(source) {
if (!source) return '';
switch (source.toLowerCase()) {
case 'rf': return i18n('recentActivity.rf', 'RF');
case 'network': case 'net': return i18n('recentActivity.net', 'Net');
case 'local': return i18n('recentActivity.local', 'Local');
default: return source;
}
}
function modeLabel(mode, slot) {
if (!mode) return '';
if (mode === 'DMR' && slot) return 'DMR TS' + slot;
if (mode === 'CW') return i18n('recentActivity.cw', 'CW');
return mode;
}
function targetLabel(entry) {
// A page's target is its message (or, for an alert, its type)
if (entry.mode === 'POCSAG') return pageText(entry);
var t = entry.target || '';
if (entry.extra && entry.extra.dgId) {
t += ' DG-ID:' + entry.extra.dgId;
}
return t;
}
// POCSAG pages: the page text where a talkgroup would be; an alert
// is "Alert", or "Alert: text" for one carrying text.
function pageText(entry) {
if (entry.mode !== 'POCSAG' || !entry.extra) return '';
var msg = entry.extra.message || '';
if (entry.extra.functional === 'alert_1' || entry.extra.functional === 'alert_2') {
return i18n('recentActivity.pageAlert', 'Alert') + (msg ? ': ' + msg : '');
}
return msg;
}
function setTarget(cell, entry) {
// Non-breaking spaces, so a D-Star command such as " E"
// (echo) keeps its leading spaces instead of collapsing to "E".
// A page's message keeps its spaces, so it wraps.
var page = entry.mode === 'POCSAG';
cell.textContent = page ? targetLabel(entry) : targetLabel(entry).replace(/ /g, '\u00A0');
cell.classList.toggle('ra-page', page);
var to = flag(extra(entry, 'to'));
if (to) cell.insertAdjacentHTML('afterbegin', to + ' ');
// NXDN / P25 talkgroup: the reflector's name under the number
if (entry.extra && entry.extra.tgName) {
var name = document.createElement('div');
name.className = 'ra-tgname';
name.textContent = entry.extra.tgName;
cell.appendChild(name);
}
// The network or reflector the call went through
var via = extra(entry, 'via');
var bridge = extra(entry, 'bridge');
if (bridge) {
// A Pi-Star cross-mode bridge: it, then its far side
var far = [bridge + ' \u2192 ' + (extra(entry, 'farTarget') || extra(entry, 'farMode')), via].filter(Boolean).join(' \u00b7 ');
var bv = document.createElement('div');
bv.className = 'ra-tgname ra-via';
var bf = flag(extra(entry, 'to') || extra(entry, 'viaFlag'));
bv.innerHTML = escapeHtml(i18n('recentActivity.via', 'via {name}')).replace('{name}', (bf ? bf + ' ' : '') + escapeHtml(far));
cell.appendChild(bv);
} else if (via) {
var v = document.createElement('div');
v.className = 'ra-tgname ra-via';
var vf = flag(extra(entry, 'viaFlag'));
// A rewritten talkgroup: the one it is on that network
var netTarget = extra(entry, 'netTarget');
v.innerHTML = escapeHtml(i18n('recentActivity.via', 'via {name}')).replace('{name}', (vf ? vf + ' ' : '') + escapeHtml(via + (netTarget ? ' \u00b7 ' + netTarget : '')));
cell.appendChild(v);
}
}
// Flags (pistar.js): where the caller is, and where the call goes
function flag(code) {
return (code && window.PiStar && PiStar.flagHTML) ? PiStar.flagHTML(code) : '';
}
function extra(entry, k) {
return (entry.extra && entry.extra[k]) || '';
}
// The caller: flag, callsign and, for DMR, P25 and NXDN, the ID it
// was found from, in brackets; under them, as the On Air panel has it,
// their name and country
function setCallsign(cell, entry) {
var f = flag(extra(entry, 'from')), id = callerID(entry);
// The callsign opens the caller's look-up menu (QRZ.com, RadioID,
// aprs.fi): pistar.js
var label = escapeHtml(callsignLabel(entry));
// A pager has no callsign to look up
if (window.PiStar && PiStar.callButton && entry.mode !== 'POCSAG') label = PiStar.callButton(entry.callsign, extra(entry, 'srcId'), label);
cell.innerHTML = (f ? f + ' ' : '') + label +
(id ? ' (' + escapeHtml(id) + ')' : '');
var sub = whoLine(entry);
if (sub) {
var div = document.createElement('div');
div.className = 'ra-tgname ra-who';
div.textContent = sub;
cell.appendChild(div);
}
// The whole cell opens the menu, not only the callsign
cell.classList.toggle('call-menu-area', !!cell.querySelector('.call-menu-btn'));
}
// The caller's ID, unless it is the callsign already (an ID
// MMDVM-Host found no callsign for)
function callerID(entry) {
// A page: the pager's RIC, as "DAPNET (RIC 123456)"
if (entry.mode === 'POCSAG') return extra(entry, 'ric') ? 'RIC ' + extra(entry, 'ric') : '';
var id = extra(entry, 'srcId');
return id && String(id) !== String(entry.callsign || '') ? String(id) : '';
}
// Name · Country: a country is never split over two lines ("United
// States"); the line wraps between the two, if it must
function whoLine(entry) {
if (entry.mode === 'POCSAG') return pageType(entry);
var from = extra(entry, 'from');
var country = from && window.PiStar ? PiStar.countryName(from).replace(/ /g, '\u00a0') : '';
return [extra(entry, 'name'), country].filter(Boolean).join(' \u00b7 ');
}
// A page's POCSAG type, under its RIC
function pageType(entry) {
switch (extra(entry, 'functional')) {
case 'alphanumeric': return i18n('recentActivity.pageAlphanumeric', 'Alphanumeric');
case 'numeric': return i18n('recentActivity.pageNumeric', 'Numeric');
case 'alert_1': case 'alert_2': return i18n('recentActivity.pageAlert', 'Alert');
default: return '';
}
}
// Loss, and for a network call whose end never came (lost: the
// network stopped sending it), a short note under it
function setLoss(cell, entry) {
cell.textContent = formatLoss(entry.loss);
if (entry.status === 'lost' && entry.source === 'network') {
var div = document.createElement('div');
div.className = 'ra-tgname ra-eot';
div.textContent = i18n('recentActivity.noEot', 'No EoT');
div.title = i18n('recentActivity.noEotTitle', 'End of transmission missed: the call\'s end never arrived from the network, so it was cut short');
cell.appendChild(div);
}
}
function callsignLabel(entry) {
var cs = entry.callsign || '';
if (entry.callsignExt) cs += ' ' + entry.callsignExt;
return cs;
}
// --- Row management ---
function createRow(entry) {
var tr = document.createElement('tr');
tr.id = 'ra-' + entry.id;
if (entry.status === 'in_progress') tr.classList.add('ra-active');
if (entry.status === 'lost') tr.classList.add('ra-lost');
var mc = modeClass(entry.mode);
tr.innerHTML =
' | ' +
'' + escapeHtml(modeLabel(entry.mode, entry.slot)) + ' | ' +
' | ' +
'' + escapeHtml(sourceLabel(entry.source)) + ' | ' +
'' + formatDuration(entry.duration) + ' | ' +
// On a phone the figures are a line of their own, so loss
// and BER carry their names (data-label)
' | ' +
'' + formatBER(entry.ber) + ' | ' +
'' +
' | ';
showRSSI(entry);
setCallsign(tr.cells[0], entry);
setTarget(tr.cells[2], entry);
setLoss(tr.cells[5], entry);
setRSSI(tr.cells[7], entry.rssi);
setTime(tr.cells[8], entry.timestamp);
return tr;
}
function updateRow(tracked, entry) {
tracked.entry = entry;
var tr = tracked.row;
tr.className = '';
if (entry.status === 'in_progress') tr.classList.add('ra-active');
if (entry.status === 'lost') tr.classList.add('ra-lost');
var cells = tr.cells;
setCallsign(cells[0], entry);
cells[1].className = modeClass(entry.mode);
cells[1].textContent = modeLabel(entry.mode, entry.slot);
setTarget(cells[2], entry);
cells[3].textContent = sourceLabel(entry.source);
cells[4].textContent = formatDuration(entry.duration);
setLoss(cells[5], entry);
cells[6].textContent = formatBER(entry.ber);
setRSSI(cells[7], entry.rssi);
setTime(cells[8], entry.timestamp);
showRSSI(entry);
// Stop live counter if call ended
if (entry.status !== 'in_progress' && tracked.timer) {
clearInterval(tracked.timer);
tracked.timer = null;
}
}
function escapeHtml(str) {
if (!str) return '';
var div = document.createElement('div');
div.appendChild(document.createTextNode(str));
return div.innerHTML;
}
function addEntry(entry) {
var tr = createRow(entry);
var tracked = { entry: entry, row: tr, timer: null };
entries[entry.id] = tracked;
order.push(entry.id);
// Start live counter for in_progress entries
if (entry.status === 'in_progress') {
startLiveCounter(tracked);
}
trim();
if (!batching) render();
}
// The oldest calls go once more are kept than MCP sends
function trim() {
while (order.length > KEEP) {
var id = order.shift();
if (entries[id] && entries[id].timer) clearInterval(entries[id].timer);
delete entries[id];
}
}
// --- Compact ---
// The caller a call is from: callsign without its suffix (/P, -1, a
// D-Star extension), else their ID; in a mode, for DMR on a timeslot.
// A POCSAG page: its pager, the RIC, from DAPNET or sent locally (so
// Skyper's frequent pages make a line each RIC).
function callerKey(entry) {
if (entry.mode === 'POCSAG') {
var ric = extra(entry, 'ric');
return ric ? 'ric:' + ric + '|' + (entry.callsign || '') : 'page:' + entry.id;
}
var base = String(entry.callsign || '').toUpperCase().trim().split(/[\/\- ]/)[0] || extra(entry, 'srcId');
if (!base) return 'call:' + entry.id;
return base + '|' + (entry.mode || '') + (entry.mode === 'DMR' ? '|' + (entry.slot || '') : '');
}
// The "×N" button on a caller's line (n: their calls; under 2, none)
function setCount(tracked, n, key) {
var cell = tracked.row.cells[0];
var btn = cell.querySelector('.ra-more');
if (n < 2) {
if (btn) btn.remove();
return;
}
if (!btn) {
btn = document.createElement('button');
btn.type = 'button';
btn.className = 'ra-more';
cell.insertBefore(btn, cell.querySelector('.ra-who'));
}
var open = !!expanded[key];
var call = callsignLabel(tracked.entry) || extra(tracked.entry, 'srcId');
btn.textContent = '\u00d7' + n;
btn.setAttribute('data-key', key);
btn.setAttribute('aria-expanded', open ? 'true' : 'false');
var label = open
? i18n('recentActivity.groupHide', 'Hide the earlier calls from {call}')
: i18n('recentActivity.groupShow', 'Show all calls from {call} ({n})');
label = label.replace('{call}', call).replace('{n}', n);
btn.setAttribute('aria-label', label);
btn.title = label;
}
// render puts the lines in the table: the newest calls; or (compact)
// each caller's latest, newest first, with their earlier calls under
// it when opened. Rows are moved, not made again (live counters run on).
function render() {
var ids = order.slice().reverse();
var rows = [];
if (!compact) {
ids.slice(0, MAX_ROWS).forEach(function(id) {
var t = entries[id];
setCount(t, 0);
t.row.classList.remove('ra-sub');
rows.push(t.row);
});
} else {
var keys = [], members = {};
ids.forEach(function(id) {
var k = callerKey(entries[id].entry);
if (!members[k]) { members[k] = []; keys.push(k); }
members[k].push(id);
});
keys.slice(0, MAX_ROWS).forEach(function(k) {
var head = entries[members[k][0]];
head.row.classList.remove('ra-sub');
setCount(head, members[k].length, k);
rows.push(head.row);
members[k].slice(1).forEach(function(id) {
var t = entries[id];
setCount(t, 0);
t.row.classList.add('ra-sub');
if (expanded[k]) rows.push(t.row);
});
});
for (var k in expanded) {
if (!members[k]) delete expanded[k];
}
}
var kids = tbody.children, same = kids.length === rows.length;
for (var i = 0; same && i < rows.length; i++) same = kids[i] === rows[i];
if (same) return;
var frag = document.createDocumentFragment();
rows.forEach(function(r) { frag.appendChild(r); });
tbody.textContent = '';
tbody.appendChild(frag);
}
// The switch, and the "×N" buttons (not the caller's look-up menu,
// whose cell they are in)
var compactSwitch = document.getElementById('ra-compact');
if (compactSwitch) {
compactSwitch.checked = compact;
compactSwitch.addEventListener('change', function() {
compact = compactSwitch.checked;
try { localStorage.setItem(COMPACT_KEY, compact ? '1' : '0'); } catch (e) {}
render();
});
}
tbody.addEventListener('click', function(e) {
var btn = e.target.closest && e.target.closest('.ra-more');
if (!btn) return;
e.preventDefault();
e.stopPropagation();
var k = btn.getAttribute('data-key');
if (expanded[k]) delete expanded[k]; else expanded[k] = true;
render();
var again = tbody.querySelector('.ra-more[data-key="' + (window.CSS && CSS.escape ? CSS.escape(k) : k) + '"]');
if (again) again.focus();
});
// --- Live duration counter ---
function startLiveCounter(tracked) {
var startTime = new Date(tracked.entry.timestamp).getTime();
tracked.timer = setInterval(function() {
if (tracked.entry.status !== 'in_progress') {
clearInterval(tracked.timer);
tracked.timer = null;
return;
}
var elapsed = (Date.now() - startTime) / 1000;
tracked.row.cells[4].textContent = formatDuration(elapsed);
}, 100);
}
// --- Batch load (on connect) ---
function loadBatch(batchEntries) {
// Clear existing
tbody.innerHTML = '';
for (var id in entries) {
if (entries[id].timer) clearInterval(entries[id].timer);
}
entries = {};
order = [];
// Entries arrive oldest-first, as order keeps them
batching = true;
for (var i = 0; i < batchEntries.length; i++) {
addEntry(batchEntries[i]);
}
batching = false;
render();
}
// --- Screen readers ---
// A new call, said once: who (and where from), the mode, where to,
// via what, and from RF or the network. The table changes all the
// time (the live duration), so it is not read as it changes.
var announcer = document.getElementById('ra-announce');
function announce(entry) {
if (!announcer || !entry || !entry.callsign) return;
var from = extra(entry, 'from');
var via = extra(entry, 'via');
var parts = [
callsignLabel(entry),
from && window.PiStar ? PiStar.countryName(from) : '',
modeLabel(entry.mode, entry.slot),
extra(entry, 'toCall') || targetLabel(entry),
via ? i18n('recentActivity.via', 'via {name}').replace('{name}', via + (extra(entry, 'netTarget') ? ' ' + extra(entry, 'netTarget') : '')) : '',
sourceLabel(entry.source)
].filter(function(s) { return s && String(s).trim(); });
announcer.textContent = '';
setTimeout(function() { announcer.textContent = parts.join(', '); }, 50);
}
// --- Event listeners ---
// The station's clock format arrived or changed: redraw the times.
document.addEventListener('pistar:clockformat', function() {
Object.keys(entries).forEach(function(id) {
var t = entries[id];
if (t && t.row && t.row.cells[8]) setTime(t.row.cells[8], t.entry.timestamp);
});
});
document.addEventListener('pistar:message', function(e) {
var msg = e.detail;
// The modem's class sets the meter's scale: redraw the meters
if (msg.type === 'modem_config' && msg.config) {
var mc = msg.config.modemClass || '';
if (mc !== modemClass) {
modemClass = mc;
document.querySelectorAll('#ra-table-full td.ra-rssi[data-rssi]').forEach(function(td) {
setRSSI(td, parseFloat(td.getAttribute('data-rssi')));
});
}
return;
}
// Handle activity_batch (sent on WebSocket connect)
if (msg.type === 'activity_batch') {
loadBatch(msg.entries || []);
return;
}
// Handle individual activity updates
if (msg.type !== 'activity') return;
var entry = msg.entry;
if (!entry || !entry.id) return;
if (msg.action === 'new') {
announce(entry);
// Remove existing row with same ID if present (shouldn't happen, but safe)
if (entries[entry.id]) {
updateRow(entries[entry.id], entry);
render();
} else {
addEntry(entry);
}
} else if (msg.action === 'update') {
if (entries[entry.id]) {
updateRow(entries[entry.id], entry);
render();
}
}
});
})();