App.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. import { Component, Suspense, type ReactNode, type ErrorInfo } from 'react';
  2. import { BrowserRouter, Routes, Route, Navigate, useLocation } from 'react-router-dom';
  3. import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
  4. import { Layout } from './components/Layout';
  5. import { useWebSocket } from './hooks/useWebSocket';
  6. import { usePrintProgressTitle } from './hooks/usePrintProgressTitle';
  7. import { useStreamTokenSync } from './hooks/useCameraStreamToken';
  8. import { ThemeProvider } from './contexts/ThemeContext';
  9. import { ToastProvider } from './contexts/ToastContext';
  10. import { SliceJobTrackerProvider } from './contexts/SliceJobTrackerContext';
  11. import { AuthProvider, useAuth } from './contexts/AuthContext';
  12. import { ColorCatalogProvider } from './contexts/ColorCatalogContext';
  13. import { SpoolBuddyLayout } from './components/spoolbuddy/SpoolBuddyLayout';
  14. import { PageLoading } from './components/PageLoading';
  15. import { lazyPage } from './utils/lazyPage';
  16. // Every page loads as its own file when first opened (#3175).
  17. const PrintersPage = lazyPage(() => import('./pages/PrintersPage'), 'PrintersPage');
  18. const ArchivesPage = lazyPage(() => import('./pages/ArchivesPage'), 'ArchivesPage');
  19. const QueuePage = lazyPage(() => import('./pages/QueuePage'), 'QueuePage');
  20. const StatsPage = lazyPage(() => import('./pages/StatsPage'), 'StatsPage');
  21. const SettingsPage = lazyPage(() => import('./pages/SettingsPage'), 'SettingsPage');
  22. const FinancePage = lazyPage(() => import('./pages/FinancePage'), 'FinancePage');
  23. const ProfilesPage = lazyPage(() => import('./pages/ProfilesPage'), 'ProfilesPage');
  24. const MaintenancePage = lazyPage(() => import('./pages/MaintenancePage'), 'MaintenancePage');
  25. const ProjectsPage = lazyPage(() => import('./pages/ProjectsPage'), 'ProjectsPage');
  26. const ProjectDetailPage = lazyPage(() => import('./pages/ProjectDetailPage'), 'ProjectDetailPage');
  27. const FileManagerPage = lazyPage(() => import('./pages/FileManagerPage'), 'FileManagerPage');
  28. const LibraryTrashPage = lazyPage(() => import('./pages/LibraryTrashPage'), 'LibraryTrashPage');
  29. const CameraPage = lazyPage(() => import('./pages/CameraPage'), 'CameraPage');
  30. const CamWallPage = lazyPage(() => import('./pages/CamWallPage'), 'CamWallPage');
  31. const StreamOverlayPage = lazyPage(() => import('./pages/StreamOverlayPage'), 'StreamOverlayPage');
  32. const ExternalLinkPage = lazyPage(() => import('./pages/ExternalLinkPage'), 'ExternalLinkPage');
  33. const GroupEditPage = lazyPage(() => import('./pages/GroupEditPage'), 'GroupEditPage');
  34. const PrinterLocationsPage = lazyPage(() => import('./pages/PrinterLocationsPage'), 'PrinterLocationsPage');
  35. const InventoryPage = lazyPage(() => import('./pages/InventoryPage'), 'default');
  36. const ModelSourcesPage = lazyPage(() => import('./pages/ModelSourcesPage'), 'ModelSourcesPage');
  37. const SystemInfoPage = lazyPage(() => import('./pages/SystemInfoPage'), 'SystemInfoPage');
  38. const LoginPage = lazyPage(() => import('./pages/LoginPage'), 'LoginPage');
  39. const ConnectAuthorizePage = lazyPage(() => import('./pages/ConnectAuthorizePage'), 'ConnectAuthorizePage');
  40. const SetupPage = lazyPage(() => import('./pages/SetupPage'), 'SetupPage');
  41. const NotificationsPage = lazyPage(() => import('./pages/NotificationsPage'), 'NotificationsPage');
  42. const GCodeViewerPage = lazyPage(() => import('./pages/GCodeViewerPage'), 'GCodeViewerPage');
  43. const SpoolBuddyDashboard = lazyPage(() => import('./pages/spoolbuddy/SpoolBuddyDashboard'), 'SpoolBuddyDashboard');
  44. const SpoolBuddyAmsPage = lazyPage(() => import('./pages/spoolbuddy/SpoolBuddyAmsPage'), 'SpoolBuddyAmsPage');
  45. const SpoolBuddySettingsPage = lazyPage(() => import('./pages/spoolbuddy/SpoolBuddySettingsPage'), 'SpoolBuddySettingsPage');
  46. const SpoolBuddyWriteTagPage = lazyPage(() => import('./pages/spoolbuddy/SpoolBuddyWriteTagPage'), 'SpoolBuddyWriteTagPage');
  47. const SpoolBuddyInventoryPage = lazyPage(() => import('./pages/spoolbuddy/SpoolBuddyInventoryPage'), 'SpoolBuddyInventoryPage');
  48. class ErrorBoundary extends Component<{ children: ReactNode }, { error: Error | null; errorInfo: ErrorInfo | null }> {
  49. state = { error: null as Error | null, errorInfo: null as ErrorInfo | null };
  50. static getDerivedStateFromError(error: Error) {
  51. return { error };
  52. }
  53. componentDidCatch(error: Error, errorInfo: ErrorInfo) {
  54. this.setState({ errorInfo });
  55. console.error('React crash:', error, errorInfo);
  56. }
  57. render() {
  58. if (this.state.error) {
  59. return (
  60. <div style={{ padding: 24, color: '#ef4444', backgroundColor: '#18181b', minHeight: '100vh', fontFamily: 'monospace' }}>
  61. <h1 style={{ fontSize: 20, marginBottom: 12 }}>UI Crash</h1>
  62. <pre style={{ whiteSpace: 'pre-wrap', fontSize: 14 }}>{this.state.error.message}</pre>
  63. <pre style={{ whiteSpace: 'pre-wrap', fontSize: 12, color: '#a1a1aa', marginTop: 12 }}>
  64. {this.state.error.stack}
  65. </pre>
  66. <button
  67. onClick={() => { this.setState({ error: null, errorInfo: null }); }}
  68. style={{ marginTop: 16, padding: '8px 16px', backgroundColor: '#3b82f6', color: '#fff', border: 'none', borderRadius: 8, cursor: 'pointer' }}
  69. >
  70. Retry
  71. </button>
  72. </div>
  73. );
  74. }
  75. return this.props.children;
  76. }
  77. }
  78. const queryClient = new QueryClient({
  79. defaultOptions: {
  80. queries: {
  81. staleTime: 1000 * 60,
  82. retry: 1,
  83. },
  84. },
  85. });
  86. function StreamTokenSync() {
  87. useStreamTokenSync();
  88. return null;
  89. }
  90. function WebSocketProvider({ children }: { children: React.ReactNode }) {
  91. useWebSocket();
  92. usePrintProgressTitle();
  93. return <>{children}</>;
  94. }
  95. function ProtectedRoute({ children }: { children: React.ReactNode }) {
  96. const { authEnabled, loading, user } = useAuth();
  97. const location = useLocation();
  98. if (loading) {
  99. return <div className="min-h-screen flex items-center justify-center">Loading...</div>;
  100. }
  101. if (authEnabled && !user) {
  102. return <Navigate to="/login" replace state={{ from: location }} />;
  103. }
  104. return <>{children}</>;
  105. }
  106. function PermissionRoute({ permission, children }: { permission: string | string[]; children: React.ReactNode }) {
  107. // Permission-gated route: any user with the given permission can enter, not
  108. // just admins. Individual components below this guard apply their own
  109. // per-action permission checks. Used for pages where delegation is supported
  110. // (e.g. settings:read grants read-only access to Settings; specific tabs
  111. // require their own permissions like users:read, groups:update, etc.).
  112. const { authEnabled, loading, user, hasPermission } = useAuth();
  113. const location = useLocation();
  114. if (loading) {
  115. return <div className="min-h-screen flex items-center justify-center">Loading...</div>;
  116. }
  117. // Auth disabled → open access (backward compatibility)
  118. if (!authEnabled) {
  119. return <>{children}</>;
  120. }
  121. if (!user) {
  122. return <Navigate to="/login" replace state={{ from: location }} />;
  123. }
  124. // A list lets in anyone holding at least one of the permissions.
  125. const required = (Array.isArray(permission) ? permission : [permission]) as Parameters<typeof hasPermission>[0][];
  126. if (!required.some((p) => hasPermission(p))) {
  127. return <Navigate to="/" replace />;
  128. }
  129. return <>{children}</>;
  130. }
  131. function SetupRoute({ children }: { children: React.ReactNode }) {
  132. const { authEnabled, loading } = useAuth();
  133. if (loading) {
  134. return <div className="min-h-screen flex items-center justify-center">Loading...</div>;
  135. }
  136. // If auth is already enabled, redirect to login
  137. // Otherwise, allow access to setup page (even if setup was completed before)
  138. // This allows users to enable auth later if they skipped it during initial setup
  139. if (authEnabled) {
  140. return <Navigate to="/login" replace />;
  141. }
  142. return <>{children}</>;
  143. }
  144. function App() {
  145. return (
  146. <ErrorBoundary>
  147. <ToastProvider>
  148. <QueryClientProvider client={queryClient}>
  149. <AuthProvider>
  150. {/* ThemeProvider sits inside AuthProvider so its initial
  151. ``api.getSettings()`` fetch can wait for AuthContext to
  152. resolve — otherwise it fires unconditionally on every
  153. login page load and returns 401. ErrorBoundary uses
  154. inline styles, so a missing theme on a crash screen is
  155. not a regression. */}
  156. <ThemeProvider>
  157. <ColorCatalogProvider>
  158. <SliceJobTrackerProvider>
  159. <StreamTokenSync />
  160. <BrowserRouter>
  161. {/* Standalone pages (login, camera, overlay, ...) wait here; pages
  162. inside a layout wait in that layout, so its frame stays up. */}
  163. <Suspense fallback={<PageLoading fullScreen />}>
  164. <Routes>
  165. {/* Setup page - only accessible if auth not enabled */}
  166. <Route path="/setup" element={<SetupRoute><SetupPage /></SetupRoute>} />
  167. {/* Login page */}
  168. <Route path="/login" element={<LoginPage />} />
  169. {/* "Sign in with Bambuddy" for connected apps: standalone, no layout,
  170. so it also fits inside the sidebar iframe of the app asking. */}
  171. <Route path="/connect/authorize" element={<ProtectedRoute><ConnectAuthorizePage /></ProtectedRoute>} />
  172. {/* Camera page - standalone, no layout, no WebSocket (doesn't need real-time updates) */}
  173. <Route path="/camera/:printerId" element={<CameraPage />} />
  174. {/* Stream overlay page - standalone for OBS/streaming embeds, no auth required */}
  175. <Route path="/overlay/:printerId" element={<StreamOverlayPage />} />
  176. {/* Cam Wall on its own URL (#2531). Outside ProtectedRoute because a
  177. ?token= kiosk has no session to protect; the page itself sends a
  178. tokenless visitor to /login, and the backend gates the feed. */}
  179. <Route path="/camwall" element={<CamWallPage />} />
  180. {/* SpoolBuddy kiosk UI */}
  181. <Route element={<ProtectedRoute><WebSocketProvider><SpoolBuddyLayout /></WebSocketProvider></ProtectedRoute>}>
  182. <Route path="spoolbuddy" element={<SpoolBuddyDashboard />} />
  183. <Route path="spoolbuddy/ams" element={<SpoolBuddyAmsPage />} />
  184. <Route path="spoolbuddy/write-tag" element={<SpoolBuddyWriteTagPage />} />
  185. <Route path="spoolbuddy/inventory" element={<SpoolBuddyInventoryPage />} />
  186. <Route path="spoolbuddy/settings" element={<SpoolBuddySettingsPage />} />
  187. {/* Calibration moved into the settings page; old bookmarks land there. */}
  188. <Route path="spoolbuddy/calibration" element={<Navigate to="/spoolbuddy/settings" replace />} />
  189. </Route>
  190. {/* Main app with WebSocket for real-time updates */}
  191. <Route element={<ProtectedRoute><WebSocketProvider><Layout /></WebSocketProvider></ProtectedRoute>}>
  192. <Route index element={<PrintersPage />} />
  193. <Route path="archives" element={<ArchivesPage />} />
  194. <Route path="queue" element={<QueuePage />} />
  195. {/* Slicer Pipelines (#1425) — Pipelines tab lives on the
  196. Print Queue page (Queue + History + Timeline +
  197. Pipelines). Old standalone URL redirects. */}
  198. <Route path="pipelines/runs" element={<Navigate to="/queue?tab=pipelines" replace />} />
  199. <Route path="stats" element={<StatsPage />} />
  200. <Route path="profiles" element={<ProfilesPage />} />
  201. <Route path="finance" element={<PermissionRoute permission="cost_centers:read_own"><FinancePage /></PermissionRoute>} />
  202. <Route path="maintenance" element={<MaintenancePage />} />
  203. <Route path="projects" element={<ProjectsPage />} />
  204. <Route path="projects/:id" element={<ProjectDetailPage />} />
  205. <Route path="inventory" element={<InventoryPage />} />
  206. <Route path="files" element={<FileManagerPage />} />
  207. <Route path="files/trash" element={<LibraryTrashPage />} />
  208. <Route path="model-sources" element={<PermissionRoute permission={['makerworld:view', 'manyfold:view']}><ModelSourcesPage /></PermissionRoute>} />
  209. {/* The page was MakerWorld-only until Manyfold joined it (#1471); old links and bookmarks still land on that tab. */}
  210. <Route path="makerworld" element={<Navigate to="/model-sources?tab=makerworld" replace />} />
  211. <Route path="settings" element={<PermissionRoute permission="settings:read"><SettingsPage /></PermissionRoute>} />
  212. <Route path="groups/new" element={<PermissionRoute permission="groups:create"><GroupEditPage /></PermissionRoute>} />
  213. <Route path="groups/:id/edit" element={<PermissionRoute permission="groups:update"><GroupEditPage /></PermissionRoute>} />
  214. <Route path="printer-locations" element={<PermissionRoute permission="printers:read"><PrinterLocationsPage /></PermissionRoute>} />
  215. <Route path="users" element={<Navigate to="/settings?tab=users" replace />} />
  216. <Route path="groups" element={<Navigate to="/settings?tab=users" replace />} />
  217. <Route path="system" element={<SystemInfoPage />} />
  218. <Route path="notifications" element={<NotificationsPage />} />
  219. <Route path="gcode-viewer" element={<GCodeViewerPage />} />
  220. <Route path="external/:id" element={<ExternalLinkPage />} />
  221. <Route path="camera-tokens" element={<Navigate to="/settings?tab=camera#card-camera-tokens" replace />} />
  222. </Route>
  223. </Routes>
  224. </Suspense>
  225. </BrowserRouter>
  226. </SliceJobTrackerProvider>
  227. </ColorCatalogProvider>
  228. </ThemeProvider>
  229. </AuthProvider>
  230. </QueryClientProvider>
  231. </ToastProvider>
  232. </ErrorBoundary>
  233. );
  234. }
  235. export default App;