Files
electro4ort/apps/web/src/routes/app/route.tsx
T
olehhapuk 98b2e0ce4b
CI / Lint, types, build, tests (push) Canceled after 0s
CI / Docker images build (push) Canceled after 0s
update
2026-12-03 10:53:09 +02:00

206 lines
7.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useState } from 'react';
import {
useQuery,
useQueryClient,
useSuspenseQuery,
} from '@tanstack/react-query';
import {
Link,
Outlet,
createFileRoute,
redirect,
useNavigate,
useRouter,
} from '@tanstack/react-router';
import type { ErrorComponentProps } from '@tanstack/react-router';
import { LogOut, UserRound, Users } from 'lucide-react';
import { Badge } from '@repo/ui/components/badge';
import { Button } from '@repo/ui/components/button';
import { Spinner } from '@repo/ui/components/spinner';
import { Brand } from '@/components/brand';
import { CallPanel } from '@/components/call-panel';
import { CallProvider } from '@/components/call-provider';
import { ConversationList } from '@/components/conversation-list';
import { IncomingCalls } from '@/components/incoming-calls';
import { NewGroupDialog } from '@/components/new-group-dialog';
import { NewRealmDialog } from '@/components/new-realm-dialog';
import { RealmList } from '@/components/realm-list';
import { UnreadDot } from '@/components/unread-dot';
import { UserAvatar } from '@/components/user-avatar';
import { ApiError } from '@/lib/api';
import { authClient } from '@/lib/auth-client';
import { callsQuery } from '@/lib/calls';
import { friendsQuery } from '@/lib/friends';
import { ownProfileQuery } from '@/lib/profile';
import { useRealtime } from '@/lib/realtime';
import { useUnreadSummary, useUnreadTitle } from '@/lib/unread';
const SETTINGS_PATH = '/app/settings';
export const Route = createFileRoute('/app')({
// Everything under /app is private and personal, so it renders in the
// browser only; the server never needs the visitor's session.
ssr: false,
beforeLoad: async ({ context, location }) => {
let profile;
try {
profile = await context.queryClient.fetchQuery(ownProfileQuery);
} catch (error) {
if (error instanceof ApiError && error.status === 401) {
throw redirect({ to: '/login', search: { redirect: location.href } });
}
throw error;
}
// Friends find each other by username, so nothing else opens without one.
if (profile.username === null && location.pathname !== SETTINGS_PATH) {
throw redirect({ to: SETTINGS_PATH });
}
},
pendingComponent: AppPending,
errorComponent: AppError,
component: AppLayout,
});
const navItems = [
{ to: '/app/friends', label: 'Friends', icon: Users },
{ to: SETTINGS_PATH, label: 'Profile', icon: UserRound },
] as const;
function AppLayout() {
const { data: profile } = useSuspenseQuery(ownProfileQuery);
const { data: friends } = useQuery(friendsQuery);
// Loaded up front: only calls that start after this are offered to join.
useQuery(callsQuery);
const queryClient = useQueryClient();
useRealtime();
useUnreadTitle();
const unread = useUnreadSummary();
const requestCount = friends?.incoming.length ?? 0;
const navigate = useNavigate();
const [isSigningOut, setIsSigningOut] = useState(false);
async function handleSignOut() {
setIsSigningOut(true);
await authClient.signOut();
await navigate({ to: '/' });
// After leaving, so nothing here refetches as a signed-out visitor.
queryClient.clear();
}
return (
<CallProvider>
<div className="flex h-svh flex-col md:flex-row">
<aside className="flex min-h-0 shrink-0 items-center gap-3 border-b px-4 py-2 md:w-64 md:flex-col md:items-stretch md:border-r md:border-b-0 md:px-3 md:py-4">
<Link to="/app" className="relative md:px-2 md:pb-2">
<Brand />
{/* Phones show no lists beside a chat, so the way back says it. */}
{unread.any && (
<UnreadDot
label="Unread messages"
className="absolute -top-0.5 -right-2.5 md:hidden"
/>
)}
</Link>
<nav className="flex flex-1 gap-1 md:flex-none md:flex-col">
{navItems.map((item) => (
<Link
key={item.to}
to={item.to}
aria-label={item.label}
className="flex items-center gap-2 rounded-lg px-2 py-1.5 text-sm text-muted-foreground hover:bg-muted hover:text-foreground data-[status=active]:bg-muted data-[status=active]:font-medium data-[status=active]:text-foreground"
>
<item.icon className="size-4" aria-hidden="true" />
<span className="hidden sm:inline">{item.label}</span>
{item.to === '/app/friends' && requestCount > 0 && (
<Badge
className="md:ml-auto"
aria-label={`${requestCount} friend requests`}
>
{requestCount}
</Badge>
)}
</Link>
))}
</nav>
{/* On phones the list is on the /app page instead. */}
<div className="hidden min-h-0 flex-1 flex-col gap-1 overflow-y-auto md:flex">
<div className="flex items-center justify-between pt-2 pl-2">
<h2 className="text-xs font-medium text-muted-foreground">
Realms
</h2>
<NewRealmDialog />
</div>
<RealmList />
<div className="flex items-center justify-between pt-2 pl-2">
<h2 className="text-xs font-medium text-muted-foreground">
Messages
</h2>
<NewGroupDialog />
</div>
<ConversationList ownId={profile.id} />
</div>
<div className="flex items-center gap-2 md:px-1">
<UserAvatar user={profile} />
<div className="hidden min-w-0 flex-1 md:block">
<p className="truncate text-sm font-medium">{profile.name}</p>
{profile.username && (
<p className="truncate text-xs text-muted-foreground">
@{profile.username}
</p>
)}
</div>
<Button
variant="ghost"
size="icon"
aria-label="Sign out"
title="Sign out"
onClick={handleSignOut}
disabled={isSigningOut}
>
{isSigningOut ? <Spinner /> : <LogOut aria-hidden="true" />}
</Button>
</div>
</aside>
<div className="flex min-h-0 min-w-0 flex-1 flex-col">
<CallPanel />
{/* Each page scrolls by itself, so the chat can keep its composer in view. */}
<main className="flex min-h-0 min-w-0 flex-1 flex-col overflow-y-auto">
<Outlet />
</main>
</div>
</div>
<IncomingCalls ownId={profile.id} />
</CallProvider>
);
}
function AppPending() {
return (
<div className="flex min-h-svh items-center justify-center">
<Spinner className="size-6" aria-label="Loading" />
</div>
);
}
function AppError({ error }: ErrorComponentProps) {
const router = useRouter();
return (
<div className="flex min-h-svh flex-col items-center justify-center gap-3 p-6 text-center">
<h1 className="font-heading text-xl font-semibold">
Couldn&apos;t load the app
</h1>
<p className="max-w-sm text-sm text-muted-foreground">
{error instanceof ApiError
? error.message
: 'The server didn’t answer. Check your connection and try again.'}
</p>
<Button onClick={() => router.invalidate()}>Try again</Button>
</div>
);
}