Layout.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. import { Outlet, Link, useLocation } from 'react-router-dom'
  2. import { useEffect, useState, useRef } from 'react'
  3. import { toast } from 'sonner'
  4. import { NowPlayingBar } from '@/components/NowPlayingBar'
  5. const navItems = [
  6. { path: '/', label: 'Browse', icon: 'grid_view', title: 'Browse Patterns' },
  7. { path: '/playlists', label: 'Playlists', icon: 'playlist_play', title: 'Playlists' },
  8. { path: '/table-control', label: 'Control', icon: 'tune', title: 'Table Control' },
  9. { path: '/led', label: 'LED', icon: 'lightbulb', title: 'LED Control' },
  10. { path: '/settings', label: 'Settings', icon: 'settings', title: 'Settings' },
  11. ]
  12. const DEFAULT_APP_NAME = 'Dune Weaver'
  13. export function Layout() {
  14. const location = useLocation()
  15. const [isDark, setIsDark] = useState(() => {
  16. if (typeof window !== 'undefined') {
  17. const saved = localStorage.getItem('theme')
  18. if (saved) return saved === 'dark'
  19. return window.matchMedia('(prefers-color-scheme: dark)').matches
  20. }
  21. return false
  22. })
  23. // App customization
  24. const [appName, setAppName] = useState(DEFAULT_APP_NAME)
  25. const [customLogo, setCustomLogo] = useState<string | null>(null)
  26. // Connection status
  27. const [isConnected, setIsConnected] = useState(false)
  28. const wsRef = useRef<WebSocket | null>(null)
  29. // Fetch app settings
  30. const fetchAppSettings = () => {
  31. fetch('/api/settings')
  32. .then((r) => r.json())
  33. .then((settings) => {
  34. if (settings.app?.name) {
  35. setAppName(settings.app.name)
  36. } else {
  37. setAppName(DEFAULT_APP_NAME)
  38. }
  39. setCustomLogo(settings.app?.custom_logo || null)
  40. })
  41. .catch(() => {})
  42. }
  43. useEffect(() => {
  44. fetchAppSettings()
  45. // Listen for branding updates from Settings page
  46. const handleBrandingUpdate = () => {
  47. fetchAppSettings()
  48. }
  49. window.addEventListener('branding-updated', handleBrandingUpdate)
  50. return () => {
  51. window.removeEventListener('branding-updated', handleBrandingUpdate)
  52. }
  53. }, [])
  54. // Logs drawer state
  55. const [isLogsOpen, setIsLogsOpen] = useState(false)
  56. // Now Playing bar state
  57. const [isNowPlayingOpen, setIsNowPlayingOpen] = useState(false)
  58. const [logs, setLogs] = useState<Array<{ timestamp: string; level: string; logger: string; message: string }>>([])
  59. const [logLevelFilter, setLogLevelFilter] = useState<string>('ALL')
  60. const logsWsRef = useRef<WebSocket | null>(null)
  61. const logsContainerRef = useRef<HTMLDivElement>(null)
  62. // Check device connection status via WebSocket
  63. useEffect(() => {
  64. const connectWebSocket = () => {
  65. const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
  66. const ws = new WebSocket(`${protocol}//${window.location.host}/ws/status`)
  67. ws.onmessage = (event) => {
  68. try {
  69. const data = JSON.parse(event.data)
  70. // Use device connection status from the status message
  71. if (data.connected !== undefined) {
  72. setIsConnected(data.connected)
  73. }
  74. } catch {
  75. // Ignore parse errors
  76. }
  77. }
  78. ws.onclose = () => {
  79. // Reconnect after 3 seconds (don't change device status on WS disconnect)
  80. setTimeout(connectWebSocket, 3000)
  81. }
  82. wsRef.current = ws
  83. }
  84. connectWebSocket()
  85. return () => {
  86. if (wsRef.current) {
  87. wsRef.current.close()
  88. }
  89. }
  90. }, [])
  91. // Connect to logs WebSocket when drawer opens
  92. useEffect(() => {
  93. if (!isLogsOpen) {
  94. // Close WebSocket when drawer closes
  95. if (logsWsRef.current) {
  96. logsWsRef.current.close()
  97. logsWsRef.current = null
  98. }
  99. return
  100. }
  101. // Fetch initial logs
  102. const fetchInitialLogs = async () => {
  103. try {
  104. const response = await fetch('/api/logs?limit=200')
  105. const data = await response.json()
  106. // Filter out empty/invalid log entries
  107. const validLogs = (data.logs || []).filter(
  108. (log: { message?: string }) => log && log.message && log.message.trim() !== ''
  109. )
  110. // API returns newest first, reverse to show oldest first (newest at bottom)
  111. setLogs(validLogs.reverse())
  112. // Scroll to bottom after initial load
  113. setTimeout(() => {
  114. if (logsContainerRef.current) {
  115. logsContainerRef.current.scrollTop = logsContainerRef.current.scrollHeight
  116. }
  117. }, 100)
  118. } catch {
  119. // Ignore errors
  120. }
  121. }
  122. fetchInitialLogs()
  123. // Connect to WebSocket for real-time updates
  124. let reconnectTimeout: ReturnType<typeof setTimeout> | null = null
  125. const connectLogsWebSocket = () => {
  126. const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
  127. const ws = new WebSocket(`${protocol}//${window.location.host}/ws/logs`)
  128. ws.onopen = () => {
  129. console.log('Logs WebSocket connected')
  130. }
  131. ws.onmessage = (event) => {
  132. try {
  133. const message = JSON.parse(event.data)
  134. // Skip heartbeat messages
  135. if (message.type === 'heartbeat') {
  136. return
  137. }
  138. // Extract log from wrapped structure
  139. const log = message.type === 'log_entry' ? message.data : message
  140. // Skip empty or invalid log entries
  141. if (!log || !log.message || log.message.trim() === '') {
  142. return
  143. }
  144. setLogs((prev) => {
  145. const newLogs = [...prev, log]
  146. // Keep only last 500 logs to prevent memory issues
  147. if (newLogs.length > 500) {
  148. return newLogs.slice(-500)
  149. }
  150. return newLogs
  151. })
  152. // Auto-scroll to bottom
  153. setTimeout(() => {
  154. if (logsContainerRef.current) {
  155. logsContainerRef.current.scrollTop = logsContainerRef.current.scrollHeight
  156. }
  157. }, 10)
  158. } catch {
  159. // Ignore parse errors
  160. }
  161. }
  162. ws.onclose = () => {
  163. console.log('Logs WebSocket closed, reconnecting...')
  164. // Reconnect after 3 seconds if drawer is still open
  165. reconnectTimeout = setTimeout(() => {
  166. if (logsWsRef.current === ws) {
  167. connectLogsWebSocket()
  168. }
  169. }, 3000)
  170. }
  171. ws.onerror = (error) => {
  172. console.error('Logs WebSocket error:', error)
  173. }
  174. logsWsRef.current = ws
  175. }
  176. connectLogsWebSocket()
  177. return () => {
  178. if (reconnectTimeout) {
  179. clearTimeout(reconnectTimeout)
  180. }
  181. if (logsWsRef.current) {
  182. logsWsRef.current.close()
  183. logsWsRef.current = null
  184. }
  185. }
  186. }, [isLogsOpen])
  187. const handleOpenLogs = () => {
  188. setIsLogsOpen(true)
  189. }
  190. // Filter logs by level
  191. const filteredLogs = logLevelFilter === 'ALL'
  192. ? logs
  193. : logs.filter((log) => log.level === logLevelFilter)
  194. // Format timestamp safely
  195. const formatTimestamp = (timestamp: string) => {
  196. if (!timestamp) return '--:--:--'
  197. try {
  198. const date = new Date(timestamp)
  199. if (isNaN(date.getTime())) return '--:--:--'
  200. return date.toLocaleTimeString()
  201. } catch {
  202. return '--:--:--'
  203. }
  204. }
  205. // Copy logs to clipboard
  206. const handleCopyLogs = () => {
  207. const text = filteredLogs
  208. .map((log) => `${formatTimestamp(log.timestamp)} [${log.level}] ${log.message}`)
  209. .join('\n')
  210. navigator.clipboard.writeText(text)
  211. toast.success('Logs copied to clipboard')
  212. }
  213. // Download logs as file
  214. const handleDownloadLogs = () => {
  215. const text = filteredLogs
  216. .map((log) => `${log.timestamp} [${log.level}] [${log.logger}] ${log.message}`)
  217. .join('\n')
  218. const blob = new Blob([text], { type: 'text/plain' })
  219. const url = URL.createObjectURL(blob)
  220. const a = document.createElement('a')
  221. a.href = url
  222. a.download = `dune-weaver-logs-${new Date().toISOString().split('T')[0]}.txt`
  223. a.click()
  224. URL.revokeObjectURL(url)
  225. }
  226. const handleRestart = async () => {
  227. if (!confirm('Are you sure you want to restart the system?')) return
  228. try {
  229. const response = await fetch('/restart', { method: 'POST' })
  230. if (response.ok) {
  231. toast.success('System is restarting...')
  232. } else {
  233. throw new Error('Restart failed')
  234. }
  235. } catch {
  236. toast.error('Failed to restart system')
  237. }
  238. }
  239. // Update document title based on current page
  240. useEffect(() => {
  241. const currentNav = navItems.find((item) => item.path === location.pathname)
  242. if (currentNav) {
  243. document.title = `${currentNav.title} | ${appName}`
  244. } else {
  245. document.title = appName
  246. }
  247. }, [location.pathname, appName])
  248. useEffect(() => {
  249. if (isDark) {
  250. document.documentElement.classList.add('dark')
  251. localStorage.setItem('theme', 'dark')
  252. } else {
  253. document.documentElement.classList.remove('dark')
  254. localStorage.setItem('theme', 'light')
  255. }
  256. }, [isDark])
  257. return (
  258. <div className="min-h-screen bg-background">
  259. {/* Header */}
  260. <header className="sticky top-0 z-40 w-full border-b border-border bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
  261. <div className="flex h-14 items-center justify-between px-4">
  262. <Link to="/" className="flex items-center gap-2">
  263. <img
  264. src={customLogo ? `/static/custom/${customLogo}` : '/static/android-chrome-192x192.png'}
  265. alt={appName}
  266. className="w-8 h-8 rounded-full object-cover"
  267. />
  268. <span className="font-semibold text-lg">{appName}</span>
  269. <span
  270. className={`w-2 h-2 rounded-full ${isConnected ? 'bg-green-500' : 'bg-red-500'}`}
  271. title={isConnected ? 'Connected' : 'Disconnected'}
  272. />
  273. </Link>
  274. <div className="flex items-center gap-1">
  275. <button
  276. onClick={() => setIsNowPlayingOpen(!isNowPlayingOpen)}
  277. className={`rounded-full w-10 h-10 flex items-center justify-center hover:bg-accent ${
  278. isNowPlayingOpen ? 'text-primary' : ''
  279. }`}
  280. aria-label="Now playing"
  281. title="Now Playing"
  282. >
  283. <span className="material-icons-outlined">play_circle</span>
  284. </button>
  285. <button
  286. onClick={handleOpenLogs}
  287. className="rounded-full w-10 h-10 flex items-center justify-center hover:bg-accent"
  288. aria-label="View logs"
  289. title="View Application Logs"
  290. >
  291. <span className="material-icons-outlined">article</span>
  292. </button>
  293. <button
  294. onClick={handleRestart}
  295. className="rounded-full w-10 h-10 flex items-center justify-center hover:bg-accent hover:text-amber-500"
  296. aria-label="Restart system"
  297. title="Restart System"
  298. >
  299. <span className="material-icons-outlined">restart_alt</span>
  300. </button>
  301. <button
  302. onClick={() => setIsDark(!isDark)}
  303. className="rounded-full w-10 h-10 flex items-center justify-center hover:bg-accent"
  304. aria-label="Toggle dark mode"
  305. >
  306. <span className="material-icons-outlined">
  307. {isDark ? 'light_mode' : 'dark_mode'}
  308. </span>
  309. </button>
  310. </div>
  311. </div>
  312. </header>
  313. {/* Main Content */}
  314. <main className={`container mx-auto px-4 transition-all duration-300 ${isLogsOpen ? 'pb-80' : 'pb-20'}`}>
  315. <Outlet />
  316. </main>
  317. {/* Now Playing Bar */}
  318. <NowPlayingBar
  319. isLogsOpen={isLogsOpen}
  320. isVisible={isNowPlayingOpen}
  321. onClose={() => setIsNowPlayingOpen(false)}
  322. />
  323. {/* Logs Drawer */}
  324. <div
  325. className={`fixed left-0 right-0 z-30 bg-background border-t border-border transition-all duration-300 ${
  326. isLogsOpen ? 'bottom-16 h-64' : 'bottom-16 h-0'
  327. }`}
  328. >
  329. {isLogsOpen && (
  330. <>
  331. <div className="flex items-center justify-between px-4 py-2 border-b bg-muted/50">
  332. <div className="flex items-center gap-3">
  333. <h2 className="text-sm font-semibold">Logs</h2>
  334. <select
  335. value={logLevelFilter}
  336. onChange={(e) => setLogLevelFilter(e.target.value)}
  337. className="text-xs bg-background border rounded px-2 py-1"
  338. >
  339. <option value="ALL">All Levels</option>
  340. <option value="DEBUG">Debug</option>
  341. <option value="INFO">Info</option>
  342. <option value="WARNING">Warning</option>
  343. <option value="ERROR">Error</option>
  344. </select>
  345. <span className="text-xs text-muted-foreground">
  346. {filteredLogs.length} entries
  347. </span>
  348. </div>
  349. <div className="flex items-center gap-1">
  350. <button
  351. onClick={handleCopyLogs}
  352. className="rounded-full w-7 h-7 flex items-center justify-center hover:bg-accent"
  353. title="Copy logs"
  354. >
  355. <span className="material-icons-outlined text-base">content_copy</span>
  356. </button>
  357. <button
  358. onClick={handleDownloadLogs}
  359. className="rounded-full w-7 h-7 flex items-center justify-center hover:bg-accent"
  360. title="Download logs"
  361. >
  362. <span className="material-icons-outlined text-base">download</span>
  363. </button>
  364. <button
  365. onClick={() => setIsLogsOpen(false)}
  366. className="rounded-full w-7 h-7 flex items-center justify-center hover:bg-accent"
  367. title="Close logs"
  368. >
  369. <span className="material-icons-outlined text-base">close</span>
  370. </button>
  371. </div>
  372. </div>
  373. <div
  374. ref={logsContainerRef}
  375. className="h-[calc(100%-40px)] overflow-auto overscroll-contain p-3 font-mono text-xs space-y-0.5"
  376. >
  377. {filteredLogs.length > 0 ? (
  378. filteredLogs.map((log, i) => (
  379. <div key={i} className="py-0.5 flex gap-2">
  380. <span className="text-muted-foreground shrink-0">
  381. {formatTimestamp(log.timestamp)}
  382. </span>
  383. <span className={`shrink-0 font-semibold ${
  384. log.level === 'ERROR' ? 'text-red-500' :
  385. log.level === 'WARNING' ? 'text-amber-500' :
  386. log.level === 'DEBUG' ? 'text-muted-foreground' :
  387. 'text-foreground'
  388. }`}>
  389. [{log.level || 'LOG'}]
  390. </span>
  391. <span className="break-all">{log.message || ''}</span>
  392. </div>
  393. ))
  394. ) : (
  395. <p className="text-muted-foreground text-center py-4">No logs available</p>
  396. )}
  397. </div>
  398. </>
  399. )}
  400. </div>
  401. {/* Bottom Navigation */}
  402. <nav className="fixed bottom-0 left-0 right-0 z-40 border-t border-border bg-background">
  403. <div className="max-w-5xl mx-auto grid grid-cols-5 h-16">
  404. {navItems.map((item) => {
  405. const isActive = location.pathname === item.path
  406. return (
  407. <Link
  408. key={item.path}
  409. to={item.path}
  410. className={`flex flex-col items-center justify-center gap-1 transition-colors ${
  411. isActive
  412. ? 'text-primary'
  413. : 'text-muted-foreground hover:text-foreground'
  414. }`}
  415. >
  416. <span className="material-icons-outlined text-xl">
  417. {item.icon}
  418. </span>
  419. <span className="text-xs font-medium">{item.label}</span>
  420. </Link>
  421. )
  422. })}
  423. </div>
  424. </nav>
  425. </div>
  426. )
  427. }