fix(modes): deep-linked mode scripts fail when body not yet parsed

ensureModeScript() used document.body.appendChild() to load lazy mode
scripts, but the preload for ?mode= query params runs in <head> before
<body> exists, causing all deep-linked modes to silently fail.

Also fix cross-mode handoffs (BT→BT Locate, WiFi→WiFi Locate,
Spy Stations→Waterfall) that assumed target module was already loaded.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Smittix
2026-03-12 20:49:08 +00:00
parent 7c425dbd99
commit ba631811a6
87 changed files with 9128 additions and 8368 deletions
+30 -14
View File
@@ -895,6 +895,7 @@ const BluetoothMode = (function() {
const isAgentMode = typeof currentAgent !== 'undefined' && currentAgent !== 'local';
if (startBtn) startBtn.classList.add('btn-loading');
try {
let response;
if (isAgentMode) {
@@ -943,6 +944,8 @@ const BluetoothMode = (function() {
reportActionableError('Start Bluetooth Scan', err, {
onRetry: () => startScan()
});
} finally {
if (startBtn) startBtn.classList.remove('btn-loading');
}
}
@@ -1738,21 +1741,34 @@ const BluetoothMode = (function() {
}
function doLocateHandoff(device) {
console.log('[BT] doLocateHandoff, BtLocate defined:', typeof BtLocate !== 'undefined');
const payload = {
device_id: device.device_id,
device_key: device.device_key || null,
mac_address: device.address,
address_type: device.address_type || null,
irk_hex: device.irk_hex || null,
known_name: device.name || null,
known_manufacturer: device.manufacturer_name || null,
last_known_rssi: device.rssi_current,
tx_power: device.tx_power || null,
appearance_name: device.appearance_name || null,
fingerprint_id: device.fingerprint_id || device.fingerprint?.id || null,
mac_cluster_count: device.mac_cluster_count || 0
};
// If BtLocate is already loaded, hand off directly
if (typeof BtLocate !== 'undefined') {
BtLocate.handoff({
device_id: device.device_id,
device_key: device.device_key || null,
mac_address: device.address,
address_type: device.address_type || null,
irk_hex: device.irk_hex || null,
known_name: device.name || null,
known_manufacturer: device.manufacturer_name || null,
last_known_rssi: device.rssi_current,
tx_power: device.tx_power || null,
appearance_name: device.appearance_name || null,
fingerprint_id: device.fingerprint_id || device.fingerprint?.id || null,
mac_cluster_count: device.mac_cluster_count || 0
BtLocate.handoff(payload);
return;
}
// Switch to bt_locate mode first — this loads the script, styles,
// and initializes the module. Then hand off the device data.
if (typeof switchMode === 'function') {
switchMode('bt_locate').then(function() {
if (typeof BtLocate !== 'undefined') {
BtLocate.handoff(payload);
}
});
}
}
+20 -12
View File
@@ -110,19 +110,27 @@ const Meshtastic = (function() {
meshMap = L.map('meshMap').setView([defaultLat, defaultLon], 4);
window.meshMap = meshMap;
// Use settings manager for tile layer (allows runtime changes)
// Add fallback tiles immediately so the map is visible instantly
const fallbackTiles = L.tileLayer('https://cartodb-basemaps-{s}.global.ssl.fastly.net/dark_all/{z}/{x}/{y}.png', {
attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OSM</a> &copy; <a href="https://carto.com/">CARTO</a>',
maxZoom: 19,
subdomains: 'abcd',
className: 'tile-layer-cyan'
}).addTo(meshMap);
// Upgrade tiles in background via Settings (with timeout fallback)
if (typeof Settings !== 'undefined') {
// Wait for settings to load from server before applying tiles
await Settings.init();
Settings.createTileLayer().addTo(meshMap);
Settings.registerMap(meshMap);
} else {
L.tileLayer('https://cartodb-basemaps-{s}.global.ssl.fastly.net/dark_all/{z}/{x}/{y}.png', {
attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OSM</a> &copy; <a href="https://carto.com/">CARTO</a>',
maxZoom: 19,
subdomains: 'abcd',
className: 'tile-layer-cyan'
}).addTo(meshMap);
try {
await Promise.race([
Settings.init(),
new Promise((_, reject) => setTimeout(() => reject(new Error('Settings timeout')), 5000))
]);
meshMap.removeLayer(fallbackTiles);
Settings.createTileLayer().addTo(meshMap);
Settings.registerMap(meshMap);
} catch (e) {
console.warn('Meshtastic: Settings init failed/timed out, using fallback tiles:', e);
}
}
// Handle resize
+10 -9
View File
@@ -280,18 +280,19 @@ const SpyStations = (function() {
showNotification('Tuning to ' + stationName, formatFrequency(freqKhz) + ' (' + tuneMode.toUpperCase() + ')');
}
// Switch to spectrum waterfall mode and tune after mode init.
if (typeof switchMode === 'function') {
switchMode('waterfall');
} else if (typeof selectMode === 'function') {
selectMode('waterfall');
}
setTimeout(() => {
// Switch to spectrum waterfall mode and tune after init completes.
const doTune = () => {
if (typeof Waterfall !== 'undefined' && typeof Waterfall.quickTune === 'function') {
Waterfall.quickTune(freqMhz, tuneMode);
}
}, 220);
};
if (typeof switchMode === 'function') {
switchMode('waterfall').then(doTune);
} else if (typeof selectMode === 'function') {
selectMode('waterfall');
setTimeout(doTune, 300);
}
}
/**
+18 -11
View File
@@ -215,18 +215,25 @@ const SSTV = (function() {
});
window.issMap = issMap;
// Add tile layer using settings manager if available
// Add fallback tiles immediately so the map is visible instantly
const fallbackTiles = L.tileLayer('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png', {
maxZoom: 19,
className: 'tile-layer-cyan'
}).addTo(issMap);
// Upgrade tiles in background via Settings (with timeout fallback)
if (typeof Settings !== 'undefined') {
// Wait for settings to load from server before applying tiles
await Settings.init();
Settings.createTileLayer().addTo(issMap);
Settings.registerMap(issMap);
} else {
// Fallback to dark theme tiles
L.tileLayer('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png', {
maxZoom: 19,
className: 'tile-layer-cyan'
}).addTo(issMap);
try {
await Promise.race([
Settings.init(),
new Promise((_, reject) => setTimeout(() => reject(new Error('Settings timeout')), 5000))
]);
issMap.removeLayer(fallbackTiles);
Settings.createTileLayer().addTo(issMap);
Settings.registerMap(issMap);
} catch (e) {
console.warn('SSTV: Settings init failed/timed out, using fallback tiles:', e);
}
}
// Create ISS icon
+41 -11
View File
@@ -252,6 +252,8 @@ const WeatherSat = (function() {
addConsoleEntry('Starting capture...', 'info');
updateStatusUI('connecting', 'Starting...');
const startBtn = document.getElementById('weatherSatStartBtn');
if (startBtn) startBtn.classList.add('btn-loading');
try {
const config = {
satellite,
@@ -295,6 +297,8 @@ const WeatherSat = (function() {
onRetry: () => start()
});
updateStatusUI('idle', 'Error');
} finally {
if (startBtn) startBtn.classList.remove('btn-loading');
}
}
@@ -445,6 +449,8 @@ const WeatherSat = (function() {
};
eventSource.onerror = () => {
// Close the failed connection first to avoid leaking it
stopStream();
setTimeout(() => {
if (isRunning || schedulerEnabled) startStream();
}, 3000);
@@ -887,18 +893,28 @@ const WeatherSat = (function() {
preferCanvas: true,
});
// Add fallback tiles immediately so the map is visible instantly
const fallbackTiles = L.tileLayer('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png', {
subdomains: 'abcd',
maxZoom: 18,
noWrap: false,
crossOrigin: true,
className: 'tile-layer-cyan',
}).addTo(groundMap);
// Upgrade tiles in background via Settings (with timeout fallback)
if (typeof Settings !== 'undefined' && Settings.createTileLayer) {
await Settings.init();
Settings.createTileLayer().addTo(groundMap);
Settings.registerMap(groundMap);
} else {
L.tileLayer('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png', {
subdomains: 'abcd',
maxZoom: 18,
noWrap: false,
crossOrigin: true,
className: 'tile-layer-cyan',
}).addTo(groundMap);
try {
await Promise.race([
Settings.init(),
new Promise((_, reject) => setTimeout(() => reject(new Error('Settings timeout')), 5000))
]);
groundMap.removeLayer(fallbackTiles);
Settings.createTileLayer().addTo(groundMap);
Settings.registerMap(groundMap);
} catch (e) {
console.warn('WeatherSat: Settings init failed/timed out, using fallback tiles:', e);
}
}
groundGridLayer = L.layerGroup().addTo(groundMap);
@@ -1874,10 +1890,24 @@ const WeatherSat = (function() {
}
}
/**
* Unconditionally tear down the SSE stream on mode switch so we don't
* leak browser connections. The server-side capture/scheduler keeps
* running independently — the stream will reconnect on next init().
*/
function destroy() {
if (countdownInterval) {
clearInterval(countdownInterval);
countdownInterval = null;
}
stopStream();
}
// Public API
return {
init,
suspend,
destroy,
start,
stop,
startPass,
+20 -10
View File
@@ -314,17 +314,27 @@ async function initWebsdrLeaflet(mapEl) {
maxBoundsViscosity: 1.0,
});
// Add fallback tiles immediately so the map is visible instantly
const fallbackTiles = L.tileLayer('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png', {
attribution: '&copy; OpenStreetMap contributors &copy; CARTO',
subdomains: 'abcd',
maxZoom: 19,
className: 'tile-layer-cyan',
}).addTo(websdrMap);
// Upgrade tiles in background via Settings (with timeout fallback)
if (typeof Settings !== 'undefined' && Settings.createTileLayer) {
await Settings.init();
Settings.createTileLayer().addTo(websdrMap);
Settings.registerMap(websdrMap);
} else {
L.tileLayer('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png', {
attribution: '&copy; OpenStreetMap contributors &copy; CARTO',
subdomains: 'abcd',
maxZoom: 19,
className: 'tile-layer-cyan',
}).addTo(websdrMap);
try {
await Promise.race([
Settings.init(),
new Promise((_, reject) => setTimeout(() => reject(new Error('Settings timeout')), 5000))
]);
websdrMap.removeLayer(fallbackTiles);
Settings.createTileLayer().addTo(websdrMap);
Settings.registerMap(websdrMap);
} catch (e) {
console.warn('WebSDR: Settings init failed/timed out, using fallback tiles:', e);
}
}
mapEl.style.background = '#1a1d29';
+33 -1
View File
@@ -247,6 +247,8 @@ const WiFiMode = (function() {
// ==========================================================================
async function checkCapabilities() {
const capBtn = document.getElementById('wifiQuickScanBtn');
if (capBtn) capBtn.classList.add('btn-loading');
try {
const isAgentMode = typeof currentAgent !== 'undefined' && currentAgent !== 'local';
let response;
@@ -291,6 +293,8 @@ const WiFiMode = (function() {
} catch (error) {
console.error('[WiFiMode] Capability check failed:', error);
showCapabilityError('Failed to check WiFi capabilities');
} finally {
if (capBtn) capBtn.classList.remove('btn-loading');
}
}
@@ -386,18 +390,40 @@ const WiFiMode = (function() {
if (elements.scanModeDeep) {
elements.scanModeDeep.addEventListener('click', () => setScanMode('deep'));
}
// Arrow key navigation between tabs
const tabContainer = document.querySelector('.wifi-scan-mode-tabs');
if (tabContainer) {
tabContainer.addEventListener('keydown', (e) => {
const tabs = Array.from(tabContainer.querySelectorAll('[role="tab"]'));
const idx = tabs.indexOf(document.activeElement);
if (idx === -1) return;
if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {
e.preventDefault();
const next = tabs[(idx + 1) % tabs.length];
next.focus();
next.click();
} else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') {
e.preventDefault();
const prev = tabs[(idx - 1 + tabs.length) % tabs.length];
prev.focus();
prev.click();
}
});
}
listenersBound.scanTabs = true;
}
function setScanMode(mode) {
scanMode = mode;
// Update tab UI
// Update tab UI and ARIA states
if (elements.scanModeQuick) {
elements.scanModeQuick.classList.toggle('active', mode === 'quick');
elements.scanModeQuick.setAttribute('aria-selected', mode === 'quick' ? 'true' : 'false');
}
if (elements.scanModeDeep) {
elements.scanModeDeep.classList.toggle('active', mode === 'deep');
elements.scanModeDeep.setAttribute('aria-selected', mode === 'deep' ? 'true' : 'false');
}
console.log('[WiFiMode] Scan mode set to:', mode);
@@ -416,6 +442,7 @@ const WiFiMode = (function() {
}
console.log('[WiFiMode] Starting quick scan...');
if (elements.quickScanBtn) elements.quickScanBtn.classList.add('btn-loading');
setScanning(true, 'quick');
try {
@@ -496,6 +523,8 @@ const WiFiMode = (function() {
console.error('[WiFiMode] Quick scan error:', error);
showError(error.message + '. Try using Deep Scan instead.');
setScanning(false);
} finally {
if (elements.quickScanBtn) elements.quickScanBtn.classList.remove('btn-loading');
}
}
@@ -508,6 +537,7 @@ const WiFiMode = (function() {
}
console.log('[WiFiMode] Starting deep scan...');
if (elements.deepScanBtn) elements.deepScanBtn.classList.add('btn-loading');
setScanning(true, 'deep');
try {
@@ -569,6 +599,8 @@ const WiFiMode = (function() {
console.error('[WiFiMode] Deep scan error:', error);
showError(error.message);
setScanning(false);
} finally {
if (elements.deepScanBtn) elements.deepScanBtn.classList.remove('btn-loading');
}
}