-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathAppLayout.tsx
More file actions
300 lines (263 loc) · 11.9 KB
/
Copy pathAppLayout.tsx
File metadata and controls
300 lines (263 loc) · 11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
/**
* App Layout Component
*
* The main layout component for the application.
* It provides the responsive sidebar navigation, mobile header, and main content area.
* It also handles the sidebar resizing logic and mobile drawer state.
*/
import { Outlet, useLocation, Navigate } from 'react-router-dom';
import logoUrl from '../../../assets/logo.png';
import { useCurrentProfile } from '../../hooks/useCurrentProfile';
import { useProfileStore } from '../../stores/profile';
import { useSettingsStore } from '../../stores/settings';
import { Button } from '../ui/button';
import { log, LogLevel } from '../../lib/logger';
import { viewNameForPath } from '../../lib/navigation';
import { useInsomnia } from '../../hooks/useInsomnia';
import {
Menu,
ChevronLeft,
ChevronRight,
Eye,
EyeOff,
Command,
} from 'lucide-react';
import { useCommandPaletteStore } from '../../stores/commandPalette';
import { useState, useEffect, useCallback, useRef } from 'react';
import { useShallow } from 'zustand/react/shallow';
import { Sheet, SheetContent, SheetDescription, SheetTitle, SheetTrigger } from '../ui/sheet';
import { useTranslation } from 'react-i18next';
import { BackgroundTaskDrawer } from '../BackgroundTaskDrawer';
import { CertTrustDialog } from '../CertTrustDialog';
import { onCertTrustRequest, type PendingCertTrust } from '../../lib/security/cert-trust-event';
import { useTvMode } from '../../hooks/useTvMode';
import { enableSpatialNavigation, checkIsTV } from '../../lib/tv/tv-spatial-nav';
import { useKioskStore } from '../../stores/kioskStore';
import { KioskOverlay } from '../kiosk/KioskOverlay';
import { SidebarContent } from './SidebarContent';
import { DeveloperNoticeBanner } from './DeveloperNoticeBanner';
import { OfflineBanner } from './OfflineBanner';
import { useReconcileDeletedMonitors } from '../../hooks/useReconcileDeletedMonitors';
import { CertTrustBanner } from '../CertTrustBanner';
import { DeleteBatchBar } from '../events/DeleteBatchBar';
import { AssistantWidget } from '../assistant/AssistantWidget';
/**
* AppLayout Component
* The main layout wrapper that includes the sidebar and main content area.
*/
export default function AppLayout() {
const { currentProfile, settings } = useCurrentProfile();
const updateProfileSettings = useSettingsStore((state) => state.updateProfileSettings);
const location = useLocation();
const [isMobileOpen, setIsMobileOpen] = useState(false);
const [isCollapsed, setIsCollapsed] = useState(() => (settings.sidebarWidth ?? 256) <= 80);
const { t } = useTranslation();
const { isTvMode } = useTvMode();
useEffect(() => {
document.documentElement.classList.toggle('tv-mode', isTvMode);
return () => document.documentElement.classList.remove('tv-mode');
}, [isTvMode]);
useEffect(() => {
if (isTvMode) {
enableSpatialNavigation();
}
}, [isTvMode]);
const profileId = currentProfile?.id;
const tvAutoDetectedRef = useRef(false);
useEffect(() => {
if (!profileId || tvAutoDetectedRef.current) return;
tvAutoDetectedRef.current = true;
checkIsTV().then((isTV) => {
if (isTV && !settings.tvMode) {
updateProfileSettings(profileId, { tvMode: true });
}
});
}, [profileId, settings.tvMode, updateProfileSettings]);
// Track route changes and save to settings
useEffect(() => {
if (!currentProfile?.id) return;
// Bold banner so view transitions are easy to spot in the console
const viewName = viewNameForPath(location.pathname);
if (viewName) {
log.banner(`Entering ${viewName} View`);
}
// Exclude setup/profile routes and notification-opened pages from being saved as lastRoute
const excludedRoutes = ['/profiles/new', '/setup', '/profiles'];
const fromNotification = (location.state as Record<string, unknown>)?.fromNotification === true;
const shouldSave = !excludedRoutes.includes(location.pathname) && !fromNotification;
if (shouldSave) {
updateProfileSettings(currentProfile.id, { lastRoute: location.pathname });
log.app('Storing route', LogLevel.DEBUG, { route: location.pathname });
}
}, [location.pathname, currentProfile?.id, updateProfileSettings]);
// Apply global insomnia setting
useInsomnia({ enabled: settings.insomnia });
// Forget monitors ZoneMinder no longer has (refs #323, #324)
useReconcileDeletedMonitors();
const { isLocked, previousInsomniaState } = useKioskStore(
useShallow((state) => ({
isLocked: state.isLocked,
previousInsomniaState: state.previousInsomniaState,
}))
);
useEffect(() => {
if (isLocked && !isCollapsed) {
setIsCollapsed(true);
}
}, [isLocked]);
const handleKioskUnlock = useCallback(() => {
if (currentProfile) {
updateProfileSettings(currentProfile.id, { insomnia: previousInsomniaState });
}
}, [currentProfile, previousInsomniaState, updateProfileSettings]);
const expandedWidth = 180;
const collapsedWidth = 60;
const sidebarWidth = isCollapsed ? collapsedWidth : expandedWidth;
const toggleSidebar = () => {
const next = !isCollapsed;
setIsCollapsed(next);
if (currentProfile) {
updateProfileSettings(currentProfile.id, { sidebarWidth: next ? collapsedWidth : expandedWidth });
}
};
// TOFU certificate trust migration dialog: hooks must be above any early return
const [pendingCert, setPendingCert] = useState<PendingCertTrust | null>(null);
useEffect(() => {
return onCertTrustRequest((pending) => {
setPendingCert(pending);
});
}, []);
const handleCertTrust = useCallback(async () => {
if (!pendingCert) return;
const { profileId, certInfo } = pendingCert;
setPendingCert(null);
updateProfileSettings(profileId, { trustedCertFingerprint: certInfo.fingerprint });
const { applySSLTrustSetting } = await import('../../lib/security/ssl-trust');
await applySSLTrustSetting(true, certInfo.fingerprint);
log.app('Certificate trusted via TOFU migration', LogLevel.INFO);
}, [pendingCert, updateProfileSettings]);
const handleCertCancel = useCallback(async () => {
if (!pendingCert) return;
const { profileId } = pendingCert;
setPendingCert(null);
// Disable self-signed certs since user rejected the certificate
updateProfileSettings(profileId, { allowSelfSignedCerts: false, trustedCertFingerprint: null });
const { applySSLTrustSetting } = await import('../../lib/security/ssl-trust');
await applySSLTrustSetting(false);
log.app('Certificate rejected, disabling self-signed cert support', LogLevel.INFO);
}, [pendingCert, updateProfileSettings]);
// Check for profile after all hooks are called to avoid hooks violation
if (!currentProfile) {
if (location.pathname === '/profiles') {
// Allow access to profiles page without a current profile
} else {
const profiles = useProfileStore.getState().profiles;
return <Navigate to={profiles.length > 0 ? "/profiles" : "/profiles/new"} replace />;
}
}
return (
<div className="flex h-[100dvh] bg-background overflow-hidden pl-[var(--sai-left,env(safe-area-inset-left))] pr-[var(--sai-right,env(safe-area-inset-right))]">
{/* Desktop Sidebar */}
<aside
className="hidden md:flex flex-col border-r bg-card/50 backdrop-blur-xl z-20 transition-all duration-300 relative group pt-[var(--sai-top,env(safe-area-inset-top))]"
style={{ width: `${sidebarWidth}px` }}
data-tv-region="sidebar"
>
<SidebarContent isCollapsed={isCollapsed} />
{/* Toggle Button */}
<div
className={`absolute right-0 top-1/2 -translate-y-1/2 translate-x-1/2 w-5 h-10 bg-primary hover:bg-primary/90 rounded-full flex items-center justify-center cursor-pointer shadow-lg z-50 transition-all duration-200 ${isTvMode ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'}`}
onClick={toggleSidebar}
onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); toggleSidebar(); } }}
tabIndex={0}
role="button"
title={isCollapsed ? t('sidebar.expand') : t('sidebar.collapse')}
data-testid="sidebar-toggle"
>
{isCollapsed ? (
<ChevronRight className="h-4 w-4 text-primary-foreground" />
) : (
<ChevronLeft className="h-4 w-4 text-primary-foreground" />
)}
</div>
</aside>
{/* Mobile Header */}
{!isLocked && (
<div className="md:hidden fixed top-0 left-0 right-0 h-[calc(3rem+var(--sai-top,env(safe-area-inset-top)))] pt-[var(--sai-top,env(safe-area-inset-top))] border-b bg-background z-30 flex items-center px-3 justify-between">
<div className="flex items-center gap-2">
{/* Menu on the left so the button sits on the side the drawer opens from. */}
<Sheet open={isMobileOpen} onOpenChange={setIsMobileOpen}>
<SheetTrigger asChild>
<Button variant="ghost" size="icon" aria-label={t('app.navigation_menu')} data-testid="mobile-menu-button">
<Menu className="h-5 w-5" />
</Button>
</SheetTrigger>
<SheetContent side="left" className="p-0 w-64 sm:w-72 flex flex-col pt-[var(--sai-top,env(safe-area-inset-top))]">
<SheetTitle className="sr-only">{t('app.navigation_menu')}</SheetTitle>
<SheetDescription className="sr-only">{t('app.navigation_menu_desc')}</SheetDescription>
<div className="flex-1 overflow-y-auto">
<SidebarContent onMobileClose={() => setIsMobileOpen(false)} />
</div>
</SheetContent>
</Sheet>
<img src={logoUrl} alt={t('app.logo_alt')} className="h-8 w-8 rounded-lg" />
<span className="font-bold">{t('app.name')}</span>
</div>
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="icon"
onClick={() => useCommandPaletteStore.getState().setOpen(true)}
title={t('command_palette.jump_to')}
data-testid="command-palette-trigger-mobile"
>
<Command className="h-5 w-5" />
</Button>
{location.pathname === '/montage' && (
<Button
variant="ghost"
size="icon"
onClick={() => {
if (currentProfile) {
updateProfileSettings(currentProfile.id, {
montageShowToolbar: !settings.montageShowToolbar,
});
}
}}
title={t('montage.toggle_toolbar')}
data-testid="montage-toolbar-toggle"
>
{settings.montageShowToolbar ? <Eye className="h-5 w-5" /> : <EyeOff className="h-5 w-5" />}
</Button>
)}
</div>
</div>
)}
{/* Main Content */}
<main className="flex-1 overflow-y-auto overflow-x-hidden relative w-full pt-[calc(3rem+var(--sai-top,env(safe-area-inset-top)))] md:pt-[var(--sai-top,env(safe-area-inset-top))] pb-[var(--sai-bottom,env(safe-area-inset-bottom))]" data-tv-region="main">
{/* Background gradient blob for visual interest */}
<div className="absolute top-0 left-0 w-full h-96 bg-gradient-to-b from-primary/5 to-transparent -z-10 pointer-events-none" />
<DeveloperNoticeBanner />
<OfflineBanner />
<CertTrustBanner />
<Outlet />
<DeleteBatchBar />
</main>
{/* Global Background Task Drawer */}
<BackgroundTaskDrawer />
{/* TOFU certificate trust migration dialog */}
<CertTrustDialog
open={!!pendingCert}
certInfo={pendingCert?.certInfo ?? null}
isChanged={false}
onTrust={handleCertTrust}
onCancel={handleCertCancel}
/>
<KioskOverlay onUnlock={handleKioskUnlock} />
{/* Rendered once at the app root, not per-route, so navigating (e.g. an
assistant "Open" card, or its own `navigate` tool call) never
unmounts the conversation underneath it (refs #246). */}
<AssistantWidget />
</div>
);
}