Files
slp-modular-cms/frontend/src/main.tsx
T

86 lines
3.1 KiB
TypeScript

import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { RouterProvider } from '@tanstack/react-router';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import './index.css';
// Per-site admin theme chosen at build time (VITE_THEME); an empty file when none is selected.
import '@theme';
import './i18n/config';
import { AuthProvider } from '@/features/auth/context/AuthProvider';
import { useAuth } from '@/features/auth/context/auth-context';
import { SessionUnreachable } from '@/features/auth/components/SessionUnreachable';
import { Toaster } from '@/components/ui/sonner';
import { router } from '@/router';
import { getAppConfig } from '@/lib/config';
import { initSentry } from '@/lib/sentry';
import { SentryErrorBoundary } from '@/components/SentryErrorBoundary';
import { UmamiAnalytics } from '@/components/UmamiAnalytics';
// First, before the query client and before render, so an error during startup is still captured.
// A no-op when no DSN is configured.
initSentry();
document.title = getAppConfig().appTitle;
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: 1, refetchOnWindowFocus: true },
},
});
function BootstrapSplash() {
return (
<div className="flex min-h-svh items-center justify-center text-muted-foreground">
<span className="h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent" />
</div>
);
}
/**
* Renders the router only once the initial silent refresh has settled, so the
* route guards see a definitive auth state rather than the transient loading one.
*/
function InnerApp() {
const auth = useAuth();
if (auth.status === 'loading') {
return <BootstrapSplash />;
}
if (auth.status === 'unreachable') {
return <SessionUnreachable />;
}
return <RouterProvider router={router} context={{ auth }} />;
}
async function enableMocking(): Promise<void> {
if (import.meta.env.VITE_ENABLE_MSW !== 'true') {
return;
}
const { worker } = await import('@/mocks/browser');
await worker.start({ onUnhandledRequest: 'bypass' });
}
void enableMocking().then(() => {
const rootElement = document.getElementById('root');
if (rootElement === null) {
throw new Error('Root element #root not found');
}
createRoot(rootElement).render(
<StrictMode>
<QueryClientProvider client={queryClient}>
<AuthProvider>
{/*
* Inside AuthProvider, not outermost: the fallback has to be reachable for a
* logged-in user, and a render error inside a page must not tear down the
* session context — otherwise recovering would also log the user out.
*/}
<SentryErrorBoundary>
<InnerApp />
<UmamiAnalytics />
</SentryErrorBoundary>
<Toaster />
</AuthProvider>
</QueryClientProvider>
</StrictMode>,
);
});