Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr Vision8 * File : web/src/App.tsx9 * Module : web10 * Repository : https://git.spboucher.ai/maclustr-vision11 * Project Website : https://camera.spboucher.ai12 * Created : 2026-11-3013 * Last Modified : 2026-11-3014 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142import { useCallback, useEffect, useMemo, useRef, useState } from 'react';43import { api, setUnauthorizedHandler, type CameraDto } from './api';44import { CommandPalette, ShortcutHelp, type Command } from './components/CommandPalette';45import { Mark } from './components/Mark';46import { StatusRail } from './components/StatusRail';47import { Ctx, Link, useRoute } from './ctx';48import { setTimezone } from './fmt';49import { IconEvents, IconHistory, IconLive, IconLogout, IconSettings, IconStorage, IconSystem } from './icons';50import { CameraPage } from './pages/Camera';51import { EventsPage } from './pages/Events';52import { HistoryPage } from './pages/History';53import { LivePage } from './pages/Live';54import { LoginPage } from './pages/Login';55import { SettingsPage } from './pages/Settings';56import { SetupPage, takeSetupToken } from './pages/Setup';57import { StoragePage } from './pages/Storage';58import { SystemPage } from './pages/System';59import { getPrefs, setPrefs } from './prefs';6061type Auth = { state: 'loading' | 'out' | 'in'; sessionId: string; configured: boolean; version: string };6263export function isTyping(e: KeyboardEvent): boolean {64 const t = e.target as HTMLElement | null;65 return !!t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.tagName === 'SELECT' || t.isContentEditable);66}6768export function App() {69 const [auth, setAuth] = useState<Auth>({ state: 'loading', sessionId: '', configured: true, version: '' });70 const [cameras, setCameras] = useState<CameraDto[]>([]);71 const [clockOffset, setClockOffset] = useState(0);72 const [toastMsg, setToastMsg] = useState<string | null>(null);73 const [palette, setPalette] = useState(false);74 const [help, setHelp] = useState(false);75 const toastTimer = useRef<number | null>(null);76 const route = useRoute();77 const [setupToken, setSetupToken] = useState<string | null>(() => takeSetupToken());7879 const check = useCallback(async () => {80 try {81 const s = await api('/api/auth/session', { quiet401: true });82 if (s.authenticated) {83 setTimezone(s.timezone);84 setAuth({ state: 'in', sessionId: s.sessionId, configured: true, version: s.version || '' });85 } else setAuth({ state: 'out', sessionId: '', configured: s.configured !== false, version: '' });86 } catch {87 setAuth((a) => (a.state === 'loading' ? { state: 'out', sessionId: '', configured: true, version: '' } : a));88 }89 }, []);9091 useEffect(() => {92 setUnauthorizedHandler(() => setAuth({ state: 'out', sessionId: '', configured: true, version: '' }));93 void check();94 }, [check]);9596 const refreshCameras = useCallback(async () => {97 const r = await api<{ cameras: CameraDto[]; serverTimeMs: number }>('/api/cameras');98 setCameras(r.cameras);99 if (r.serverTimeMs) setClockOffset(r.serverTimeMs - Date.now());100 }, []);101102 useEffect(() => {103 if (auth.state !== 'in') return;104 const run = () => !document.hidden && void refreshCameras().catch(() => {});105 run();106 const t = window.setInterval(run, 5000);107 document.addEventListener('visibilitychange', run);108 return () => {109 clearInterval(t);110 document.removeEventListener('visibilitychange', run);111 };112 }, [auth.state, refreshCameras]);113114 const toast = useCallback((msg: string) => {115 setToastMsg(msg);116 if (toastTimer.current) clearTimeout(toastTimer.current);117 toastTimer.current = window.setTimeout(() => setToastMsg(null), 3400);118 }, []);119120 const logout = useCallback(() => {121 void api('/api/auth/logout', { method: 'POST' })122 .catch(() => {})123 .finally(() => {124 setCameras([]);125 document.body.classList.remove('cinema');126 setAuth({ state: 'out', sessionId: '', configured: true, version: '' });127 });128 }, []);129130 const { navigate } = route;131 // raccourcis globaux132 useEffect(() => {133 if (auth.state !== 'in') return;134 const on = (e: KeyboardEvent) => {135 if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') {136 e.preventDefault();137 setPalette((p) => !p);138 return;139 }140 if (isTyping(e) || e.metaKey || e.ctrlKey || e.altKey || palette || help) return;141 if (e.key === '?') setHelp(true);142 else if (e.key === 'g' || e.key === 'G') navigate('/');143 else if (e.key === 'h' || e.key === 'H') navigate('/history');144 else if (/^[1-9]$/.test(e.key)) {145 const c = cameras[Number(e.key) - 1];146 if (c) navigate(`/camera/${encodeURIComponent(c.id)}`);147 } else if (e.key === 'Escape') document.body.classList.remove('cinema');148 };149 window.addEventListener('keydown', on);150 return () => window.removeEventListener('keydown', on);151 }, [auth.state, cameras, navigate, palette, help]);152153 const commands = useMemo<Command[]>(() => {154 const go = (to: string) => () => navigate(to);155 const p = getPrefs();156 return [157 { id: 'p-live', group: 'Page', label: 'Mur de moniteurs', hint: 'G', run: go('/') },158 { id: 'p-hist', group: 'Page', label: 'Historique', hint: 'H', run: go('/history') },159 { id: 'p-ev', group: 'Page', label: 'Événements', run: go('/events') },160 { id: 'p-st', group: 'Page', label: 'Stockage', run: go('/storage') },161 { id: 'p-sys', group: 'Page', label: 'Système', run: go('/system') },162 { id: 'p-set', group: 'Page', label: 'Réglages et options avancées', run: go('/settings') },163 ...cameras.flatMap((c, i) => [164 { id: `c-${c.id}`, group: 'Direct', label: c.name, hint: i < 9 ? String(i + 1) : undefined, run: go(`/camera/${encodeURIComponent(c.id)}`) },165 { id: `h-${c.id}`, group: 'Historique', label: c.name, run: go(`/history?camera=${encodeURIComponent(c.id)}`) },166 ]),167 { id: 'a-cinema', group: 'Action', label: 'Mode cinéma : masquer l’interface', hint: 'C', run: () => (navigate('/'), document.body.classList.add('cinema')) },168 { id: 'a-stats', group: 'Action', label: p.stats ? 'Masquer les statistiques techniques' : 'Afficher les statistiques techniques', hint: 'I', run: () => setPrefs({ stats: !getPrefs().stats }) },169 { id: 'a-marks', group: 'Action', label: p.marks ? 'Masquer les repères de viseur' : 'Afficher les repères de viseur', run: () => setPrefs({ marks: !getPrefs().marks }) },170 { id: 'a-fit', group: 'Action', label: p.fit === 'cover' ? 'Cadrage : image entière' : 'Cadrage : remplir les tuiles', run: () => setPrefs({ fit: getPrefs().fit === 'cover' ? 'contain' : 'cover' }) },171 { id: 'a-focus', group: 'Action', label: 'Disposition focus (une grande, les autres en bande)', run: () => (setPrefs({ layout: 9 }), navigate('/')) },172 { id: 'a-help', group: 'Action', label: 'Raccourcis clavier', hint: '?', run: () => setHelp(true) },173 { id: 'a-lock', group: 'Action', label: 'Verrouiller cet appareil', run: logout },174 ];175 // eslint-disable-next-line react-hooks/exhaustive-deps176 }, [cameras, navigate, logout, palette]);177178 if (setupToken) return <SetupPage token={setupToken} onDone={() => (setSetupToken(null), void check())} />;179 if (auth.state === 'loading')180 return (181 <div className="login" aria-busy="true">182 <div className="spinner" role="status">183 <span className="sr-only">Chargement</span>184 </div>185 </div>186 );187 if (auth.state === 'out') return <LoginPage configured={auth.configured} onDone={() => void check()} />;188189 const p = route.path;190 const nav = [191 { to: '/', label: 'Direct', icon: <IconLive />, on: p === '/' || p.startsWith('/camera/'), hint: 'G' },192 { to: '/history', label: 'Historique', icon: <IconHistory />, on: p.startsWith('/history'), hint: 'H' },193 { to: '/events', label: 'Événements', icon: <IconEvents />, on: p.startsWith('/events') },194 { to: '/storage', label: 'Stockage', icon: <IconStorage />, on: p.startsWith('/storage'), desktopOnly: true },195 { to: '/system', label: 'Système', icon: <IconSystem />, on: p.startsWith('/system'), desktopOnly: true },196 { to: '/settings', label: 'Réglages', icon: <IconSettings />, on: p.startsWith('/settings') },197 ];198 let page;199 if (p.startsWith('/camera/')) page = <CameraPage key={p} id={decodeURIComponent(p.slice(8))} />;200 else if (p.startsWith('/history')) page = <HistoryPage />;201 else if (p.startsWith('/events')) page = <EventsPage />;202 else if (p.startsWith('/storage')) page = <StoragePage />;203 else if (p.startsWith('/system')) page = <SystemPage />;204 else if (p.startsWith('/settings')) page = <SettingsPage />;205 else page = <LivePage />;206 const mobileNav = nav.filter((n) => !n.desktopOnly).map((n) => (n.to === '/settings' ? { ...n, on: n.on || p.startsWith('/storage') || p.startsWith('/system') } : n));207208 return (209 <Ctx.Provider value={{ cameras, refreshCameras, path: route.path, query: route.query, navigate: route.navigate, toast, logout, sessionId: auth.sessionId, clockOffset, version: auth.version }}>210 <div className="shell">211 <nav className="side" aria-label="Navigation principale">212 <div className="brand">213 <Mark size={30} />214 <div>215 <b>VISION</b>216 <span>MacLustr</span>217 </div>218 </div>219 {nav.map((n) => (220 <Link key={n.to} to={n.to} className="navlink" current={n.on}>221 {n.icon}222 {n.label}223 {n.hint && <kbd className="hint">{n.hint}</kbd>}224 </Link>225 ))}226 <div className="spacer" />227 <button className="navlink" onClick={logout}>228 <IconLogout />229 Verrouiller230 </button>231 <div className="foot mono">232 <span>v{auth.version}</span>233 </div>234 </nav>235 <StatusRail onPalette={() => setPalette(true)} onHelp={() => setHelp(true)} />236 <main className="main" id="contenu">237 {page}238 </main>239 <nav className="tabbar" aria-label="Navigation principale">240 {mobileNav.map((n) => (241 <Link key={n.to} to={n.to} className="tab" current={n.on}>242 {n.icon}243 <span>{n.label}</span>244 </Link>245 ))}246 </nav>247 </div>248 {palette && <CommandPalette commands={commands} onClose={() => setPalette(false)} />}249 {help && <ShortcutHelp onClose={() => setHelp(false)} />}250 {toastMsg && (251 <div className="toast" role="status">252 {toastMsg}253 </div>254 )}255 </Ctx.Provider>256 );257}258