mirror of
https://github.com/legop3/MultiRoombaRover.git
synced 2026-11-16 11:42:17 -05:00
Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
79d36cae93 | ||
|
|
1dcd7e5d7d | ||
|
|
b4bc99ab27 | ||
|
|
c94e1a0508 | ||
|
|
abcb0871b2 | ||
|
|
1ffe680895 | ||
|
|
ed26b90384 |
Binary file not shown.
@@ -4,7 +4,7 @@
|
||||
const path = require('path');
|
||||
const { subscribe } = require('../eventBus');
|
||||
|
||||
const DONE_CHARGING_SOUND_PATH = path.resolve(__dirname, '..', '..', '..', 'public', 'donecharging.wav');
|
||||
const DONE_CHARGING_SOUND_PATH = path.resolve(__dirname, '..', '..', '..', 'assets', 'donecharging.wav');
|
||||
|
||||
function registerChargeCompleteSound(deps) {
|
||||
const {
|
||||
@@ -12,22 +12,18 @@ function registerChargeCompleteSound(deps) {
|
||||
playServerAudioFile,
|
||||
} = deps;
|
||||
|
||||
subscribe('battery.unlocked', (event = {}) => {
|
||||
subscribe('battery.chargeComplete', (event = {}) => {
|
||||
const roverId = String(event?.payload?.roverId || '').trim();
|
||||
if (!roverId) return;
|
||||
|
||||
try {
|
||||
// battery.unlocked is the existing server-side definition of "done
|
||||
// charging" because it only fires after the battery manager has waited
|
||||
// through its full charge-release policy. Playing from this event avoids
|
||||
// duplicating charging thresholds or raw sensor-state guesses here.
|
||||
playServerAudioFile(roverId, DONE_CHARGING_SOUND_PATH, {
|
||||
source: 'charge-complete',
|
||||
});
|
||||
logger.info('Played charging complete sound', { roverId, filePath: DONE_CHARGING_SOUND_PATH });
|
||||
logger.info('Started charging complete sound', { roverId, filePath: DONE_CHARGING_SOUND_PATH });
|
||||
} catch (err) {
|
||||
// A missing/offline rover or unavailable ffmpeg should not affect the
|
||||
// battery manager's unlock decision. The sound is an announcement layered
|
||||
// battery manager's processing. The sound is an announcement layered
|
||||
// on top of the state transition, so failures are logged and contained.
|
||||
logger.warn('Failed to play charging complete sound', {
|
||||
roverId,
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
const logger = require('../../globals/logger').child('batteryManager');
|
||||
const { publishEvent } = require('../eventBus');
|
||||
const { managerEvents, lockRover, rovers } = require('../roverManager');
|
||||
const { issueCommand } = require('../commandService');
|
||||
|
||||
const STATES = {
|
||||
NORMAL: 'normal',
|
||||
@@ -29,6 +30,7 @@ function getState(roverId) {
|
||||
dockedCharging: false,
|
||||
charging: false,
|
||||
batteryLocked: false,
|
||||
completionAnnounced: false,
|
||||
waitingSince: null,
|
||||
});
|
||||
}
|
||||
@@ -61,6 +63,11 @@ function handleSensorEvent({ roverId, sensors, batteryState }) {
|
||||
}
|
||||
if (!state.urgent && batteryState?.urgentActive) {
|
||||
state.urgent = true;
|
||||
try {
|
||||
issueCommand(roverId, { type: 'song', song: { notes: [{ note: 72, duration: 8 }, { note: 0, duration: 8 }, { note: 72, duration: 16 }] } });
|
||||
} catch (err) {
|
||||
logger.warn('Failed to play urgent battery warning', { roverId, error: err.message });
|
||||
}
|
||||
publishEvent({
|
||||
source: 'batteryManager',
|
||||
type: 'battery.urgent',
|
||||
@@ -137,6 +144,18 @@ function handleSensorEvent({ roverId, sensors, batteryState }) {
|
||||
(batteryState?.charge != null && fullThreshold != null && batteryState.charge >= fullThreshold) ||
|
||||
(batteryState?.percent != null && batteryState.percent >= 0.99);
|
||||
|
||||
// Announce once per dock visit, independently of the charging lock. Keep the
|
||||
// latch at 100% so small charge fluctuations cannot repeat the sound.
|
||||
if (!onDock) state.completionAnnounced = false;
|
||||
if (onDock && batteryState?.percentDisplay >= 100 && !state.completionAnnounced) {
|
||||
state.completionAnnounced = true;
|
||||
publishEvent({
|
||||
source: 'batteryManager',
|
||||
type: 'battery.chargeComplete',
|
||||
payload: { roverId, batteryState },
|
||||
});
|
||||
}
|
||||
|
||||
const needsCharge = state.warned;
|
||||
|
||||
if (dockedCharging && lockable && needsCharge && !state.batteryLocked && !isFull && !waitingLongEnough) {
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// Purpose: Centralizes rover battery/status snapshot formatting and embed rendering for Discord surfaces.
|
||||
// Scope: Shared presentation logic for status commands and admin alert battery event posts.
|
||||
const { EmbedBuilder } = require('discord.js');
|
||||
const { getMode } = require('../modeManager');
|
||||
|
||||
function formatVoltage(voltageMv) {
|
||||
if (voltageMv == null) return 'n/a';
|
||||
@@ -69,6 +70,7 @@ function buildRoverStatusSnapshot(record) {
|
||||
|
||||
function buildBatteryStatusEmbed({ color = 0x2196f3, records = [] }) {
|
||||
const embed = new EmbedBuilder().setTitle('Rover Battery Status').setColor(color).setTimestamp(new Date());
|
||||
embed.addFields({ name: 'Server mode', value: getMode(), inline: true });
|
||||
const snapshots = records.map((entry) => buildRoverStatusSnapshot(entry)).filter(Boolean);
|
||||
if (!snapshots.length) {
|
||||
embed.setDescription('No rovers online.');
|
||||
|
||||
@@ -400,6 +400,7 @@ function createOvercurrentProtectionService(options = {}) {
|
||||
type: 'drive',
|
||||
driveDirect: { left: 0, right: 0 },
|
||||
});
|
||||
issueAdjustedCommand(roverId, { type: 'song', song: { notes: [{ note: 76, duration: 8 }, { note: 72, duration: 8 }, { note: 67, duration: 16 }] } });
|
||||
logger.warn('Stopped rover after persistent wheel overcurrent', {
|
||||
roverId,
|
||||
motor: stalledWheel,
|
||||
|
||||
@@ -2,20 +2,19 @@
|
||||
// Purpose: Publishes sustained 600-series Roomba trouble as roster and alert state.
|
||||
// Scope: Integrates the pure monitor with roverManager, browser alerts, and the event bus.
|
||||
const roverManager = require('../roverManager');
|
||||
const { issueCommand } = require('../commandService');
|
||||
const { sendAlert } = require('../alertService');
|
||||
const { publishEvent } = require('../eventBus');
|
||||
const { REASON_LABELS, createRoverHelpMonitor } = require('./monitor');
|
||||
const { createHelpHornNotifier } = require('./hornNotifier');
|
||||
const logger = require('../../globals/logger').child('roverHelpService');
|
||||
|
||||
const HELP_ALERT_COLOR = '#ef4444';
|
||||
|
||||
const hornNotifier = createHelpHornNotifier({
|
||||
getRover: (roverId) => roverManager.rovers.get(String(roverId)),
|
||||
// commandService imports roverManager, so resolving it only when a chirp is
|
||||
// actually issued avoids turning server startup order into a circular module
|
||||
// dependency while retaining the established command transport.
|
||||
issueCommand: (roverId, payload) => require('../commandService').issueCommand(roverId, payload),
|
||||
logger: require('../../globals/logger').child('roverHelpService'),
|
||||
issueCommand,
|
||||
logger,
|
||||
});
|
||||
|
||||
const monitor = createRoverHelpMonitor({
|
||||
@@ -42,6 +41,11 @@ const monitor = createRoverHelpMonitor({
|
||||
});
|
||||
} else if (wasNeedingHelp && !needsHelp) {
|
||||
hornNotifier.stop(roverId);
|
||||
try {
|
||||
issueCommand(roverId, { type: 'song', song: { notes: [{ note: 72, duration: 8 }, { note: 79, duration: 16 }] } });
|
||||
} catch (err) {
|
||||
logger.warn('Failed to play HELP-cleared confirmation', { roverId, error: err.message });
|
||||
}
|
||||
publishEvent({
|
||||
source: 'roverHelpService',
|
||||
type: 'rover.helpCleared',
|
||||
|
||||
@@ -187,6 +187,7 @@ function buildSession(socket) {
|
||||
socketId: socket?.id || null,
|
||||
role: getRole(socket),
|
||||
operatingMode: getOperatingMode(socket),
|
||||
canLeaveRover: roverManager.canLeaveCurrentRover(socket).ok,
|
||||
mode: getMode(),
|
||||
isLocalNetwork: isLocalNetwork(getSocketIp(socket)),
|
||||
bandwidthSavings: buildBandwidthSavingsSessionState(socket, controllableUserCount),
|
||||
@@ -263,10 +264,14 @@ function buildSession(socket) {
|
||||
};
|
||||
}
|
||||
|
||||
// Cache only the published decision so sensor frames send updates on transitions.
|
||||
const leavePermissionBySocket = new WeakMap();
|
||||
|
||||
function syncSocket(socket) {
|
||||
if (!socket) return;
|
||||
const payload = buildSession(socket);
|
||||
logger.info('Syncing session', socket.id, payload.role, payload.assignment);
|
||||
leavePermissionBySocket.set(socket, payload.canLeaveRover);
|
||||
socket.emit('session:sync', payload);
|
||||
}
|
||||
|
||||
@@ -287,6 +292,15 @@ io.on('connection', (socket) => {
|
||||
syncSocket(socket);
|
||||
});
|
||||
|
||||
managerEvents.on('sensor', ({ roverId }) => {
|
||||
io.sockets.sockets.forEach((socket) => {
|
||||
const decision = roverManager.canLeaveCurrentRover(socket);
|
||||
if (decision.currentId !== roverId) return;
|
||||
if (leavePermissionBySocket.get(socket) === decision.ok) return;
|
||||
syncSocket(socket);
|
||||
});
|
||||
});
|
||||
|
||||
operatingModeEvents.on('change', () => syncAll());
|
||||
|
||||
roleEvents.on('change', ({ socket }) => {
|
||||
@@ -365,13 +379,13 @@ privateRoverAccessRequestEvents.on('change', (event = {}) => {
|
||||
syncAll();
|
||||
});
|
||||
|
||||
managerEvents.on('driver', ({ socketId }) => {
|
||||
if (!socketId) return;
|
||||
const socket = io.sockets.sockets.get(socketId);
|
||||
if (socket) {
|
||||
logger.info('Driver assignment change; syncing session', socketId);
|
||||
syncSocket(socket);
|
||||
}
|
||||
// Update the changed driver and anyone whose departure permission depends on them.
|
||||
managerEvents.on('driver', ({ socketId, roverId }) => {
|
||||
io.sockets.sockets.forEach((socket) => {
|
||||
if (socket.id === socketId || roverManager.isDriver(roverId, socket)) {
|
||||
syncSocket(socket);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
turnEvents.on('activeDriver', () => {
|
||||
|
||||
@@ -59,20 +59,6 @@ function BarcodeScanToast({ payload }) {
|
||||
);
|
||||
}
|
||||
|
||||
function UndockedExitWarningToast() {
|
||||
return (
|
||||
<div
|
||||
className="w-[min(32rem,80vw)] rounded-md bg-amber-950 px-4 py-3 text-left text-amber-50"
|
||||
role="alert"
|
||||
>
|
||||
<p className="text-xl font-bold leading-tight text-amber-100">Please dock your rover</p>
|
||||
<p className="mt-1 text-base font-medium leading-snug text-amber-50/90">
|
||||
Your rover is still undocked. Please dock it before leaving the page.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function AlertContent({ alert }) {
|
||||
if (alert.kind === 'buttonbox-active' && alert.payload) {
|
||||
const payload = alert.payload;
|
||||
@@ -112,9 +98,6 @@ export default function AlertContent({ alert }) {
|
||||
if (alert.kind === 'barcode-scan' && alert.payload) {
|
||||
return <BarcodeScanToast payload={alert.payload} />;
|
||||
}
|
||||
if (alert.kind === 'undocked-exit-warning') {
|
||||
return <UndockedExitWarningToast />;
|
||||
}
|
||||
const color = typeof alert.color === 'string' ? alert.color.trim() : '';
|
||||
const backgroundColor = /^#?[0-9a-f]{6}$/i.test(color) ? `#${color.replace('#', '')}` : '#2196f3';
|
||||
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { createPortal, flushSync } from 'react-dom';
|
||||
import { useBlocker } from 'react-router-dom';
|
||||
import { useSessionSelector } from '../../context/SessionContext.jsx';
|
||||
|
||||
export default function PageExitGuard() {
|
||||
const shouldBlock = useSessionSelector((state) => state.session?.canLeaveRover === false);
|
||||
const [warning, setWarning] = useState({ blocked: shouldBlock, visible: false });
|
||||
// Clear an old exit attempt when server permission changes, so undocking
|
||||
// again does not resurrect a warning from the previous trip.
|
||||
if (warning.blocked !== shouldBlock) {
|
||||
setWarning({ blocked: shouldBlock, visible: false });
|
||||
}
|
||||
const blocker = useBlocker(({ currentLocation, nextLocation }) => shouldBlock && (
|
||||
currentLocation.pathname !== nextLocation.pathname || currentLocation.search !== nextLocation.search
|
||||
));
|
||||
|
||||
useEffect(() => {
|
||||
if (!shouldBlock) return undefined;
|
||||
function handleBeforeUnload(event) {
|
||||
// Commit before the native dialog pauses JavaScript. The browser still
|
||||
// decides whether it repaints the document before displaying its dialog.
|
||||
flushSync(() => setWarning({ blocked: true, visible: true }));
|
||||
event.preventDefault();
|
||||
event.returnValue = true;
|
||||
}
|
||||
function blockNavigation(event) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
setWarning({ blocked: true, visible: true });
|
||||
}
|
||||
function handleLinkClick(event) {
|
||||
if (event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return;
|
||||
const link = event.target instanceof Element ? event.target.closest('a[href]') : null;
|
||||
if (!link || link.hasAttribute('download')) return;
|
||||
const target = (link.getAttribute('target') || document.querySelector('base[target]')?.getAttribute('target') || '_self').toLowerCase();
|
||||
if (target !== '_self') return;
|
||||
const destination = new URL(link.href, window.location.href);
|
||||
if (destination.protocol !== 'http:' && destination.protocol !== 'https:') return;
|
||||
// Hash links stay in this document and do not abandon the rover.
|
||||
if (destination.origin === window.location.origin
|
||||
&& destination.pathname === window.location.pathname
|
||||
&& destination.search === window.location.search
|
||||
&& link.getAttribute('href').includes('#')) return;
|
||||
blockNavigation(event);
|
||||
}
|
||||
window.addEventListener('beforeunload', handleBeforeUnload);
|
||||
document.addEventListener('click', handleLinkClick, true);
|
||||
window.addEventListener('page:navigate', blockNavigation);
|
||||
return () => {
|
||||
window.removeEventListener('beforeunload', handleBeforeUnload);
|
||||
document.removeEventListener('click', handleLinkClick, true);
|
||||
window.removeEventListener('page:navigate', blockNavigation);
|
||||
};
|
||||
}, [shouldBlock]);
|
||||
|
||||
useEffect(() => {
|
||||
// Docking cancels the attempted navigation; the next attempt can proceed.
|
||||
if (!shouldBlock && blocker.state === 'blocked') blocker.reset();
|
||||
}, [shouldBlock, blocker]);
|
||||
|
||||
const visible = shouldBlock && (warning.visible || blocker.state === 'blocked');
|
||||
if (!visible) return null;
|
||||
|
||||
function dismiss() {
|
||||
setWarning({ blocked: shouldBlock, visible: false });
|
||||
if (blocker.state === 'blocked') blocker.reset();
|
||||
}
|
||||
|
||||
return createPortal(
|
||||
<div
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="page-exit-warning"
|
||||
className="fixed inset-0 z-[2147483647] flex flex-col items-center justify-between gap-4 bg-black p-6 text-center text-white"
|
||||
onKeyDown={(event) => {
|
||||
event.stopPropagation();
|
||||
if (event.key === 'Escape') dismiss();
|
||||
}}
|
||||
>
|
||||
<p id="page-exit-warning" className="text-[clamp(3rem,10vw,10rem)] font-bold leading-tight">
|
||||
Please dock your rover!
|
||||
</p>
|
||||
<button type="button" autoFocus className="button-dark px-8 py-4 text-3xl" onClick={dismiss}>
|
||||
Okay
|
||||
</button>
|
||||
<p aria-hidden="true" className="text-[clamp(3rem,10vw,10rem)] font-bold leading-tight">
|
||||
Please dock your rover!
|
||||
</p>
|
||||
</div>,
|
||||
document.body,
|
||||
);
|
||||
}
|
||||
@@ -21,6 +21,7 @@ export default function PtzQueueCard() {
|
||||
const featureEnabled = useSessionSelector((state) => isFeatureEnabled(state, 'ptzCamera'));
|
||||
const ptz = useSessionSelector((state) => state.session?.ptzCamera || null);
|
||||
const selfId = useSessionSelector((state) => state.session?.socketId || null);
|
||||
const canLeaveRover = useSessionSelector((state) => state.session?.canLeaveRover !== false);
|
||||
const { setOperatingMode } = useSessionActions();
|
||||
const navigate = useNavigate();
|
||||
const now = useSharedClock(1000, Boolean(ptz?.turn?.deadline));
|
||||
@@ -32,7 +33,7 @@ export default function PtzQueueCard() {
|
||||
if (!featureEnabled) return null;
|
||||
|
||||
const handleRequest = async () => {
|
||||
if (!canUse || pending) return;
|
||||
if (!canUse || !canLeaveRover || pending) return;
|
||||
if (isParticipant) {
|
||||
navigate('/ptz');
|
||||
return;
|
||||
@@ -76,14 +77,14 @@ export default function PtzQueueCard() {
|
||||
}}
|
||||
turn={ptz?.turn}
|
||||
selfId={selfId}
|
||||
canClick={canUse && !pending}
|
||||
canClick={canUse && canLeaveRover && !pending}
|
||||
pending={pending}
|
||||
buttonLabel={actionLabel}
|
||||
batteryLabel={ptz?.turn?.ownsControl ? 'LIVE' : ptz?.turn?.turnsAhead ? `#${ptz.turn.turnsAhead}` : '--'}
|
||||
batteryClassName={ptz?.turn?.ownsControl ? 'text-emerald-300' : ptz?.turn?.turnsAhead ? 'text-sky-300' : 'text-slate-400'}
|
||||
timerLabel={timerLabel}
|
||||
onRequest={handleRequest}
|
||||
showAction={canUse}
|
||||
showAction={canUse && canLeaveRover}
|
||||
/>
|
||||
</ul>
|
||||
{isParticipant ? (
|
||||
|
||||
@@ -101,6 +101,7 @@ export default function RoverQueuesPanel({
|
||||
fillHeight = false,
|
||||
}) {
|
||||
const role = useSessionSelector((state) => state.session?.role || null);
|
||||
const canLeaveRover = useSessionSelector((state) => state.session?.canLeaveRover !== false);
|
||||
const localRoster = useSessionSelector((state) => state.session?.roster ?? []);
|
||||
const interInstanceEnabled = useSessionSelector((state) => isFeatureEnabled(state, 'interInstance'));
|
||||
const { value: pageSettings } = useSettingsNamespace('page', { interInstanceTransferSettings: true });
|
||||
@@ -122,8 +123,8 @@ export default function RoverQueuesPanel({
|
||||
const roster = Array.isArray(rosterOverride) ? rosterOverride : localRoster;
|
||||
|
||||
const canRequest = useMemo(
|
||||
() => (externalMode ? !externalBlocked : role && role !== 'spectator'),
|
||||
[externalBlocked, externalMode, role],
|
||||
() => canLeaveRover && (externalMode ? !externalBlocked : role && role !== 'spectator'),
|
||||
[canLeaveRover, externalBlocked, externalMode, role],
|
||||
);
|
||||
const adminCapable = useMemo(
|
||||
() => role === 'admin' || role === 'lockdown',
|
||||
@@ -142,7 +143,7 @@ export default function RoverQueuesPanel({
|
||||
|
||||
async function handleRequest(targetRoverId) {
|
||||
if (!targetRoverId) return;
|
||||
if (externalBlocked) return;
|
||||
if (!canRequest) return;
|
||||
if (externalMode) {
|
||||
/*
|
||||
External queue cards deliberately reuse the local row layout, but their
|
||||
@@ -252,7 +253,7 @@ export default function RoverQueuesPanel({
|
||||
? lockLabel
|
||||
: externalMode
|
||||
? 'Open'
|
||||
: 'request';
|
||||
: 'Switch';
|
||||
const canClickRow = canRequest && !lockedBlocked && !pending[roverId];
|
||||
return (
|
||||
<QueueTargetRow
|
||||
|
||||
@@ -1,66 +0,0 @@
|
||||
// Undocked Page Exit Guard
|
||||
// Purpose: Asks the browser to confirm document-level navigation while the current driver's rover is undocked.
|
||||
// Scope: Owns the native beforeunload lifecycle and queues the matching AlertFeed explanation when leaving is attempted.
|
||||
import { useEffect } from 'react';
|
||||
import { useControlSelector } from '../../controls/index.js';
|
||||
import { useSessionActions } from '../../context/SessionContext.jsx';
|
||||
import { useTelemetrySelector } from '../../context/TelemetryContext.jsx';
|
||||
|
||||
const UNDOCKED_EXIT_ALERT_LIFETIME_MS = 15 * 1000;
|
||||
|
||||
function selectHomeBaseState(frame) {
|
||||
const homeBase = frame?.sensors?.chargingSources?.homeBase;
|
||||
|
||||
/*
|
||||
Missing telemetry must remain distinct from a real "not on the home base"
|
||||
reading. Treating the initial empty frame as undocked would enable the exit
|
||||
warning before the browser has received enough information to justify it.
|
||||
*/
|
||||
return typeof homeBase === 'boolean' ? homeBase : null;
|
||||
}
|
||||
|
||||
export default function UndockedPageExitGuard() {
|
||||
const roverId = useControlSelector((control) => control.state.roverId);
|
||||
const homeBaseState = useTelemetrySelector(roverId, selectHomeBaseState);
|
||||
const { pushAlert } = useSessionActions();
|
||||
const shouldConfirmExit = Boolean(roverId) && homeBaseState === false;
|
||||
|
||||
useEffect(() => {
|
||||
if (!shouldConfirmExit) return undefined;
|
||||
|
||||
function handleBeforeUnload(event) {
|
||||
/*
|
||||
Browsers intentionally own the wording and presentation of this dialog.
|
||||
preventDefault is the modern signal, while assigning returnValue keeps
|
||||
the confirmation working in browsers that still require the legacy part
|
||||
of the beforeunload contract.
|
||||
*/
|
||||
event.preventDefault();
|
||||
event.returnValue = true;
|
||||
|
||||
/*
|
||||
If the driver cancels the browser-owned confirmation, React remains
|
||||
mounted and AlertFeed presents the actionable reason for the warning.
|
||||
A stable id refreshes this one warning lane on another exit attempt
|
||||
instead of stacking duplicate cards over the driving interface.
|
||||
*/
|
||||
pushAlert({
|
||||
id: 'undocked-page-exit-warning',
|
||||
kind: 'undocked-exit-warning',
|
||||
lifetimeMs: UNDOCKED_EXIT_ALERT_LIFETIME_MS,
|
||||
});
|
||||
}
|
||||
|
||||
window.addEventListener('beforeunload', handleBeforeUnload);
|
||||
return () => {
|
||||
/*
|
||||
Removing the listener as soon as the rover docks or the assignment ends
|
||||
prevents ordinary spectators and completed drivers from seeing a stale
|
||||
leave-page confirmation.
|
||||
*/
|
||||
window.removeEventListener('beforeunload', handleBeforeUnload);
|
||||
};
|
||||
}, [pushAlert, shouldConfirmExit]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -28,7 +28,6 @@ import useLayoutMode from '../hooks/useLayoutMode.js';
|
||||
import { DriverHelpProvider } from '../layouts/driver/DriverHelpContext.jsx';
|
||||
import { LayoutProvider } from '../layouts/LayoutContext.jsx';
|
||||
import DriverLayoutRoot from '../layouts/driver/DriverLayoutRoot.jsx';
|
||||
import UndockedPageExitGuard from '../components/UndockedPageExitGuard/index.jsx';
|
||||
|
||||
/* Driver-page compositions live under layouts/driver. App retains only global providers, overlays, and route-level state. */
|
||||
function DriverPageRoot({ oldDesktop = false }) {
|
||||
@@ -92,7 +91,6 @@ function DriverPageContent({ layout, oldDesktop }) {
|
||||
return (
|
||||
<ControlSystemProvider>
|
||||
<RoomAudioPlayer />
|
||||
<UndockedPageExitGuard />
|
||||
<KeyboardInputManager />
|
||||
<GamepadInputManager />
|
||||
<main className={`relative flex w-full flex-col ${themeGapClass} text-base`}>
|
||||
|
||||
@@ -40,5 +40,8 @@ export function buildExternalRoverUrl(instance, roverId, { includeSettings = fal
|
||||
export function openExternalRover(instance, roverId, { includeSettings = true } = {}) {
|
||||
const targetUrl = buildExternalRoverUrl(instance, roverId, { includeSettings });
|
||||
if (!targetUrl) return;
|
||||
// These queue actions are buttons, so let the page guard veto navigation
|
||||
// before beforeunload would pause painting behind the native browser dialog.
|
||||
if (!window.dispatchEvent(new Event('page:navigate', { cancelable: true }))) return;
|
||||
window.location.href = targetUrl;
|
||||
}
|
||||
|
||||
+39
-29
@@ -2,7 +2,7 @@
|
||||
// Purpose: Boots the React application and mounts global providers/router roots. Scope: Defines top-level route wiring and root render lifecycle for the browser app.
|
||||
import { lazy, StrictMode, Suspense } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom'
|
||||
import { createBrowserRouter, Route, RouterProvider, Routes } from 'react-router-dom'
|
||||
import './index.css'
|
||||
// Theme artwork is a separate style concern from global component utilities. Loading its dedicated
|
||||
// entrypoint here keeps every route consistent without returning theme definitions to index.css.
|
||||
@@ -22,6 +22,7 @@ import AnalyticsReporter from './analytics/AnalyticsReporter.jsx'
|
||||
import PtzAppRoot from './ptz/PtzAppRoot.jsx'
|
||||
import MicApp from './mic/MicApp.jsx'
|
||||
import OperatingModeRouteSync from './components/OperatingModeRouteSync/index.jsx'
|
||||
import PageExitGuard from './components/PageExitGuard/index.jsx'
|
||||
import InitialSessionOverlay from './components/InitialSessionOverlay/index.jsx'
|
||||
import AppErrorBoundary from './components/AppErrorBoundary.jsx'
|
||||
|
||||
@@ -41,6 +42,42 @@ function lazyRoute(element, label) {
|
||||
)
|
||||
}
|
||||
|
||||
// A data router provides one blocker for links, programmatic navigation, and history.
|
||||
const router = createBrowserRouter([{
|
||||
path: '*',
|
||||
element: (
|
||||
<>
|
||||
<AnalyticsReporter />
|
||||
<OperatingModeRouteSync />
|
||||
<PageExitGuard />
|
||||
<Routes>
|
||||
<Route path="/" element={<DriverPageRoot />} />
|
||||
{/* The retired desktop composition remains available for direct comparison
|
||||
without duplicating the driver shell or changing canonical mobile layouts. */}
|
||||
<Route path="/old" element={<DriverPageRoot oldDesktop />} />
|
||||
<Route path="/spectate" element={<SpectatorApp />} />
|
||||
<Route path="/mini" element={<MiniSummaryApp />} />
|
||||
<Route path="/display" element={<ServerDisplayApp />} />
|
||||
<Route path="/mic" element={<MicApp />} />
|
||||
<Route path="/scanner" element={<ScannerApp />} />
|
||||
<Route path="/setup" element={lazyRoute(<SetupApp />, 'setup')} />
|
||||
<Route path="/admin" element={lazyRoute(<AdminApp />, 'administration')} />
|
||||
{/*
|
||||
PTZ is a separate route so the driver layout and its replay
|
||||
panel are not mounted behind the camera controller. This
|
||||
also makes orientation changes a PTZ layout concern instead
|
||||
of a local overlay-open state owned by the driver page.
|
||||
*/}
|
||||
<Route path="/ptz" element={<PtzAppRoot />} />
|
||||
<Route
|
||||
path="/reports"
|
||||
element={lazyRoute(<FleetReportsApp />, 'fleet reports')}
|
||||
/>
|
||||
</Routes>
|
||||
</>
|
||||
),
|
||||
}])
|
||||
|
||||
createRoot(document.getElementById('root')).render(
|
||||
<AppErrorBoundary>
|
||||
<StrictMode>
|
||||
@@ -55,34 +92,7 @@ createRoot(document.getElementById('root')).render(
|
||||
<SettingsProvider>
|
||||
<ChatProvider>
|
||||
<DeterrenceChaos />
|
||||
<BrowserRouter>
|
||||
<AnalyticsReporter />
|
||||
<OperatingModeRouteSync />
|
||||
<Routes>
|
||||
<Route path="/" element={<DriverPageRoot />} />
|
||||
{/* The retired desktop composition remains available for direct comparison
|
||||
without duplicating the driver shell or changing canonical mobile layouts. */}
|
||||
<Route path="/old" element={<DriverPageRoot oldDesktop />} />
|
||||
<Route path="/spectate" element={<SpectatorApp />} />
|
||||
<Route path="/mini" element={<MiniSummaryApp />} />
|
||||
<Route path="/display" element={<ServerDisplayApp />} />
|
||||
<Route path="/mic" element={<MicApp />} />
|
||||
<Route path="/scanner" element={<ScannerApp />} />
|
||||
<Route path="/setup" element={lazyRoute(<SetupApp />, 'setup')} />
|
||||
<Route path="/admin" element={lazyRoute(<AdminApp />, 'administration')} />
|
||||
{/*
|
||||
PTZ is a separate route so the driver layout and its replay
|
||||
panel are not mounted behind the camera controller. This
|
||||
also makes orientation changes a PTZ layout concern instead
|
||||
of a local overlay-open state owned by the driver page.
|
||||
*/}
|
||||
<Route path="/ptz" element={<PtzAppRoot />} />
|
||||
<Route
|
||||
path="/reports"
|
||||
element={lazyRoute(<FleetReportsApp />, 'fleet reports')}
|
||||
/>
|
||||
</Routes>
|
||||
</BrowserRouter>
|
||||
<RouterProvider router={router} />
|
||||
</ChatProvider>
|
||||
</SettingsProvider>
|
||||
</TelemetryProvider>
|
||||
|
||||
Reference in New Issue
Block a user