App.tsx 15 KB

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