update
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
# URL of the API (apps/api).
|
||||
VITE_API_URL=http://localhost:3001
|
||||
@@ -8,20 +8,29 @@
|
||||
"generate-routes": "tsr generate",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview",
|
||||
"start": "srvx --prod -s ../client dist/server/server.js",
|
||||
"lint": "oxlint",
|
||||
"format": "prettier --write \"**/*.{ts,tsx}\"",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@livekit/components-react": "^2.9.26",
|
||||
"@repo/contracts": "workspace:*",
|
||||
"@repo/ui": "workspace:*",
|
||||
"@tailwindcss/vite": "^4",
|
||||
"@tanstack/react-devtools": "latest",
|
||||
"@tanstack/react-query": "^5.108.4",
|
||||
"@tanstack/react-router": "latest",
|
||||
"@tanstack/react-router-devtools": "latest",
|
||||
"@tanstack/react-router-ssr-query": "^1.167.3",
|
||||
"@tanstack/react-start": "latest",
|
||||
"better-auth": "^1.7.29",
|
||||
"livekit-client": "^2.26.0",
|
||||
"lucide-react": "^1.84.0",
|
||||
"react": "^19.3.1",
|
||||
"react-dom": "^19.3.1",
|
||||
"socket.io-client": "^4.8.4",
|
||||
"srvx": "^1.0.6",
|
||||
"tailwindcss": "^4"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Link, useNavigate } from '@tanstack/react-router';
|
||||
import {
|
||||
NAME_MAX_LENGTH,
|
||||
USERNAME_MAX_LENGTH,
|
||||
USERNAME_MIN_LENGTH,
|
||||
usernameSchema,
|
||||
} from '@repo/contracts';
|
||||
import { Alert, AlertDescription } from '@repo/ui/components/alert';
|
||||
import { Button } from '@repo/ui/components/button';
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '@repo/ui/components/card';
|
||||
import {
|
||||
Field,
|
||||
FieldDescription,
|
||||
FieldGroup,
|
||||
FieldLabel,
|
||||
} from '@repo/ui/components/field';
|
||||
import { Input } from '@repo/ui/components/input';
|
||||
import { Spinner } from '@repo/ui/components/spinner';
|
||||
import { authClient } from '@/lib/auth-client';
|
||||
import { DEFAULT_SIGNED_IN_PATH, toSitePath } from '@/lib/redirect';
|
||||
|
||||
const MIN_PASSWORD_LENGTH = 8;
|
||||
|
||||
const copy = {
|
||||
login: {
|
||||
title: 'Log in',
|
||||
description: 'Enter your email and password to continue.',
|
||||
submit: 'Log in',
|
||||
fallbackError: 'Could not log in. Please try again.',
|
||||
},
|
||||
register: {
|
||||
title: 'Create an account',
|
||||
description: 'Enter your details to get started.',
|
||||
submit: 'Create account',
|
||||
fallbackError: 'Could not create the account. Please try again.',
|
||||
},
|
||||
};
|
||||
|
||||
interface AuthFormProps {
|
||||
mode: 'login' | 'register';
|
||||
/** A path on this site to open after signing in. */
|
||||
redirectTo?: string;
|
||||
}
|
||||
|
||||
export function AuthForm({ mode, redirectTo: requested }: AuthFormProps) {
|
||||
// Checked again here, so no caller can pass an off-site address through.
|
||||
const redirectTo = toSitePath(requested) ?? DEFAULT_SIGNED_IN_PATH;
|
||||
const navigate = useNavigate();
|
||||
const { data: session } = authClient.useSession();
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const text = copy[mode];
|
||||
// Keeps the return path when switching between the two forms.
|
||||
const linkSearch = { redirect: toSitePath(requested) };
|
||||
|
||||
// Already signed in (or just signed in): there is nothing to do here.
|
||||
const isSignedIn = Boolean(session);
|
||||
useEffect(() => {
|
||||
if (isSignedIn) void navigate({ href: redirectTo, replace: true });
|
||||
}, [isSignedIn, navigate, redirectTo]);
|
||||
if (isSignedIn) return null;
|
||||
|
||||
async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
const form = new FormData(event.currentTarget);
|
||||
const field = (name: string) => {
|
||||
const value = form.get(name);
|
||||
return typeof value === 'string' ? value : '';
|
||||
};
|
||||
const email = field('email');
|
||||
const password = field('password');
|
||||
|
||||
let username = '';
|
||||
if (mode === 'register') {
|
||||
const parsed = usernameSchema.safeParse(field('username'));
|
||||
if (!parsed.success) {
|
||||
setError(parsed.error.issues[0]?.message ?? text.fallbackError);
|
||||
return;
|
||||
}
|
||||
username = parsed.data;
|
||||
}
|
||||
|
||||
setError(null);
|
||||
setIsSubmitting(true);
|
||||
const result =
|
||||
mode === 'login'
|
||||
? await authClient.signIn.email({ email, password })
|
||||
: await authClient.signUp.email({
|
||||
name: field('name'),
|
||||
username,
|
||||
email,
|
||||
password,
|
||||
});
|
||||
|
||||
if (result.error) {
|
||||
setError(result.error.message ?? text.fallbackError);
|
||||
setIsSubmitting(false);
|
||||
return;
|
||||
}
|
||||
await navigate({ href: redirectTo, replace: true });
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="flex min-h-svh items-center justify-center p-6">
|
||||
<Card className="w-full max-w-sm">
|
||||
<CardHeader>
|
||||
<CardTitle>{text.title}</CardTitle>
|
||||
<CardDescription>{text.description}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<FieldGroup>
|
||||
{mode === 'register' && (
|
||||
<>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="name">Name</FieldLabel>
|
||||
<Input
|
||||
id="name"
|
||||
name="name"
|
||||
autoComplete="name"
|
||||
maxLength={NAME_MAX_LENGTH}
|
||||
required
|
||||
/>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="username">Username</FieldLabel>
|
||||
<Input
|
||||
id="username"
|
||||
name="username"
|
||||
autoComplete="username"
|
||||
autoCapitalize="none"
|
||||
spellCheck={false}
|
||||
minLength={USERNAME_MIN_LENGTH}
|
||||
maxLength={USERNAME_MAX_LENGTH}
|
||||
required
|
||||
/>
|
||||
<FieldDescription>
|
||||
How friends find you. Letters, numbers, underscores and
|
||||
dots.
|
||||
</FieldDescription>
|
||||
</Field>
|
||||
</>
|
||||
)}
|
||||
<Field>
|
||||
<FieldLabel htmlFor="email">Email</FieldLabel>
|
||||
<Input
|
||||
id="email"
|
||||
name="email"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
required
|
||||
/>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="password">Password</FieldLabel>
|
||||
<Input
|
||||
id="password"
|
||||
name="password"
|
||||
type="password"
|
||||
autoComplete={
|
||||
mode === 'login' ? 'current-password' : 'new-password'
|
||||
}
|
||||
minLength={
|
||||
mode === 'register' ? MIN_PASSWORD_LENGTH : undefined
|
||||
}
|
||||
required
|
||||
/>
|
||||
{mode === 'register' && (
|
||||
<FieldDescription>
|
||||
At least {MIN_PASSWORD_LENGTH} characters.
|
||||
</FieldDescription>
|
||||
)}
|
||||
</Field>
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
<Field>
|
||||
<Button type="submit" disabled={isSubmitting}>
|
||||
{isSubmitting && <Spinner />}
|
||||
{text.submit}
|
||||
</Button>
|
||||
<FieldDescription className="text-center">
|
||||
{mode === 'login' ? (
|
||||
<>
|
||||
Don't have an account?{' '}
|
||||
<Link to="/register" search={linkSearch}>
|
||||
Register
|
||||
</Link>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
Already have an account?{' '}
|
||||
<Link to="/login" search={linkSearch}>
|
||||
Log in
|
||||
</Link>
|
||||
</>
|
||||
)}
|
||||
</FieldDescription>
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import { useState } from 'react';
|
||||
import { BAN_REASON_MAX_LENGTH } from '@repo/contracts';
|
||||
import type { UserSummary } from '@repo/contracts';
|
||||
import { Button } from '@repo/ui/components/button';
|
||||
import {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@repo/ui/components/dialog';
|
||||
import { Field, FieldDescription, FieldLabel } from '@repo/ui/components/field';
|
||||
import { Input } from '@repo/ui/components/input';
|
||||
import { Spinner } from '@repo/ui/components/spinner';
|
||||
import type { TriggerButtonProps } from '@/components/trigger-button';
|
||||
import { errorMessage } from '@/lib/errors';
|
||||
import { useBanMember } from '@/lib/realms';
|
||||
|
||||
interface BanDialogProps extends TriggerButtonProps {
|
||||
realmId: string;
|
||||
realmName: string;
|
||||
/** The member to ban. */
|
||||
user: UserSummary;
|
||||
}
|
||||
|
||||
/** A button that asks why, then bans a member from a realm. */
|
||||
export function BanDialog({
|
||||
realmId,
|
||||
realmName,
|
||||
user,
|
||||
children,
|
||||
...button
|
||||
}: BanDialogProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger render={<Button {...button} />}>{children}</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-sm">
|
||||
{/* Mounted only while open, so each opening starts empty. */}
|
||||
<BanForm
|
||||
realmId={realmId}
|
||||
realmName={realmName}
|
||||
user={user}
|
||||
onDone={() => setOpen(false)}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function BanForm({
|
||||
realmId,
|
||||
realmName,
|
||||
user,
|
||||
onDone,
|
||||
}: {
|
||||
realmId: string;
|
||||
realmName: string;
|
||||
user: UserSummary;
|
||||
onDone: () => void;
|
||||
}) {
|
||||
const ban = useBanMember(realmId);
|
||||
const [reason, setReason] = useState('');
|
||||
|
||||
return (
|
||||
<form
|
||||
className="grid gap-4"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
// The row this dialog hangs from goes once the ban is known, which
|
||||
// may be before the answer; closing first is harmless either way.
|
||||
ban.mutate({ userId: user.id, reason }, { onSuccess: onDone });
|
||||
}}
|
||||
>
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
Ban {user.name} from {realmName}?
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
They are removed and no invite link lets them back in until the ban is
|
||||
lifted. Their messages stay.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="ban-reason">Reason (optional)</FieldLabel>
|
||||
<Input
|
||||
id="ban-reason"
|
||||
value={reason}
|
||||
maxLength={BAN_REASON_MAX_LENGTH}
|
||||
autoComplete="off"
|
||||
onChange={(event) => setReason(event.target.value)}
|
||||
/>
|
||||
<FieldDescription>
|
||||
Shown to those who can manage bans, not to {user.name}.
|
||||
</FieldDescription>
|
||||
</Field>
|
||||
{ban.isError && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{errorMessage(ban.error)}
|
||||
</p>
|
||||
)}
|
||||
<DialogFooter>
|
||||
<DialogClose render={<Button type="button" variant="outline" />}>
|
||||
Cancel
|
||||
</DialogClose>
|
||||
<Button type="submit" variant="destructive" disabled={ban.isPending}>
|
||||
{ban.isPending && <Spinner />}
|
||||
Ban
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { Zap } from 'lucide-react';
|
||||
import { site } from '@/lib/site';
|
||||
|
||||
/** The logo mark and site name. */
|
||||
export function Brand() {
|
||||
return (
|
||||
<span className="flex items-center gap-2 font-heading text-base font-semibold">
|
||||
<span className="flex size-7 items-center justify-center rounded-lg bg-primary text-primary-foreground">
|
||||
<Zap className="size-4" aria-hidden="true" />
|
||||
</span>
|
||||
{site.name}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { Phone, PhoneOff } from 'lucide-react';
|
||||
import { Button } from '@repo/ui/components/button';
|
||||
import { useCalls } from '@/components/call-provider';
|
||||
import type { CallPlace } from '@/components/call-provider';
|
||||
import { UserAvatar } from '@/components/user-avatar';
|
||||
import { callSummary, useCallIn, useCallsEnabled } from '@/lib/calls';
|
||||
|
||||
/** How many faces of a call to show before "+2". */
|
||||
const MAX_FACES = 3;
|
||||
|
||||
interface CallButtonProps {
|
||||
place: CallPlace;
|
||||
/** Whether the user may start or join a call here. */
|
||||
canJoin: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* For a page's header: starts a call there, or shows who is in the one
|
||||
* going on and joins it. Renders nothing when the server has no calls.
|
||||
*/
|
||||
export function CallButton({ place, canJoin }: CallButtonProps) {
|
||||
const isEnabled = useCallsEnabled();
|
||||
const call = useCallIn(place.conversationId);
|
||||
const { active, join, leave } = useCalls();
|
||||
if (!isEnabled) return null;
|
||||
|
||||
if (active?.place.conversationId === place.conversationId) {
|
||||
return (
|
||||
<Button variant="outline" size="sm" onClick={leave}>
|
||||
<PhoneOff aria-hidden="true" />
|
||||
Leave call
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
if (!call) {
|
||||
if (!canJoin) return null;
|
||||
return (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
aria-label="Start a call"
|
||||
title="Start a call"
|
||||
onClick={() => join(place)}
|
||||
>
|
||||
<Phone aria-hidden="true" />
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
const faces = call.participants.slice(0, MAX_FACES);
|
||||
const more = call.participants.length - faces.length;
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<p className="sr-only">{callSummary(call)}</p>
|
||||
<div className="hidden items-center -space-x-1.5 sm:flex" aria-hidden>
|
||||
{faces.map((person) => (
|
||||
<UserAvatar
|
||||
key={person.id}
|
||||
user={person}
|
||||
size="sm"
|
||||
className="ring-2 ring-background"
|
||||
/>
|
||||
))}
|
||||
{more > 0 && (
|
||||
<span className="pl-2.5 text-xs text-muted-foreground">+{more}</span>
|
||||
)}
|
||||
</div>
|
||||
{canJoin && (
|
||||
<Button size="sm" onClick={() => join(place)}>
|
||||
<Phone aria-hidden="true" />
|
||||
Join call
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Phone } from 'lucide-react';
|
||||
import { cn } from '@repo/ui/lib/utils';
|
||||
|
||||
/** A small mark for "a call is going on here", for the lists. */
|
||||
export function CallMark({ className }: { className?: string }) {
|
||||
return (
|
||||
<span className={cn('shrink-0 text-primary', className)}>
|
||||
<Phone className="size-3.5" aria-hidden="true" />
|
||||
<span className="sr-only">Call going on</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,345 @@
|
||||
import { useState } from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Link } from '@tanstack/react-router';
|
||||
import {
|
||||
RoomAudioRenderer,
|
||||
RoomContext,
|
||||
StartAudio,
|
||||
VideoTrack,
|
||||
useIsMuted,
|
||||
useIsSpeaking,
|
||||
useLocalParticipant,
|
||||
useParticipantTracks,
|
||||
useParticipants,
|
||||
useTrackToggle,
|
||||
useTracks,
|
||||
} from '@livekit/components-react';
|
||||
import type { TrackReference } from '@livekit/components-react';
|
||||
import { Track } from 'livekit-client';
|
||||
import type { Participant } from 'livekit-client';
|
||||
import {
|
||||
Maximize2,
|
||||
Mic,
|
||||
MicOff,
|
||||
Minimize2,
|
||||
MonitorUp,
|
||||
MonitorX,
|
||||
Phone,
|
||||
PhoneOff,
|
||||
Video,
|
||||
VideoOff,
|
||||
} from 'lucide-react';
|
||||
import { Button, buttonVariants } from '@repo/ui/components/button';
|
||||
import { Spinner } from '@repo/ui/components/spinner';
|
||||
import { toast } from '@repo/ui/components/toast';
|
||||
import { cn } from '@repo/ui/lib/utils';
|
||||
import { useCalls } from '@/components/call-provider';
|
||||
import type { ActiveCall, CallPlace } from '@/components/call-provider';
|
||||
import { UserAvatar } from '@/components/user-avatar';
|
||||
import { callsQuery } from '@/lib/calls';
|
||||
|
||||
/**
|
||||
* The call the user is in, docked above whatever page they are on: who is
|
||||
* there, their video and shared screens, and the controls. Renders nothing
|
||||
* outside a call.
|
||||
*/
|
||||
export function CallPanel() {
|
||||
const { active, leave } = useCalls();
|
||||
const [isLarge, setIsLarge] = useState(false);
|
||||
if (!active) return null;
|
||||
|
||||
return (
|
||||
<section
|
||||
aria-label={`Call in ${active.place.title}`}
|
||||
className={cn(
|
||||
'flex shrink-0 flex-col gap-2 border-b bg-muted/40 p-2',
|
||||
isLarge && 'h-[70svh]',
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-2 pl-2">
|
||||
<Phone className="size-4 shrink-0 text-primary" aria-hidden="true" />
|
||||
<p className="min-w-0 flex-1 truncate text-sm">
|
||||
<PlaceLink place={active.place} />
|
||||
<span className="text-muted-foreground">
|
||||
{active.status === 'connecting' ? ' · Connecting…' : ' · In call'}
|
||||
</span>
|
||||
</p>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
aria-label={
|
||||
isLarge ? 'Make the call smaller' : 'Make the call larger'
|
||||
}
|
||||
title={isLarge ? 'Smaller' : 'Larger'}
|
||||
onClick={() => setIsLarge(!isLarge)}
|
||||
>
|
||||
{isLarge ? (
|
||||
<Minimize2 aria-hidden="true" />
|
||||
) : (
|
||||
<Maximize2 aria-hidden="true" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{active.status === 'connecting' ? (
|
||||
<div className="flex h-24 items-center justify-center">
|
||||
<Spinner className="size-5" aria-label="Connecting" />
|
||||
</div>
|
||||
) : (
|
||||
// The key: LiveKit's hooks keep what they learned from one room.
|
||||
<RoomContext value={active.room} key={active.place.conversationId}>
|
||||
<Stage call={active} isLarge={isLarge} />
|
||||
<RoomAudioRenderer />
|
||||
</RoomContext>
|
||||
)}
|
||||
|
||||
<div className="flex flex-wrap items-center justify-center gap-2">
|
||||
{active.status === 'connected' && (
|
||||
<RoomContext value={active.room}>
|
||||
<Controls />
|
||||
</RoomContext>
|
||||
)}
|
||||
<Button variant="destructive" size="sm" onClick={leave}>
|
||||
<PhoneOff aria-hidden="true" />
|
||||
Leave
|
||||
</Button>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function PlaceLink({ place }: { place: CallPlace }) {
|
||||
const className = 'font-medium hover:underline';
|
||||
return place.realmId ? (
|
||||
<Link
|
||||
to="/app/r/$realmId/$cauldronId"
|
||||
params={{ realmId: place.realmId, cauldronId: place.conversationId }}
|
||||
className={className}
|
||||
>
|
||||
{place.title}
|
||||
</Link>
|
||||
) : (
|
||||
<Link
|
||||
to="/app/c/$conversationId"
|
||||
params={{ conversationId: place.conversationId }}
|
||||
className={className}
|
||||
>
|
||||
{place.title}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
/** Everyone in the call, and before them the screens being shared. */
|
||||
function Stage({ call, isLarge }: { call: ActiveCall; isLarge: boolean }) {
|
||||
const participants = useParticipants();
|
||||
const screens = useTracks([Track.Source.ScreenShare]);
|
||||
// The API's word on who these people are: their pictures come from it.
|
||||
const { data } = useQuery(callsQuery);
|
||||
const people = data?.calls.find(
|
||||
(item) => item.conversationId === call.place.conversationId,
|
||||
)?.participants;
|
||||
|
||||
return (
|
||||
<ul
|
||||
className={cn(
|
||||
'gap-2',
|
||||
isLarge
|
||||
? 'grid min-h-0 flex-1 auto-rows-fr grid-cols-[repeat(auto-fit,minmax(min(100%,14rem),1fr))]'
|
||||
: 'flex overflow-x-auto',
|
||||
)}
|
||||
>
|
||||
{screens.map((screen) => (
|
||||
<Tile
|
||||
key={screen.publication.trackSid}
|
||||
isLarge={isLarge}
|
||||
label={`${nameOf(screen.participant)}’s screen`}
|
||||
>
|
||||
<VideoTrack trackRef={screen} className="size-full object-contain" />
|
||||
</Tile>
|
||||
))}
|
||||
{participants.map((participant) => (
|
||||
<ParticipantTile
|
||||
key={participant.identity}
|
||||
participant={participant}
|
||||
image={
|
||||
people?.find((person) => person.id === participant.identity)
|
||||
?.image ?? null
|
||||
}
|
||||
isLarge={isLarge}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
function ParticipantTile({
|
||||
participant,
|
||||
image,
|
||||
isLarge,
|
||||
}: {
|
||||
participant: Participant;
|
||||
image: string | null;
|
||||
isLarge: boolean;
|
||||
}) {
|
||||
const name = nameOf(participant);
|
||||
const isSpeaking = useIsSpeaking(participant);
|
||||
const isMuted = useIsMuted({
|
||||
participant,
|
||||
source: Track.Source.Microphone,
|
||||
});
|
||||
const [camera] = useParticipantTracks(
|
||||
[Track.Source.Camera],
|
||||
participant.identity,
|
||||
) as (TrackReference | undefined)[];
|
||||
const hasVideo = camera !== undefined && !camera.publication.isMuted;
|
||||
|
||||
return (
|
||||
<Tile
|
||||
isLarge={isLarge}
|
||||
label={participant.isLocal ? `${name} (you)` : name}
|
||||
isSpeaking={isSpeaking}
|
||||
badge={
|
||||
isMuted && (
|
||||
<>
|
||||
<MicOff className="size-3" aria-hidden="true" />
|
||||
<span className="sr-only">Muted</span>
|
||||
</>
|
||||
)
|
||||
}
|
||||
>
|
||||
{hasVideo ? (
|
||||
<VideoTrack
|
||||
trackRef={camera}
|
||||
// People expect to see themselves as in a mirror.
|
||||
className={cn(
|
||||
'size-full object-cover',
|
||||
participant.isLocal && '-scale-x-100',
|
||||
)}
|
||||
/>
|
||||
) : (
|
||||
<UserAvatar user={{ name, image }} size="lg" />
|
||||
)}
|
||||
</Tile>
|
||||
);
|
||||
}
|
||||
|
||||
function Tile({
|
||||
label,
|
||||
isLarge,
|
||||
isSpeaking = false,
|
||||
badge,
|
||||
children,
|
||||
}: {
|
||||
label: string;
|
||||
isLarge: boolean;
|
||||
isSpeaking?: boolean;
|
||||
/** Shown beside the name. */
|
||||
badge?: React.ReactNode;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<li
|
||||
className={cn(
|
||||
'relative flex items-center justify-center overflow-hidden rounded-lg bg-background ring-1 ring-border',
|
||||
isLarge ? 'min-h-0' : 'aspect-video h-24 shrink-0',
|
||||
isSpeaking && 'ring-2 ring-primary',
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
<p className="absolute bottom-1 left-1 flex max-w-[calc(100%-0.5rem)] items-center gap-1 rounded-md bg-background/80 px-1.5 py-0.5 text-xs">
|
||||
<span className="truncate">{label}</span>
|
||||
{badge}
|
||||
</p>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
function Controls() {
|
||||
const { localParticipant } = useLocalParticipant();
|
||||
const onDeviceError = (what: string) => () =>
|
||||
toast.add({
|
||||
title: `Couldn’t use your ${what}. Check the browser’s permission for this site.`,
|
||||
type: 'error',
|
||||
});
|
||||
const microphone = useTrackToggle({
|
||||
source: Track.Source.Microphone,
|
||||
onDeviceError: onDeviceError('microphone'),
|
||||
});
|
||||
const camera = useTrackToggle({
|
||||
source: Track.Source.Camera,
|
||||
onDeviceError: onDeviceError('camera'),
|
||||
});
|
||||
const screen = useTrackToggle({
|
||||
source: Track.Source.ScreenShare,
|
||||
// Closing the browser's own picker is a "no", not a fault.
|
||||
onDeviceError: () => undefined,
|
||||
});
|
||||
// Phones have no screens to share this way.
|
||||
const canShareScreen =
|
||||
typeof navigator.mediaDevices.getDisplayMedia === 'function';
|
||||
|
||||
return (
|
||||
<>
|
||||
<StartAudio
|
||||
label="Turn on sound"
|
||||
className={buttonVariants({ size: 'sm' })}
|
||||
/>
|
||||
<Button
|
||||
variant={microphone.enabled ? 'outline' : 'secondary'}
|
||||
size="sm"
|
||||
aria-pressed={!microphone.enabled}
|
||||
disabled={microphone.pending}
|
||||
onClick={() => void microphone.toggle()}
|
||||
>
|
||||
{microphone.enabled ? (
|
||||
<Mic aria-hidden="true" />
|
||||
) : (
|
||||
<MicOff aria-hidden="true" />
|
||||
)}
|
||||
{microphone.enabled ? 'Mute' : 'Unmute'}
|
||||
</Button>
|
||||
<Button
|
||||
variant={camera.enabled ? 'secondary' : 'outline'}
|
||||
size="sm"
|
||||
aria-pressed={camera.enabled}
|
||||
disabled={camera.pending}
|
||||
onClick={() => void camera.toggle()}
|
||||
>
|
||||
{camera.enabled ? (
|
||||
<VideoOff aria-hidden="true" />
|
||||
) : (
|
||||
<Video aria-hidden="true" />
|
||||
)}
|
||||
{camera.enabled ? 'Stop video' : 'Start video'}
|
||||
</Button>
|
||||
{canShareScreen && (
|
||||
<Button
|
||||
variant={screen.enabled ? 'secondary' : 'outline'}
|
||||
size="sm"
|
||||
aria-pressed={screen.enabled}
|
||||
disabled={screen.pending}
|
||||
onClick={() => void screen.toggle()}
|
||||
>
|
||||
{screen.enabled ? (
|
||||
<MonitorX aria-hidden="true" />
|
||||
) : (
|
||||
<MonitorUp aria-hidden="true" />
|
||||
)}
|
||||
<span className="sr-only sm:not-sr-only">
|
||||
{screen.enabled ? 'Stop sharing' : 'Share screen'}
|
||||
</span>
|
||||
</Button>
|
||||
)}
|
||||
<span className="sr-only" aria-live="polite">
|
||||
{localParticipant.isMicrophoneEnabled
|
||||
? 'Your microphone is on.'
|
||||
: 'Your microphone is off.'}
|
||||
</span>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** The display name the API put in the participant's token. */
|
||||
function nameOf(participant: Participant): string {
|
||||
return participant.name || 'Someone';
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import {
|
||||
createContext,
|
||||
use,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from 'react';
|
||||
import { DisconnectReason, Room, RoomEvent } from 'livekit-client';
|
||||
import { toast } from '@repo/ui/components/toast';
|
||||
import { ApiError } from '@/lib/api';
|
||||
import { requestCallAccess, stopRinging } from '@/lib/calls';
|
||||
|
||||
/** Where a call is: a conversation, or a cauldron of a realm. */
|
||||
export interface CallPlace {
|
||||
conversationId: string;
|
||||
/** Set for a cauldron. */
|
||||
realmId: string | null;
|
||||
/** What the place is called, as its own page shows it. */
|
||||
title: string;
|
||||
}
|
||||
|
||||
/** The call this tab is in. */
|
||||
export interface ActiveCall {
|
||||
place: CallPlace;
|
||||
/** The connection to the media server; LiveKit's hooks read from it. */
|
||||
room: Room;
|
||||
status: 'connecting' | 'connected';
|
||||
}
|
||||
|
||||
interface CallContextValue {
|
||||
/** Nothing when the user isn't in a call. */
|
||||
active: ActiveCall | null;
|
||||
/** Joins the call of a place, leaving the current one first. */
|
||||
join: (place: CallPlace) => void;
|
||||
leave: () => void;
|
||||
}
|
||||
|
||||
const CallContext = createContext<CallContextValue | null>(null);
|
||||
|
||||
export function useCalls(): CallContextValue {
|
||||
const value = use(CallContext);
|
||||
if (!value) throw new Error('useCalls needs a CallProvider above it.');
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Holds the call the user is in, above the pages, so that moving around
|
||||
* the app doesn't hang up. One call at a time: joining another leaves the
|
||||
* first.
|
||||
*/
|
||||
export function CallProvider({ children }: { children: React.ReactNode }) {
|
||||
const [active, setActive] = useState<ActiveCall | null>(null);
|
||||
// The same call for the callbacks below, which outlive the render that
|
||||
// made them and need to know whether their call is still the one.
|
||||
const current = useRef<{ room: Room; conversationId: string } | null>(null);
|
||||
|
||||
const leave = useCallback(() => {
|
||||
const room = current.current?.room;
|
||||
current.current = null;
|
||||
setActive(null);
|
||||
void room?.disconnect();
|
||||
}, []);
|
||||
|
||||
const join = useCallback((place: CallPlace) => {
|
||||
stopRinging(place.conversationId);
|
||||
if (current.current?.conversationId === place.conversationId) return;
|
||||
void current.current?.room.disconnect();
|
||||
|
||||
// Send each viewer only the video sizes they show, and none they don't.
|
||||
const room = new Room({ adaptiveStream: true, dynacast: true });
|
||||
const isCurrent = () => current.current?.room === room;
|
||||
const end = (message?: string, type: 'info' | 'error' = 'error') => {
|
||||
if (!isCurrent()) return;
|
||||
current.current = null;
|
||||
setActive(null);
|
||||
if (message) toast.add({ title: message, type });
|
||||
};
|
||||
current.current = { room, conversationId: place.conversationId };
|
||||
setActive({ place, room, status: 'connecting' });
|
||||
|
||||
// Only reached for a call that is still the current one: leaving and
|
||||
// switching clear `current` before they disconnect.
|
||||
room.on(RoomEvent.Disconnected, (reason) =>
|
||||
end(...disconnectNotice(reason)),
|
||||
);
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
const access = await requestCallAccess(place.conversationId);
|
||||
if (!isCurrent()) return;
|
||||
await room.connect(access.url, access.token);
|
||||
} catch (error) {
|
||||
void room.disconnect();
|
||||
end(
|
||||
error instanceof ApiError
|
||||
? error.message
|
||||
: 'Couldn’t connect to the call. Check your connection and try again.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!isCurrent()) return;
|
||||
setActive({ place, room, status: 'connected' });
|
||||
try {
|
||||
await room.localParticipant.setMicrophoneEnabled(true);
|
||||
} catch {
|
||||
if (!isCurrent()) return;
|
||||
toast.add({
|
||||
title:
|
||||
'Your microphone isn’t available, so you joined muted. Check the browser’s permission for this site.',
|
||||
type: 'warning',
|
||||
});
|
||||
}
|
||||
})();
|
||||
}, []);
|
||||
|
||||
// Signing out (or anything else that takes the app away) hangs up.
|
||||
useEffect(
|
||||
() => () => {
|
||||
void current.current?.room.disconnect();
|
||||
current.current = null;
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const value = useMemo(() => ({ active, join, leave }), [active, join, leave]);
|
||||
return <CallContext value={value}>{children}</CallContext>;
|
||||
}
|
||||
|
||||
/** What to tell someone whose call ended without them hanging up. */
|
||||
function disconnectNotice(
|
||||
reason: DisconnectReason | undefined,
|
||||
): [message?: string, type?: 'info' | 'error'] {
|
||||
switch (reason) {
|
||||
case DisconnectReason.CLIENT_INITIATED:
|
||||
return [];
|
||||
case DisconnectReason.DUPLICATE_IDENTITY:
|
||||
return ['You joined this call somewhere else, so it ended here.', 'info'];
|
||||
case DisconnectReason.PARTICIPANT_REMOVED:
|
||||
return ['You were taken out of the call.', 'info'];
|
||||
case DisconnectReason.ROOM_DELETED:
|
||||
return ['The call was ended.', 'info'];
|
||||
default:
|
||||
return ['The call was disconnected.', 'error'];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import { useState } from 'react';
|
||||
import { CAULDRON_NAME_MAX_LENGTH } from '@repo/contracts';
|
||||
import type { Cauldron } from '@repo/contracts';
|
||||
import { Button } from '@repo/ui/components/button';
|
||||
import {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@repo/ui/components/dialog';
|
||||
import { Field, FieldLabel } from '@repo/ui/components/field';
|
||||
import { Input } from '@repo/ui/components/input';
|
||||
import { Spinner } from '@repo/ui/components/spinner';
|
||||
import type { TriggerButtonProps } from '@/components/trigger-button';
|
||||
import { errorMessage } from '@/lib/errors';
|
||||
import { useCreateCauldron, useRenameCauldron } from '@/lib/realms';
|
||||
|
||||
interface CauldronDialogProps extends TriggerButtonProps {
|
||||
realmId: string;
|
||||
/** The cauldron to rename; a new one is created without it. */
|
||||
cauldron?: Cauldron;
|
||||
/** Called with a cauldron that was just created. */
|
||||
onCreated?: (cauldron: Cauldron) => void;
|
||||
}
|
||||
|
||||
/** A button that opens the form for naming a new or existing cauldron. */
|
||||
export function CauldronDialog({
|
||||
realmId,
|
||||
cauldron,
|
||||
onCreated,
|
||||
children,
|
||||
...button
|
||||
}: CauldronDialogProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger render={<Button {...button} />}>{children}</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-sm">
|
||||
{/* Mounted only while open, so each opening starts from the saved name. */}
|
||||
<CauldronForm
|
||||
realmId={realmId}
|
||||
cauldron={cauldron}
|
||||
onDone={(created) => {
|
||||
setOpen(false);
|
||||
if (created) onCreated?.(created);
|
||||
}}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function CauldronForm({
|
||||
realmId,
|
||||
cauldron,
|
||||
onDone,
|
||||
}: {
|
||||
realmId: string;
|
||||
cauldron?: Cauldron;
|
||||
onDone: (created?: Cauldron) => void;
|
||||
}) {
|
||||
const create = useCreateCauldron(realmId);
|
||||
const rename = useRenameCauldron(realmId);
|
||||
const [name, setName] = useState(cauldron?.name ?? '');
|
||||
const failure = create.error ?? rename.error;
|
||||
const isPending = create.isPending || rename.isPending;
|
||||
|
||||
function handleSubmit(event: React.FormEvent) {
|
||||
event.preventDefault();
|
||||
if (cauldron) {
|
||||
rename.mutate(
|
||||
{ cauldronId: cauldron.id, name },
|
||||
{ onSuccess: () => onDone() },
|
||||
);
|
||||
} else {
|
||||
create.mutate(name, { onSuccess: onDone });
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form className="grid gap-4" onSubmit={handleSubmit}>
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{cauldron ? 'Rename cauldron' : 'New cauldron'}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Everyone in the realm can read a cauldron.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="cauldron-name">Name</FieldLabel>
|
||||
<Input
|
||||
id="cauldron-name"
|
||||
value={name}
|
||||
maxLength={CAULDRON_NAME_MAX_LENGTH}
|
||||
placeholder="potions"
|
||||
autoComplete="off"
|
||||
onChange={(event) => setName(event.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
{failure && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{errorMessage(failure)}
|
||||
</p>
|
||||
)}
|
||||
<DialogFooter>
|
||||
<DialogClose render={<Button type="button" variant="outline" />}>
|
||||
Cancel
|
||||
</DialogClose>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={
|
||||
name.trim() === '' || name.trim() === cauldron?.name || isPending
|
||||
}
|
||||
>
|
||||
{isPending && <Spinner />}
|
||||
{cauldron ? 'Save' : 'Create'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
import { useEffect, useMemo, useRef } from 'react';
|
||||
import {
|
||||
useSuspenseInfiniteQuery,
|
||||
useSuspenseQuery,
|
||||
} from '@tanstack/react-query';
|
||||
import type { Message } from '@repo/contracts';
|
||||
import { ArrowDown } from 'lucide-react';
|
||||
import { Button } from '@repo/ui/components/button';
|
||||
import { Composer } from '@/components/composer';
|
||||
import { MessageRow } from '@/components/message-row';
|
||||
import {
|
||||
chronological,
|
||||
messagesQuery,
|
||||
useDeleteMessage,
|
||||
useToggleReaction,
|
||||
} from '@/lib/conversations';
|
||||
import { ownProfileQuery } from '@/lib/profile';
|
||||
import {
|
||||
setConversationOnScreen,
|
||||
useAttentive,
|
||||
useMarkRead,
|
||||
} from '@/lib/unread';
|
||||
import { useChatScroll } from '@/lib/use-chat-scroll';
|
||||
|
||||
// Messages from one person within this long are shown as one block.
|
||||
const GROUP_WINDOW_MS = 5 * 60 * 1000;
|
||||
|
||||
interface ChatViewProps {
|
||||
/** A conversation's id, or a cauldron's: both hold messages the same way. */
|
||||
conversationId: string;
|
||||
/** What the place is called, for the message box and screen readers. */
|
||||
title: string;
|
||||
/** Shown above the first message once the whole history is loaded. */
|
||||
startOfHistory: string;
|
||||
/** Set when the messages belong to a realm's cauldron: that realm's id. */
|
||||
realmId?: string;
|
||||
/** How many messages here the user hasn't read, as the lists show it. */
|
||||
unreadCount: number;
|
||||
/** Whether the user may add reactions; they can always take theirs back. */
|
||||
canReact?: boolean;
|
||||
/** Whether the user may delete other people's messages here, not only theirs. */
|
||||
canModerate?: boolean;
|
||||
/** Why the user can't post here; shown in place of the message box. */
|
||||
blockedNotice?: React.ReactNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* The messages of a conversation and the box to write one, filling the space
|
||||
* below whatever header the page puts above it. The history must be loaded
|
||||
* (or loading under a Suspense boundary) before this renders. Give it a `key`
|
||||
* per conversation, so each has its own draft and scroll position.
|
||||
*/
|
||||
export function ChatView({
|
||||
conversationId,
|
||||
title,
|
||||
startOfHistory,
|
||||
realmId,
|
||||
unreadCount,
|
||||
canReact = true,
|
||||
canModerate = false,
|
||||
blockedNotice,
|
||||
}: ChatViewProps) {
|
||||
const { data: profile } = useSuspenseQuery(ownProfileQuery);
|
||||
const history = useSuspenseInfiniteQuery(messagesQuery(conversationId));
|
||||
const messages = useMemo(
|
||||
() => chronological(history.data.pages),
|
||||
[history.data.pages],
|
||||
);
|
||||
const scroll = useChatScroll(messages);
|
||||
const toggleReaction = useToggleReaction(conversationId, profile.id);
|
||||
const { mutateAsync: deleteMessage } = useDeleteMessage(
|
||||
conversationId,
|
||||
realmId ?? null,
|
||||
);
|
||||
|
||||
// While the newest messages are in view, new ones aren't counted as
|
||||
// unread (see lib/unread) and are marked read below instead.
|
||||
useEffect(() => {
|
||||
setConversationOnScreen(conversationId, scroll.isAtEnd);
|
||||
return () => setConversationOnScreen(conversationId, false);
|
||||
}, [conversationId, scroll.isAtEnd]);
|
||||
|
||||
const latest = messages.at(-1);
|
||||
const isAttentive = useAttentive();
|
||||
const { mutate: markRead } = useMarkRead(conversationId, realmId ?? null);
|
||||
// The newest message the API has been told about. Starts at the newest
|
||||
// one loaded when there is nothing to tell.
|
||||
const marked = useRef(unreadCount === 0 ? latest?.id : undefined);
|
||||
useEffect(() => {
|
||||
if (!latest || latest.id === marked.current) return;
|
||||
if (!isAttentive || !scroll.isAtEnd) return;
|
||||
marked.current = latest.id;
|
||||
// The user's own message moves their marker when it is posted.
|
||||
if (unreadCount > 0 || latest.author.id !== profile.id) markRead(latest.id);
|
||||
}, [latest, isAttentive, scroll.isAtEnd, unreadCount, profile.id, markRead]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="relative min-h-0 flex-1">
|
||||
<div
|
||||
ref={scroll.viewportRef}
|
||||
onScroll={scroll.onScroll}
|
||||
role="log"
|
||||
aria-label={`Messages in ${title}`}
|
||||
className="h-full overflow-y-auto [overflow-anchor:none]"
|
||||
>
|
||||
{/* justify-end: a short conversation sits just above the composer. */}
|
||||
<div className="flex min-h-full flex-col justify-end p-4">
|
||||
<div className="flex justify-center pb-4">
|
||||
{history.hasNextPage ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={history.isFetchingNextPage}
|
||||
onClick={() => void history.fetchNextPage()}
|
||||
>
|
||||
Load earlier messages
|
||||
</Button>
|
||||
) : (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{startOfHistory}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
{messages.map((message, index) => (
|
||||
<MessageRow
|
||||
key={message.id}
|
||||
message={message}
|
||||
startsGroup={startsGroup(message, messages[index - 1])}
|
||||
onReact={
|
||||
canReact
|
||||
? (target, emoji) =>
|
||||
toggleReaction.mutate({ message: target, emoji })
|
||||
: undefined
|
||||
}
|
||||
onDelete={
|
||||
canModerate || message.author.id === profile.id
|
||||
? (target) => deleteMessage(target.id)
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
{!scroll.isAtEnd && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="absolute right-4 bottom-3 shadow-sm"
|
||||
onClick={scroll.scrollToEnd}
|
||||
>
|
||||
<ArrowDown aria-hidden="true" />
|
||||
Latest messages
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{blockedNotice ? (
|
||||
<p className="border-t px-4 py-3 text-center text-sm text-muted-foreground">
|
||||
{blockedNotice}
|
||||
</p>
|
||||
) : (
|
||||
<Composer
|
||||
conversationId={conversationId}
|
||||
inRealm={realmId !== undefined}
|
||||
recipient={title}
|
||||
onSend={scroll.scrollToEnd}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function startsGroup(message: Message, previous: Message | undefined) {
|
||||
return (
|
||||
!previous ||
|
||||
previous.author.id !== message.author.id ||
|
||||
Date.parse(message.createdAt) - Date.parse(previous.createdAt) >
|
||||
GROUP_WINDOW_MS
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import {
|
||||
MESSAGE_MAX_ATTACHMENTS,
|
||||
MESSAGE_MAX_LENGTH,
|
||||
sendMessageSchema,
|
||||
} from '@repo/contracts';
|
||||
import type { Attachment } from '@repo/contracts';
|
||||
import { CircleAlert, Paperclip, SendHorizontal, X } from 'lucide-react';
|
||||
import { Button } from '@repo/ui/components/button';
|
||||
import { Spinner } from '@repo/ui/components/spinner';
|
||||
import { Textarea } from '@repo/ui/components/textarea';
|
||||
import {
|
||||
discardAttachment,
|
||||
fileProblem,
|
||||
formatFileSize,
|
||||
uploadAttachment,
|
||||
} from '@/lib/attachments';
|
||||
import { useSendMessage } from '@/lib/conversations';
|
||||
import { errorMessage } from '@/lib/errors';
|
||||
|
||||
/** A file picked for the next message, on its way up or already there. */
|
||||
interface PickedFile {
|
||||
key: number;
|
||||
file: File;
|
||||
/** Set once the upload is done; its id goes in the message. */
|
||||
attachment?: Attachment;
|
||||
/** Why the upload failed, in words to show. */
|
||||
problem?: string;
|
||||
/** Stops the upload if the file is removed first. */
|
||||
abort: AbortController;
|
||||
}
|
||||
|
||||
interface ComposerProps {
|
||||
conversationId: string;
|
||||
/** The conversation is a realm's cauldron. */
|
||||
inRealm: boolean;
|
||||
/** Who or what the message goes to, for the placeholder. */
|
||||
recipient: string;
|
||||
/** Called as a message goes out, before it shows up in the list. */
|
||||
onSend: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* The box a message is written in, with the files picked for it. Files
|
||||
* start uploading as soon as they are picked (with the button, by pasting
|
||||
* or by dropping them on the page) and go out with the next message.
|
||||
*/
|
||||
export function Composer({
|
||||
conversationId,
|
||||
inRealm,
|
||||
recipient,
|
||||
onSend,
|
||||
}: ComposerProps) {
|
||||
const sendMessage = useSendMessage(conversationId, inRealm);
|
||||
const [draft, setDraft] = useState('');
|
||||
const [files, setFiles] = useState<PickedFile[]>([]);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const fileInput = useRef<HTMLInputElement>(null);
|
||||
const nextKey = useRef(0);
|
||||
// Uploads go one after another, so files keep the order they were picked in.
|
||||
const queue = useRef<Promise<void>>(Promise.resolve());
|
||||
const picked = useRef(files);
|
||||
useEffect(() => {
|
||||
picked.current = files;
|
||||
}, [files]);
|
||||
|
||||
// Leaving the chat stops what is still going up.
|
||||
useEffect(
|
||||
() => () => {
|
||||
for (const file of picked.current) file.abort.abort();
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
// Files dropped anywhere on the page are attached, not opened in place
|
||||
// of the app. Set up again on each render, so it sees the current files.
|
||||
useEffect(() => {
|
||||
const allow = (event: DragEvent) => {
|
||||
if (event.dataTransfer?.types.includes('Files')) event.preventDefault();
|
||||
};
|
||||
const take = (event: DragEvent) => {
|
||||
const dropped = event.dataTransfer?.files;
|
||||
if (!dropped || dropped.length === 0) return;
|
||||
event.preventDefault();
|
||||
addFiles([...dropped]);
|
||||
};
|
||||
window.addEventListener('dragover', allow);
|
||||
window.addEventListener('drop', take);
|
||||
return () => {
|
||||
window.removeEventListener('dragover', allow);
|
||||
window.removeEventListener('drop', take);
|
||||
};
|
||||
});
|
||||
|
||||
function update(key: number, change: Partial<PickedFile>) {
|
||||
setFiles((current) =>
|
||||
current.map((item) => (item.key === key ? { ...item, ...change } : item)),
|
||||
);
|
||||
}
|
||||
|
||||
function addFiles(chosen: File[]) {
|
||||
if (chosen.length === 0) return;
|
||||
setError(null);
|
||||
const room = MESSAGE_MAX_ATTACHMENTS - files.length;
|
||||
if (chosen.length > room) {
|
||||
setError(`A message can have at most ${MESSAGE_MAX_ATTACHMENTS} files.`);
|
||||
}
|
||||
const added: PickedFile[] = [];
|
||||
for (const file of chosen.slice(0, Math.max(room, 0))) {
|
||||
const problem = fileProblem(file);
|
||||
if (problem) {
|
||||
setError(problem);
|
||||
continue;
|
||||
}
|
||||
added.push({
|
||||
key: nextKey.current++,
|
||||
file,
|
||||
abort: new AbortController(),
|
||||
});
|
||||
}
|
||||
setFiles((current) => [...current, ...added]);
|
||||
for (const item of added) {
|
||||
// Asked afresh each time: the file may be removed at any point.
|
||||
const isRemoved = () => item.abort.signal.aborted;
|
||||
queue.current = queue.current.then(async () => {
|
||||
if (isRemoved()) return;
|
||||
try {
|
||||
const attachment = await uploadAttachment(
|
||||
item.file,
|
||||
item.abort.signal,
|
||||
);
|
||||
// Removed while the last bytes went up: the API can forget it.
|
||||
if (isRemoved()) {
|
||||
void discardAttachment(attachment.id).catch(() => undefined);
|
||||
} else {
|
||||
update(item.key, { attachment });
|
||||
}
|
||||
} catch (failure) {
|
||||
if (isRemoved()) return;
|
||||
update(item.key, {
|
||||
problem: errorMessage(failure, 'The upload failed.'),
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function remove(item: PickedFile) {
|
||||
item.abort.abort();
|
||||
if (item.attachment) {
|
||||
void discardAttachment(item.attachment.id).catch(() => undefined);
|
||||
}
|
||||
setFiles((current) => current.filter((other) => other.key !== item.key));
|
||||
}
|
||||
|
||||
const isUploading = files.some((item) => !item.attachment && !item.problem);
|
||||
const ready = files.flatMap((item) =>
|
||||
item.attachment ? [item.attachment.id] : [],
|
||||
);
|
||||
const parsed = sendMessageSchema.safeParse({
|
||||
content: draft,
|
||||
attachmentIds: ready,
|
||||
});
|
||||
// Nothing goes out while a file is still on its way.
|
||||
const canSend = parsed.success && !isUploading;
|
||||
|
||||
function send() {
|
||||
if (!parsed.success || isUploading) return;
|
||||
const sent = { draft, files };
|
||||
setDraft('');
|
||||
setFiles([]);
|
||||
setError(null);
|
||||
onSend();
|
||||
sendMessage.mutate(parsed.data, {
|
||||
onError: (failure) => {
|
||||
// Give it all back, unless something new was started meanwhile.
|
||||
setDraft((current) => (current === '' ? sent.draft : current));
|
||||
setFiles((current) => (current.length === 0 ? sent.files : current));
|
||||
setError(
|
||||
errorMessage(
|
||||
failure,
|
||||
'Could not send the message. Please try again.',
|
||||
),
|
||||
);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<form
|
||||
className="flex flex-col gap-2 border-t p-3"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
send();
|
||||
}}
|
||||
>
|
||||
{error && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{files.length > 0 && (
|
||||
<ul aria-label="Files to send" className="flex flex-wrap gap-2">
|
||||
{files.map((item) => (
|
||||
<li
|
||||
key={item.key}
|
||||
className="flex max-w-60 items-center gap-2 rounded-lg border bg-muted/50 py-1 pr-1 pl-2 text-xs"
|
||||
>
|
||||
{item.problem ? (
|
||||
<CircleAlert
|
||||
className="size-4 shrink-0 text-destructive"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
) : item.attachment ? (
|
||||
<Paperclip
|
||||
className="size-4 shrink-0 text-muted-foreground"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
) : (
|
||||
<Spinner className="shrink-0" aria-label="Uploading" />
|
||||
)}
|
||||
<span className="flex min-w-0 flex-col">
|
||||
<span className="truncate font-medium">{item.file.name}</span>
|
||||
<span
|
||||
className={
|
||||
item.problem ? 'text-destructive' : 'text-muted-foreground'
|
||||
}
|
||||
>
|
||||
{item.problem ??
|
||||
(item.attachment
|
||||
? formatFileSize(item.file.size)
|
||||
: 'Uploading…')}
|
||||
</span>
|
||||
</span>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
aria-label={`Remove ${item.file.name}`}
|
||||
title="Remove"
|
||||
onClick={() => remove(item)}
|
||||
>
|
||||
<X aria-hidden="true" />
|
||||
</Button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<div className="flex items-end gap-2">
|
||||
<input
|
||||
ref={fileInput}
|
||||
type="file"
|
||||
multiple
|
||||
hidden
|
||||
onChange={(event) => {
|
||||
addFiles([...(event.target.files ?? [])]);
|
||||
// So picking the same file again is noticed.
|
||||
event.target.value = '';
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
aria-label="Attach files"
|
||||
title="Attach files"
|
||||
disabled={files.length >= MESSAGE_MAX_ATTACHMENTS}
|
||||
onClick={() => fileInput.current?.click()}
|
||||
>
|
||||
<Paperclip aria-hidden="true" />
|
||||
</Button>
|
||||
<Textarea
|
||||
rows={1}
|
||||
value={draft}
|
||||
maxLength={MESSAGE_MAX_LENGTH}
|
||||
placeholder={`Message ${recipient}`}
|
||||
aria-label={`Message ${recipient}`}
|
||||
className="max-h-40 min-h-9 resize-none"
|
||||
onChange={(event) => setDraft(event.target.value)}
|
||||
onPaste={(event) => {
|
||||
// A pasted picture or file is attached; pasted text goes in.
|
||||
if (event.clipboardData.files.length === 0) return;
|
||||
event.preventDefault();
|
||||
addFiles([...event.clipboardData.files]);
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
// Enter sends, Shift+Enter adds a line; Enter that confirms an
|
||||
// IME composition (Japanese, Chinese...) does neither.
|
||||
if (
|
||||
event.key === 'Enter' &&
|
||||
!event.shiftKey &&
|
||||
!event.nativeEvent.isComposing
|
||||
) {
|
||||
event.preventDefault();
|
||||
send();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
type="submit"
|
||||
size="icon"
|
||||
aria-label="Send message"
|
||||
disabled={!canSend}
|
||||
>
|
||||
<SendHorizontal aria-hidden="true" />
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from '@repo/ui/components/alert-dialog';
|
||||
import { Button } from '@repo/ui/components/button';
|
||||
import { Spinner } from '@repo/ui/components/spinner';
|
||||
import { showError } from '@/lib/errors';
|
||||
|
||||
interface ConfirmButtonProps extends Pick<
|
||||
React.ComponentProps<typeof Button>,
|
||||
'variant' | 'size' | 'className' | 'disabled' | 'aria-label' | 'title'
|
||||
> {
|
||||
/** The button's own content. */
|
||||
children: React.ReactNode;
|
||||
/** The question the dialog asks. */
|
||||
question: string;
|
||||
/** What happens if they go ahead. */
|
||||
consequence: React.ReactNode;
|
||||
/** The label of the button that goes ahead. */
|
||||
confirmLabel: string;
|
||||
/**
|
||||
* Does it. Anything to do afterwards belongs in this promise, not in a
|
||||
* mutation's callbacks: the button may be gone by then (the socket often
|
||||
* reports the change first), which drops those.
|
||||
*/
|
||||
onConfirm: () => Promise<unknown>;
|
||||
}
|
||||
|
||||
/** A button that asks before doing something that can't be undone. */
|
||||
export function ConfirmButton({
|
||||
children,
|
||||
question,
|
||||
consequence,
|
||||
confirmLabel,
|
||||
onConfirm,
|
||||
...button
|
||||
}: ConfirmButtonProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [isPending, setIsPending] = useState(false);
|
||||
|
||||
function confirm() {
|
||||
setIsPending(true);
|
||||
onConfirm()
|
||||
.then(() => setOpen(false), showError)
|
||||
.finally(() => setIsPending(false));
|
||||
}
|
||||
|
||||
return (
|
||||
<AlertDialog open={open} onOpenChange={setOpen}>
|
||||
<AlertDialogTrigger render={<Button {...button} />}>
|
||||
{children}
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent className="shadow-xl">
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{question}</AlertDialogTitle>
|
||||
<AlertDialogDescription>{consequence}</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
variant="destructive"
|
||||
disabled={isPending}
|
||||
onClick={confirm}
|
||||
>
|
||||
{isPending && <Spinner />}
|
||||
{confirmLabel}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { Conversation } from '@repo/contracts';
|
||||
import { Users } from 'lucide-react';
|
||||
import { Avatar, AvatarFallback } from '@repo/ui/components/avatar';
|
||||
import { UserAvatar } from '@/components/user-avatar';
|
||||
import { otherMember } from '@/lib/conversations';
|
||||
|
||||
/** The other person's picture for a direct chat, a group mark for a group. */
|
||||
export function ConversationAvatar({
|
||||
conversation,
|
||||
ownId,
|
||||
}: {
|
||||
conversation: Conversation;
|
||||
ownId: string;
|
||||
}) {
|
||||
const other = otherMember(conversation, ownId);
|
||||
if (conversation.type === 'direct' && other) {
|
||||
return <UserAvatar user={other} />;
|
||||
}
|
||||
return (
|
||||
<Avatar>
|
||||
<AvatarFallback>
|
||||
<Users className="size-4" aria-hidden="true" />
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Link } from '@tanstack/react-router';
|
||||
import type { Conversation } from '@repo/contracts';
|
||||
import { Badge } from '@repo/ui/components/badge';
|
||||
import { cn } from '@repo/ui/lib/utils';
|
||||
import { CallMark } from '@/components/call-mark';
|
||||
import { ConversationAvatar } from '@/components/conversation-avatar';
|
||||
import { useCallPlaces } from '@/lib/calls';
|
||||
import {
|
||||
conversationTitle,
|
||||
conversationsQuery,
|
||||
memberCount,
|
||||
messagePreview,
|
||||
} from '@/lib/conversations';
|
||||
import { formatUnread } from '@/lib/unread';
|
||||
|
||||
interface ConversationListProps {
|
||||
/** The signed-in user's id, to tell which member is the other person. */
|
||||
ownId: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/** Links to the user's conversations, most recently active first. */
|
||||
export function ConversationList({ ownId, className }: ConversationListProps) {
|
||||
const { data: conversations } = useQuery(conversationsQuery);
|
||||
const calls = useCallPlaces();
|
||||
if (!conversations || conversations.length === 0) return null;
|
||||
|
||||
return (
|
||||
<ul className={cn('flex flex-col gap-0.5', className)}>
|
||||
{conversations.map((conversation) => (
|
||||
<li key={conversation.id}>
|
||||
<Link
|
||||
to="/app/c/$conversationId"
|
||||
params={{ conversationId: conversation.id }}
|
||||
className="flex items-center gap-2 rounded-lg px-2 py-1.5 hover:bg-muted data-[status=active]:bg-muted"
|
||||
>
|
||||
<ConversationAvatar conversation={conversation} ownId={ownId} />
|
||||
<span className="flex min-w-0 flex-1 flex-col">
|
||||
<span className="truncate text-sm font-medium">
|
||||
{conversationTitle(conversation, ownId)}
|
||||
</span>
|
||||
<span
|
||||
className={cn(
|
||||
'truncate text-xs text-muted-foreground',
|
||||
conversation.unreadCount > 0 && 'font-medium text-foreground',
|
||||
)}
|
||||
>
|
||||
{preview(conversation, ownId)}
|
||||
</span>
|
||||
</span>
|
||||
{calls.conversationIds.has(conversation.id) && <CallMark />}
|
||||
{conversation.unreadCount > 0 && (
|
||||
<Badge
|
||||
aria-label={`${formatUnread(conversation.unreadCount)} unread`}
|
||||
>
|
||||
{formatUnread(conversation.unreadCount)}
|
||||
</Badge>
|
||||
)}
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
/** The latest message; in a group, with who said it. */
|
||||
function preview(conversation: Conversation, ownId: string): string {
|
||||
const { lastMessage, type } = conversation;
|
||||
if (!lastMessage) {
|
||||
return type === 'group' ? memberCount(conversation) : 'No messages yet';
|
||||
}
|
||||
const text = messagePreview(lastMessage);
|
||||
if (lastMessage.author.id === ownId) return `You: ${text}`;
|
||||
return type === 'group' ? `${lastMessage.author.name}: ${text}` : text;
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
import { useState } from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useNavigate } from '@tanstack/react-router';
|
||||
import { GROUP_MAX_MEMBERS, GROUP_NAME_MAX_LENGTH } from '@repo/contracts';
|
||||
import type { Conversation } from '@repo/contracts';
|
||||
import { Users } from 'lucide-react';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from '@repo/ui/components/alert-dialog';
|
||||
import { Badge } from '@repo/ui/components/badge';
|
||||
import { Button } from '@repo/ui/components/button';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@repo/ui/components/dialog';
|
||||
import { Field, FieldLabel } from '@repo/ui/components/field';
|
||||
import { Input } from '@repo/ui/components/input';
|
||||
import { Spinner } from '@repo/ui/components/spinner';
|
||||
import { toast } from '@repo/ui/components/toast';
|
||||
import { PersonRow } from '@/components/person-row';
|
||||
import {
|
||||
conversationTitle,
|
||||
memberCount,
|
||||
useAddGroupMembers,
|
||||
useRemoveGroupMember,
|
||||
useRenameGroup,
|
||||
} from '@/lib/conversations';
|
||||
import { showError } from '@/lib/errors';
|
||||
import { friendsQuery } from '@/lib/friends';
|
||||
|
||||
interface GroupDetailsProps {
|
||||
conversation: Conversation;
|
||||
/** The signed-in user's id. */
|
||||
ownId: string;
|
||||
}
|
||||
|
||||
/** A button showing how many people are in a group; opens its details. */
|
||||
export function GroupDetailsDialog({ conversation, ownId }: GroupDetailsProps) {
|
||||
return (
|
||||
<Dialog>
|
||||
<DialogTrigger
|
||||
render={
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
aria-label={`Group details, ${memberCount(conversation)}`}
|
||||
title="Group details"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<Users aria-hidden="true" />
|
||||
{conversation.members.length}
|
||||
</DialogTrigger>
|
||||
{/* The leave confirmation opens on top without a backdrop of its own,
|
||||
so this dialog steps back while it is up. */}
|
||||
<DialogContent className="max-h-[85svh] overflow-y-auto transition-[filter] data-nested-dialog-open:brightness-90 sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{conversationTitle(conversation, ownId)}</DialogTitle>
|
||||
<DialogDescription>
|
||||
Anyone here can rename the group and add their friends. Only the
|
||||
owner can remove people.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<RenameForm conversation={conversation} />
|
||||
<Members conversation={conversation} ownId={ownId} />
|
||||
<AddPeople conversation={conversation} />
|
||||
<LeaveGroup conversation={conversation} ownId={ownId} />
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function RenameForm({ conversation }: { conversation: Conversation }) {
|
||||
const rename = useRenameGroup(conversation.id);
|
||||
const savedName = conversation.name ?? '';
|
||||
const [name, setName] = useState(savedName);
|
||||
|
||||
return (
|
||||
<form
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
rename.mutate(name, {
|
||||
onSuccess: (updated) => setName(updated.name ?? ''),
|
||||
onError: showError,
|
||||
});
|
||||
}}
|
||||
>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="group-rename">Name</FieldLabel>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
id="group-rename"
|
||||
value={name}
|
||||
maxLength={GROUP_NAME_MAX_LENGTH}
|
||||
placeholder="No name: shows who is in it"
|
||||
autoComplete="off"
|
||||
onChange={(event) => setName(event.target.value)}
|
||||
/>
|
||||
<Button
|
||||
type="submit"
|
||||
variant="outline"
|
||||
disabled={name.trim() === savedName || rename.isPending}
|
||||
>
|
||||
{rename.isPending && <Spinner />}
|
||||
Save
|
||||
</Button>
|
||||
</div>
|
||||
</Field>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function Members({ conversation, ownId }: GroupDetailsProps) {
|
||||
const remove = useRemoveGroupMember(conversation.id);
|
||||
const isOwner = conversation.ownerId === ownId;
|
||||
|
||||
return (
|
||||
<section className="flex flex-col gap-1">
|
||||
<h3 className="text-sm font-medium text-muted-foreground">
|
||||
Members ({conversation.members.length} of {GROUP_MAX_MEMBERS})
|
||||
</h3>
|
||||
<ul className="flex flex-col divide-y">
|
||||
{conversation.members.map((member) => (
|
||||
<PersonRow key={member.id} user={member}>
|
||||
{member.id === conversation.ownerId && (
|
||||
<Badge variant="secondary">Owner</Badge>
|
||||
)}
|
||||
{member.id === ownId && <Badge variant="outline">You</Badge>}
|
||||
{isOwner && member.id !== ownId && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
disabled={remove.isPending}
|
||||
onClick={() => remove.mutate(member.id, { onError: showError })}
|
||||
>
|
||||
Remove
|
||||
</Button>
|
||||
)}
|
||||
</PersonRow>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function AddPeople({ conversation }: { conversation: Conversation }) {
|
||||
const { data: friends } = useQuery(friendsQuery);
|
||||
const add = useAddGroupMembers(conversation.id);
|
||||
const candidates = (friends?.friends ?? []).filter(
|
||||
(friend) => !conversation.members.some((member) => member.id === friend.id),
|
||||
);
|
||||
const isFull = conversation.members.length >= GROUP_MAX_MEMBERS;
|
||||
|
||||
return (
|
||||
<section className="flex flex-col gap-1">
|
||||
<h3 className="text-sm font-medium text-muted-foreground">Add friends</h3>
|
||||
{isFull ? (
|
||||
<p className="py-2 text-sm text-muted-foreground">
|
||||
This group is full.
|
||||
</p>
|
||||
) : candidates.length === 0 ? (
|
||||
<p className="py-2 text-sm text-muted-foreground">
|
||||
All of your friends are already here.
|
||||
</p>
|
||||
) : (
|
||||
<ul className="flex flex-col divide-y">
|
||||
{candidates.map((friend) => (
|
||||
<PersonRow key={friend.id} user={friend}>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={add.isPending}
|
||||
onClick={() => add.mutate([friend.id], { onError: showError })}
|
||||
>
|
||||
Add
|
||||
</Button>
|
||||
</PersonRow>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function LeaveGroup({ conversation, ownId }: GroupDetailsProps) {
|
||||
const leave = useRemoveGroupMember(conversation.id);
|
||||
const navigate = useNavigate();
|
||||
const title = conversationTitle(conversation, ownId);
|
||||
const isLast = conversation.members.length === 1;
|
||||
const isOwner = conversation.ownerId === ownId;
|
||||
|
||||
return (
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger
|
||||
render={<Button variant="destructive" className="justify-self-start" />}
|
||||
>
|
||||
Leave group
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent className="shadow-xl">
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Leave this group?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{isLast
|
||||
? 'You are the last person here, so the group and its messages will be deleted.'
|
||||
: isOwner
|
||||
? 'The member who has been here longest becomes the owner. To come back, someone in the group has to add you again.'
|
||||
: 'To come back, someone in the group has to add you again.'}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Stay</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
variant="destructive"
|
||||
disabled={leave.isPending}
|
||||
// A promise rather than mutate()'s callbacks: those are dropped
|
||||
// if this dialog goes away first, which it does when the socket
|
||||
// reports the change before the request returns.
|
||||
onClick={() =>
|
||||
void leave.mutateAsync(ownId).then(() => {
|
||||
toast.add({ title: `You left ${title}`, type: 'success' });
|
||||
void navigate({ to: '/app' });
|
||||
}, showError)
|
||||
}
|
||||
>
|
||||
{leave.isPending && <Spinner />}
|
||||
Leave group
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Phone, X } from 'lucide-react';
|
||||
import { Button } from '@repo/ui/components/button';
|
||||
import { useCalls } from '@/components/call-provider';
|
||||
import { UserAvatar } from '@/components/user-avatar';
|
||||
import { stopRinging, useRinging } from '@/lib/calls';
|
||||
import { conversationTitle, conversationsQuery } from '@/lib/conversations';
|
||||
|
||||
/**
|
||||
* Offers the calls friends just started in the user's chats: who is
|
||||
* calling, with a way to join and a way to wave it off. Each offer goes
|
||||
* away by itself after a while, and when the call ends.
|
||||
*/
|
||||
export function IncomingCalls({ ownId }: { ownId: string }) {
|
||||
const ringing = useRinging();
|
||||
const { data: conversations } = useQuery(conversationsQuery);
|
||||
const { join } = useCalls();
|
||||
|
||||
return (
|
||||
// Always there, so that screen readers announce what appears in it.
|
||||
<section
|
||||
aria-label="Incoming calls"
|
||||
aria-live="assertive"
|
||||
className="pointer-events-none fixed inset-x-4 top-4 z-50 flex flex-col items-end gap-2"
|
||||
>
|
||||
{ringing.map((call) => {
|
||||
const conversation = conversations?.find(
|
||||
(item) => item.id === call.conversationId,
|
||||
);
|
||||
const caller = call.participants.at(0);
|
||||
if (!conversation || !caller) return null;
|
||||
const title = conversationTitle(conversation, ownId);
|
||||
return (
|
||||
<div
|
||||
key={call.conversationId}
|
||||
className="pointer-events-auto flex w-full max-w-sm items-center gap-3 rounded-2xl border bg-popover p-3 text-popover-foreground shadow-lg"
|
||||
>
|
||||
<UserAvatar user={caller} />
|
||||
<p className="min-w-0 flex-1 text-sm">
|
||||
<span className="block truncate font-medium">{caller.name}</span>
|
||||
<span className="block truncate text-xs text-muted-foreground">
|
||||
{conversation.type === 'group'
|
||||
? `Started a call in ${title}`
|
||||
: 'Incoming call'}
|
||||
</span>
|
||||
</p>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() =>
|
||||
join({
|
||||
conversationId: call.conversationId,
|
||||
realmId: null,
|
||||
title,
|
||||
})
|
||||
}
|
||||
>
|
||||
<Phone aria-hidden="true" />
|
||||
Join
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
aria-label={`Dismiss the call from ${caller.name}`}
|
||||
title="Dismiss"
|
||||
onClick={() => stopRinging(call.conversationId)}
|
||||
>
|
||||
<X aria-hidden="true" />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
import { useState } from 'react';
|
||||
import { INVITE_EXPIRY_DAYS } from '@repo/contracts';
|
||||
import type { RealmInvite } from '@repo/contracts';
|
||||
import { Copy } from 'lucide-react';
|
||||
import { Button } from '@repo/ui/components/button';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@repo/ui/components/dialog';
|
||||
import { Field, FieldLabel } from '@repo/ui/components/field';
|
||||
import { Input } from '@repo/ui/components/input';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@repo/ui/components/select';
|
||||
import { Spinner } from '@repo/ui/components/spinner';
|
||||
import { toast } from '@repo/ui/components/toast';
|
||||
import type { TriggerButtonProps } from '@/components/trigger-button';
|
||||
import { errorMessage } from '@/lib/errors';
|
||||
import { inviteLink, useCreateInvite } from '@/lib/realms';
|
||||
|
||||
const NEVER = 'never';
|
||||
const NO_LIMIT = 'none';
|
||||
|
||||
const EXPIRY_OPTIONS = [
|
||||
...INVITE_EXPIRY_DAYS.map((days) => ({
|
||||
value: String(days),
|
||||
label: days === 1 ? '1 day' : `${days} days`,
|
||||
})),
|
||||
{ value: NEVER, label: 'Never' },
|
||||
];
|
||||
|
||||
const USES_OPTIONS = [
|
||||
{ value: NO_LIMIT, label: 'No limit' },
|
||||
...[1, 5, 10, 25, 100].map((uses) => ({
|
||||
value: String(uses),
|
||||
label: uses === 1 ? '1 person' : `${uses} people`,
|
||||
})),
|
||||
];
|
||||
|
||||
/** Copies an invite's link and says so. */
|
||||
export async function copyInviteLink(code: string) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(inviteLink(code));
|
||||
toast.add({ title: 'Invite link copied', type: 'success' });
|
||||
} catch {
|
||||
toast.add({
|
||||
title: 'Could not copy. Select the link and copy it yourself.',
|
||||
type: 'error',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** A button that opens the form for making an invite link to a realm. */
|
||||
export function InviteDialog({
|
||||
realmId,
|
||||
realmName,
|
||||
children,
|
||||
...button
|
||||
}: TriggerButtonProps & { realmId: string; realmName: string }) {
|
||||
return (
|
||||
<Dialog>
|
||||
<DialogTrigger render={<Button {...button} />}>{children}</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Invite people to {realmName}</DialogTitle>
|
||||
<DialogDescription>
|
||||
Anyone with the link can join until it runs out, so share it only
|
||||
with people you want here.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
{/* Mounted only while open, so an old link isn't shown again. */}
|
||||
<InviteForm realmId={realmId} />
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function InviteForm({ realmId }: { realmId: string }) {
|
||||
const createInvite = useCreateInvite(realmId);
|
||||
const [expiry, setExpiry] = useState('7');
|
||||
const [maxUses, setMaxUses] = useState(NO_LIMIT);
|
||||
const [invite, setInvite] = useState<RealmInvite | null>(null);
|
||||
|
||||
return (
|
||||
<form
|
||||
className="grid gap-4"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
createInvite.mutate(
|
||||
{
|
||||
expiresInDays:
|
||||
expiry === NEVER
|
||||
? null
|
||||
: (INVITE_EXPIRY_DAYS.find((d) => String(d) === expiry) ?? 7),
|
||||
maxUses: maxUses === NO_LIMIT ? null : Number(maxUses),
|
||||
},
|
||||
{ onSuccess: setInvite },
|
||||
);
|
||||
}}
|
||||
>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<Field>
|
||||
<FieldLabel htmlFor="invite-expiry">Expires after</FieldLabel>
|
||||
<Select
|
||||
items={EXPIRY_OPTIONS}
|
||||
value={expiry}
|
||||
onValueChange={(value) => {
|
||||
if (value) setExpiry(value);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger id="invite-expiry" className="w-full">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{EXPIRY_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="invite-uses">Can be used by</FieldLabel>
|
||||
<Select
|
||||
items={USES_OPTIONS}
|
||||
value={maxUses}
|
||||
onValueChange={(value) => {
|
||||
if (value) setMaxUses(value);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger id="invite-uses" className="w-full">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{USES_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
</div>
|
||||
|
||||
{createInvite.isError && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{errorMessage(
|
||||
createInvite.error,
|
||||
'Could not make the link. Please try again.',
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{invite && (
|
||||
<Field>
|
||||
<FieldLabel htmlFor="invite-link">Invite link</FieldLabel>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
id="invite-link"
|
||||
readOnly
|
||||
value={inviteLink(invite.code)}
|
||||
onFocus={(event) => event.target.select()}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={() => void copyInviteLink(invite.code)}
|
||||
>
|
||||
<Copy aria-hidden="true" />
|
||||
Copy
|
||||
</Button>
|
||||
</div>
|
||||
</Field>
|
||||
)}
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
variant={invite ? 'outline' : 'default'}
|
||||
className="justify-self-start"
|
||||
disabled={createInvite.isPending}
|
||||
>
|
||||
{createInvite.isPending && <Spinner />}
|
||||
{invite ? 'Make another link' : 'Make a link'}
|
||||
</Button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
import { useState } from 'react';
|
||||
import type { Realm, RealmMember } from '@repo/contracts';
|
||||
import { Button } from '@repo/ui/components/button';
|
||||
import { Checkbox } from '@repo/ui/components/checkbox';
|
||||
import {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@repo/ui/components/dialog';
|
||||
import { Spinner } from '@repo/ui/components/spinner';
|
||||
import type { TriggerButtonProps } from '@/components/trigger-button';
|
||||
import { errorMessage } from '@/lib/errors';
|
||||
import {
|
||||
PERMISSION_LABELS,
|
||||
canManageRole,
|
||||
useSetMemberRoles,
|
||||
} from '@/lib/realms';
|
||||
|
||||
interface MemberRolesDialogProps extends TriggerButtonProps {
|
||||
realm: Realm;
|
||||
member: RealmMember;
|
||||
}
|
||||
|
||||
/** A button that opens the choice of roles for one member of a realm. */
|
||||
export function MemberRolesDialog({
|
||||
realm,
|
||||
member,
|
||||
children,
|
||||
...button
|
||||
}: MemberRolesDialogProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger render={<Button {...button} />}>{children}</DialogTrigger>
|
||||
<DialogContent className="max-h-[85svh] overflow-y-auto sm:max-w-md">
|
||||
{/* Mounted only while open, so each opening starts from what is saved. */}
|
||||
<RolesForm
|
||||
realm={realm}
|
||||
member={member}
|
||||
onDone={() => setOpen(false)}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function RolesForm({
|
||||
realm,
|
||||
member,
|
||||
onDone,
|
||||
}: {
|
||||
realm: Realm;
|
||||
member: RealmMember;
|
||||
onDone: () => void;
|
||||
}) {
|
||||
const setRoles = useSetMemberRoles(realm.id);
|
||||
const [roleIds, setRoleIds] = useState(member.roleIds);
|
||||
const roles = realm.roles.filter((role) => !role.isDefault);
|
||||
|
||||
function toggle(roleId: string, checked: boolean) {
|
||||
setRoleIds((current) =>
|
||||
checked ? [...current, roleId] : current.filter((id) => id !== roleId),
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<form
|
||||
className="grid gap-4"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
setRoles.mutate(
|
||||
{ userId: member.user.id, roleIds },
|
||||
{ onSuccess: onDone },
|
||||
);
|
||||
}}
|
||||
>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Roles of {member.user.name}</DialogTitle>
|
||||
<DialogDescription>
|
||||
They can do what any of their roles allows, on top of what everyone in
|
||||
the realm may do.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<fieldset className="grid gap-1">
|
||||
<legend className="sr-only">Roles</legend>
|
||||
{roles.map((role) => {
|
||||
const isOutOfReach = !canManageRole(realm, role);
|
||||
return (
|
||||
<label
|
||||
key={role.id}
|
||||
className="grid cursor-pointer grid-cols-[auto_1fr] gap-x-3 rounded-lg px-2 py-1.5 hover:bg-muted has-disabled:cursor-not-allowed has-disabled:opacity-60"
|
||||
>
|
||||
<Checkbox
|
||||
aria-label={role.name}
|
||||
className="row-span-2 mt-0.5"
|
||||
checked={roleIds.includes(role.id)}
|
||||
disabled={isOutOfReach}
|
||||
onCheckedChange={(next) => toggle(role.id, next)}
|
||||
/>
|
||||
<span className="min-w-0 text-sm">{role.name}</span>
|
||||
<span className="col-start-2 min-w-0 text-xs text-muted-foreground">
|
||||
{isOutOfReach
|
||||
? 'Allows more than you can do, so it isn’t yours to give or take.'
|
||||
: role.permissions.length === 0
|
||||
? 'Allows nothing extra.'
|
||||
: role.permissions
|
||||
.map((permission) => PERMISSION_LABELS[permission].name)
|
||||
.join(', ')}
|
||||
</span>
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
</fieldset>
|
||||
|
||||
{setRoles.isError && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{errorMessage(setRoles.error)}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<DialogFooter>
|
||||
<DialogClose render={<Button type="button" variant="outline" />}>
|
||||
Cancel
|
||||
</DialogClose>
|
||||
<Button type="submit" disabled={setRoles.isPending}>
|
||||
{setRoles.isPending && <Spinner />}
|
||||
Save
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
import { useState } from 'react';
|
||||
import { isInlineImage } from '@repo/contracts';
|
||||
import type { Attachment, Message } from '@repo/contracts';
|
||||
import { FileText, SmilePlus, Trash2 } from 'lucide-react';
|
||||
import { Button } from '@repo/ui/components/button';
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from '@repo/ui/components/popover';
|
||||
import { cn } from '@repo/ui/lib/utils';
|
||||
import { ConfirmButton } from '@/components/confirm-button';
|
||||
import { UserAvatar } from '@/components/user-avatar';
|
||||
import { attachmentUrl, formatFileSize } from '@/lib/attachments';
|
||||
import { formatMessageTime } from '@/lib/format';
|
||||
|
||||
/** The emoji offered for a reaction. */
|
||||
const QUICK_REACTIONS = [
|
||||
'👍',
|
||||
'❤️',
|
||||
'😂',
|
||||
'😮',
|
||||
'😢',
|
||||
'🙏',
|
||||
'🎉',
|
||||
'🔥',
|
||||
'👀',
|
||||
'✅',
|
||||
'👎',
|
||||
'🤔',
|
||||
];
|
||||
|
||||
// The most room a picture takes in the chat, in pixels.
|
||||
const PICTURE_MAX_WIDTH = 360;
|
||||
const PICTURE_MAX_HEIGHT = 280;
|
||||
|
||||
interface MessageRowProps {
|
||||
message: Message;
|
||||
/** The first of a run of messages from one person: shows who and when. */
|
||||
startsGroup: boolean;
|
||||
/** Adds the user's reaction, or takes it back. Left out when they can't. */
|
||||
onReact?: (message: Message, emoji: string) => void;
|
||||
/** Deletes the message for everyone. Left out when the user may not. */
|
||||
onDelete?: (message: Message) => Promise<unknown>;
|
||||
}
|
||||
|
||||
export function MessageRow({
|
||||
message,
|
||||
startsGroup,
|
||||
onReact,
|
||||
onDelete,
|
||||
}: MessageRowProps) {
|
||||
// Carried by the message itself, so people who have left since still show
|
||||
// by name.
|
||||
const { author } = message;
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'group/message relative flex gap-3',
|
||||
startsGroup ? 'pt-4' : 'pt-0.5',
|
||||
)}
|
||||
>
|
||||
<div className="w-8 shrink-0">
|
||||
{startsGroup && <UserAvatar user={author} />}
|
||||
</div>
|
||||
{/* Room on the right for the buttons. */}
|
||||
<div
|
||||
className={cn(
|
||||
'min-w-0 flex-1',
|
||||
onReact && onDelete ? 'pr-16' : (onReact ?? onDelete) && 'pr-8',
|
||||
)}
|
||||
>
|
||||
{startsGroup && (
|
||||
<div className="flex items-baseline gap-2">
|
||||
<span className="truncate text-sm font-medium">{author.name}</span>
|
||||
<time
|
||||
dateTime={message.createdAt}
|
||||
className="shrink-0 text-xs text-muted-foreground"
|
||||
>
|
||||
{formatMessageTime(message.createdAt)}
|
||||
</time>
|
||||
</div>
|
||||
)}
|
||||
{message.content && (
|
||||
<p className="text-sm wrap-break-word whitespace-pre-wrap">
|
||||
{message.content}
|
||||
</p>
|
||||
)}
|
||||
{message.attachments.length > 0 && (
|
||||
<ul className="flex flex-col items-start gap-1.5 py-1">
|
||||
{message.attachments.map((attachment) => (
|
||||
<li key={attachment.id} className="max-w-full">
|
||||
<AttachmentView attachment={attachment} />
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
{message.reactions.length > 0 && (
|
||||
<ul className="flex flex-wrap gap-1 py-1">
|
||||
{message.reactions.map((reaction) => (
|
||||
<li key={reaction.emoji}>
|
||||
<button
|
||||
type="button"
|
||||
disabled={!onReact}
|
||||
aria-pressed={reaction.mine}
|
||||
aria-label={`${reaction.emoji} ${reaction.count}, ${reaction.mine ? 'take back your reaction' : 'react the same'}`}
|
||||
onClick={() => onReact?.(message, reaction.emoji)}
|
||||
className={cn(
|
||||
'flex h-6 items-center gap-1 rounded-full border px-2 text-xs tabular-nums outline-none focus-visible:ring-3 focus-visible:ring-ring/50 enabled:hover:bg-muted',
|
||||
reaction.mine &&
|
||||
'border-primary/50 bg-primary/10 font-medium enabled:hover:bg-primary/20',
|
||||
)}
|
||||
>
|
||||
<span aria-hidden="true">{reaction.emoji}</span>
|
||||
{reaction.count}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
{(onReact ?? onDelete) && (
|
||||
<div
|
||||
className={cn(
|
||||
// They show when the message is pointed at or one of them is
|
||||
// focused or open, and all the time where there is no pointer
|
||||
// to hover with.
|
||||
'absolute right-0 flex gap-1 opacity-0 group-hover/message:opacity-100 focus-within:opacity-100 has-data-popup-open:opacity-100 [@media(hover:none)]:opacity-100',
|
||||
// Level with the first line of text, below the gap above a group.
|
||||
startsGroup ? 'top-4' : 'top-0',
|
||||
)}
|
||||
>
|
||||
{onReact && (
|
||||
<ReactionPicker
|
||||
message={message}
|
||||
className={ACTION_CLASS}
|
||||
onPick={(emoji) => onReact(message, emoji)}
|
||||
/>
|
||||
)}
|
||||
{onDelete && (
|
||||
<ConfirmButton
|
||||
variant="outline"
|
||||
size="icon-xs"
|
||||
aria-label="Delete message"
|
||||
title="Delete message"
|
||||
className={ACTION_CLASS}
|
||||
question="Delete this message?"
|
||||
consequence="It is deleted for everyone here, with its files and reactions. This can’t be undone."
|
||||
confirmLabel="Delete message"
|
||||
onConfirm={() => onDelete(message)}
|
||||
>
|
||||
<Trash2 aria-hidden="true" />
|
||||
</ConfirmButton>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Always there on touch screens, so kept quiet.
|
||||
const ACTION_CLASS =
|
||||
'bg-background [@media(hover:none)]:border-transparent [@media(hover:none)]:bg-transparent [@media(hover:none)]:text-muted-foreground';
|
||||
|
||||
/** The button that offers emoji for a message. */
|
||||
function ReactionPicker({
|
||||
message,
|
||||
className,
|
||||
onPick,
|
||||
}: {
|
||||
message: Message;
|
||||
className?: string;
|
||||
onPick: (emoji: string) => void;
|
||||
}) {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
return (
|
||||
<Popover open={isOpen} onOpenChange={setIsOpen}>
|
||||
<PopoverTrigger
|
||||
render={
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon-xs"
|
||||
aria-label="Add a reaction"
|
||||
title="Add a reaction"
|
||||
className={className}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<SmilePlus aria-hidden="true" />
|
||||
</PopoverTrigger>
|
||||
<PopoverContent align="end" className="w-auto">
|
||||
<ul className="grid grid-cols-6 gap-1">
|
||||
{QUICK_REACTIONS.map((emoji) => {
|
||||
const mine = message.reactions.some(
|
||||
(reaction) => reaction.emoji === emoji && reaction.mine,
|
||||
);
|
||||
return (
|
||||
<li key={emoji}>
|
||||
<Button
|
||||
variant={mine ? 'secondary' : 'ghost'}
|
||||
size="icon"
|
||||
aria-pressed={mine}
|
||||
aria-label={
|
||||
mine ? `Take back ${emoji}` : `React with ${emoji}`
|
||||
}
|
||||
className="text-base"
|
||||
onClick={() => {
|
||||
onPick(emoji);
|
||||
setIsOpen(false);
|
||||
}}
|
||||
>
|
||||
<span aria-hidden="true">{emoji}</span>
|
||||
</Button>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
|
||||
/** A picture shown in place, or any other file as a link that downloads it. */
|
||||
function AttachmentView({ attachment }: { attachment: Attachment }) {
|
||||
const url = attachmentUrl(attachment.id);
|
||||
const { width, height } = attachment;
|
||||
if (isInlineImage(attachment) && width !== null && height !== null) {
|
||||
// Sized before it loads, so the messages below don't jump.
|
||||
const scale = Math.min(
|
||||
1,
|
||||
PICTURE_MAX_WIDTH / width,
|
||||
PICTURE_MAX_HEIGHT / height,
|
||||
);
|
||||
return (
|
||||
<a
|
||||
href={url}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
title={`Open ${attachment.filename}`}
|
||||
className="block overflow-hidden rounded-lg border outline-none focus-visible:ring-3 focus-visible:ring-ring/50"
|
||||
>
|
||||
<img
|
||||
src={url}
|
||||
alt={attachment.filename}
|
||||
width={width}
|
||||
height={height}
|
||||
loading="lazy"
|
||||
className="h-auto max-w-full bg-muted"
|
||||
style={{
|
||||
width: Math.round(width * scale),
|
||||
aspectRatio: `${width} / ${height}`,
|
||||
}}
|
||||
/>
|
||||
</a>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<a
|
||||
href={url}
|
||||
download={attachment.filename}
|
||||
className="flex max-w-full items-center gap-2 rounded-lg border px-3 py-2 outline-none hover:bg-muted focus-visible:ring-3 focus-visible:ring-ring/50 sm:max-w-sm"
|
||||
>
|
||||
<FileText
|
||||
className="size-5 shrink-0 text-muted-foreground"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span className="flex min-w-0 flex-col">
|
||||
<span className="truncate text-sm font-medium">
|
||||
{attachment.filename}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{formatFileSize(attachment.size)}
|
||||
</span>
|
||||
</span>
|
||||
</a>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
import { useState } from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Link, useNavigate } from '@tanstack/react-router';
|
||||
import {
|
||||
GROUP_MAX_MEMBERS,
|
||||
GROUP_MIN_INVITED,
|
||||
GROUP_NAME_MAX_LENGTH,
|
||||
} from '@repo/contracts';
|
||||
import { Plus } from 'lucide-react';
|
||||
import { Button } from '@repo/ui/components/button';
|
||||
import { Checkbox } from '@repo/ui/components/checkbox';
|
||||
import {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@repo/ui/components/dialog';
|
||||
import { Field, FieldLabel } from '@repo/ui/components/field';
|
||||
import { Input } from '@repo/ui/components/input';
|
||||
import { Spinner } from '@repo/ui/components/spinner';
|
||||
import { UserAvatar } from '@/components/user-avatar';
|
||||
import { useCreateGroup } from '@/lib/conversations';
|
||||
import { errorMessage } from '@/lib/errors';
|
||||
import { friendsQuery } from '@/lib/friends';
|
||||
|
||||
// The creator takes one of the places.
|
||||
const MAX_INVITED = GROUP_MAX_MEMBERS - 1;
|
||||
|
||||
/** A button that opens the form for starting a group chat. */
|
||||
export function NewGroupDialog({
|
||||
variant = 'icon',
|
||||
}: {
|
||||
/** "icon" is a small plus for headings; "text" spells it out. */
|
||||
variant?: 'icon' | 'text';
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger
|
||||
render={
|
||||
variant === 'icon' ? (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
aria-label="New group"
|
||||
title="New group"
|
||||
/>
|
||||
) : (
|
||||
<Button variant="outline" size="sm" />
|
||||
)
|
||||
}
|
||||
>
|
||||
<Plus aria-hidden="true" />
|
||||
{variant === 'text' && 'New group'}
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
{/* Mounted only while open, so each opening starts from a blank form. */}
|
||||
<NewGroupForm onDone={() => setOpen(false)} />
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function NewGroupForm({ onDone }: { onDone: () => void }) {
|
||||
const { data: friends } = useQuery(friendsQuery);
|
||||
const createGroup = useCreateGroup();
|
||||
const navigate = useNavigate();
|
||||
const [name, setName] = useState('');
|
||||
const [selected, setSelected] = useState<string[]>([]);
|
||||
const people = friends?.friends ?? [];
|
||||
|
||||
function toggle(userId: string, checked: boolean) {
|
||||
setSelected((current) =>
|
||||
checked ? [...current, userId] : current.filter((id) => id !== userId),
|
||||
);
|
||||
}
|
||||
|
||||
function handleSubmit(event: React.FormEvent) {
|
||||
event.preventDefault();
|
||||
createGroup.mutate(
|
||||
{ name, memberIds: selected },
|
||||
{
|
||||
onSuccess: (conversation) => {
|
||||
onDone();
|
||||
void navigate({
|
||||
to: '/app/c/$conversationId',
|
||||
params: { conversationId: conversation.id },
|
||||
});
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<form className="grid gap-4" onSubmit={handleSubmit}>
|
||||
<DialogHeader>
|
||||
<DialogTitle>New group</DialogTitle>
|
||||
<DialogDescription>
|
||||
Pick at least {GROUP_MIN_INVITED} friends. You can add more later, up
|
||||
to {GROUP_MAX_MEMBERS} people in all.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{friends && people.length < GROUP_MIN_INVITED ? (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
A group needs at least {GROUP_MIN_INVITED} of your friends.{' '}
|
||||
<Link to="/app/friends" className="underline" onClick={onDone}>
|
||||
Add some friends
|
||||
</Link>{' '}
|
||||
first.
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="group-name">Name (optional)</FieldLabel>
|
||||
<Input
|
||||
id="group-name"
|
||||
value={name}
|
||||
maxLength={GROUP_NAME_MAX_LENGTH}
|
||||
placeholder="Shown instead of everyone's names"
|
||||
autoComplete="off"
|
||||
onChange={(event) => setName(event.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<fieldset className="grid gap-1">
|
||||
<legend className="pb-1 text-sm font-medium">
|
||||
Friends ({selected.length} of {MAX_INVITED} picked)
|
||||
</legend>
|
||||
<ul className="max-h-64 overflow-y-auto">
|
||||
{people.map((friend) => {
|
||||
const checked = selected.includes(friend.id);
|
||||
return (
|
||||
<li key={friend.id}>
|
||||
<label className="flex cursor-pointer items-center gap-3 rounded-lg px-2 py-1.5 hover:bg-muted has-disabled:cursor-not-allowed has-disabled:opacity-60">
|
||||
<Checkbox
|
||||
aria-label={friend.name}
|
||||
checked={checked}
|
||||
disabled={!checked && selected.length >= MAX_INVITED}
|
||||
onCheckedChange={(next) => toggle(friend.id, next)}
|
||||
/>
|
||||
<UserAvatar user={friend} size="sm" />
|
||||
<span className="min-w-0 flex-1 truncate text-sm">
|
||||
{friend.name}
|
||||
</span>
|
||||
{friend.username && (
|
||||
<span className="truncate text-xs text-muted-foreground">
|
||||
@{friend.username}
|
||||
</span>
|
||||
)}
|
||||
</label>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</fieldset>
|
||||
</>
|
||||
)}
|
||||
|
||||
{createGroup.isError && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{errorMessage(
|
||||
createGroup.error,
|
||||
'Could not create the group. Please try again.',
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<DialogFooter>
|
||||
<DialogClose render={<Button type="button" variant="outline" />}>
|
||||
Cancel
|
||||
</DialogClose>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={
|
||||
selected.length < GROUP_MIN_INVITED || createGroup.isPending
|
||||
}
|
||||
>
|
||||
{createGroup.isPending && <Spinner />}
|
||||
Create group
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
import { useState } from 'react';
|
||||
import { useNavigate } from '@tanstack/react-router';
|
||||
import { REALM_NAME_MAX_LENGTH } from '@repo/contracts';
|
||||
import { Plus } from 'lucide-react';
|
||||
import { Button } from '@repo/ui/components/button';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@repo/ui/components/dialog';
|
||||
import { Field, FieldDescription, FieldLabel } from '@repo/ui/components/field';
|
||||
import { Input } from '@repo/ui/components/input';
|
||||
import { Separator } from '@repo/ui/components/separator';
|
||||
import { Spinner } from '@repo/ui/components/spinner';
|
||||
import { errorMessage } from '@/lib/errors';
|
||||
import { inviteCodeFrom, useCreateRealm } from '@/lib/realms';
|
||||
|
||||
/** A button that opens the form for creating a realm or joining one. */
|
||||
export function NewRealmDialog({
|
||||
variant = 'icon',
|
||||
}: {
|
||||
/** "icon" is a small plus for headings; "text" spells it out. */
|
||||
variant?: 'icon' | 'text';
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger
|
||||
render={
|
||||
variant === 'icon' ? (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
aria-label="Add a realm"
|
||||
title="Add a realm"
|
||||
/>
|
||||
) : (
|
||||
<Button variant="outline" />
|
||||
)
|
||||
}
|
||||
>
|
||||
<Plus aria-hidden="true" />
|
||||
{variant === 'text' && 'Create or join a realm'}
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Add a realm</DialogTitle>
|
||||
<DialogDescription>
|
||||
A realm is a place for a community, with cauldrons to talk in and
|
||||
roles for the people who look after it.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
{/* Mounted only while open, so each opening starts from blank forms. */}
|
||||
<CreateForm onDone={() => setOpen(false)} />
|
||||
<Separator />
|
||||
<JoinForm onDone={() => setOpen(false)} />
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function CreateForm({ onDone }: { onDone: () => void }) {
|
||||
const createRealm = useCreateRealm();
|
||||
const navigate = useNavigate();
|
||||
const [name, setName] = useState('');
|
||||
|
||||
return (
|
||||
<form
|
||||
className="grid gap-2"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
createRealm.mutate(name, {
|
||||
onSuccess: (realm) => {
|
||||
onDone();
|
||||
void navigate({
|
||||
to: '/app/r/$realmId',
|
||||
params: { realmId: realm.id },
|
||||
});
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="realm-name">Create a new realm</FieldLabel>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
id="realm-name"
|
||||
value={name}
|
||||
maxLength={REALM_NAME_MAX_LENGTH}
|
||||
placeholder="Its name"
|
||||
autoComplete="off"
|
||||
onChange={(event) => setName(event.target.value)}
|
||||
/>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={name.trim() === '' || createRealm.isPending}
|
||||
>
|
||||
{createRealm.isPending && <Spinner />}
|
||||
Create
|
||||
</Button>
|
||||
</div>
|
||||
</Field>
|
||||
{createRealm.isError && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{errorMessage(
|
||||
createRealm.error,
|
||||
'Could not create the realm. Please try again.',
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function JoinForm({ onDone }: { onDone: () => void }) {
|
||||
const navigate = useNavigate();
|
||||
const [pasted, setPasted] = useState('');
|
||||
const [isInvalid, setIsInvalid] = useState(false);
|
||||
|
||||
return (
|
||||
<form
|
||||
className="grid gap-2"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
const code = inviteCodeFrom(pasted);
|
||||
if (!code) {
|
||||
setIsInvalid(true);
|
||||
return;
|
||||
}
|
||||
onDone();
|
||||
void navigate({ to: '/app/invite/$code', params: { code } });
|
||||
}}
|
||||
>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="realm-invite">Join with an invite</FieldLabel>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
id="realm-invite"
|
||||
value={pasted}
|
||||
placeholder="Paste an invite link"
|
||||
autoComplete="off"
|
||||
aria-invalid={isInvalid}
|
||||
onChange={(event) => {
|
||||
setPasted(event.target.value);
|
||||
setIsInvalid(false);
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
type="submit"
|
||||
variant="outline"
|
||||
disabled={pasted.trim() === ''}
|
||||
>
|
||||
Open
|
||||
</Button>
|
||||
</div>
|
||||
<FieldDescription>
|
||||
Someone in the realm can make you a link.
|
||||
</FieldDescription>
|
||||
</Field>
|
||||
{isInvalid && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
That doesn’t look like an invite link.
|
||||
</p>
|
||||
)}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
Field,
|
||||
FieldContent,
|
||||
FieldDescription,
|
||||
FieldGroup,
|
||||
FieldLabel,
|
||||
} from '@repo/ui/components/field';
|
||||
import { Switch } from '@repo/ui/components/switch';
|
||||
import {
|
||||
allowNotifications,
|
||||
notificationsSupported,
|
||||
setNotificationSettings,
|
||||
useNotificationSettings,
|
||||
} from '@/lib/notifications';
|
||||
import type { NotificationSettings as Settings } from '@/lib/notifications';
|
||||
|
||||
const choices: { key: keyof Settings; label: string; description: string }[] = [
|
||||
{
|
||||
key: 'chats',
|
||||
label: 'Direct and group messages',
|
||||
description: 'When a friend or a group you are in writes.',
|
||||
},
|
||||
{
|
||||
key: 'realms',
|
||||
label: 'Realm messages',
|
||||
description: 'For every message in any cauldron of your realms.',
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* Switches for desktop notifications. They are kept in this browser, since
|
||||
* the browser's own permission is per browser too.
|
||||
*/
|
||||
export function NotificationSettings() {
|
||||
const settings = useNotificationSettings();
|
||||
const [isBlocked, setIsBlocked] = useState(false);
|
||||
const isSupported = notificationsSupported();
|
||||
|
||||
async function change(key: keyof Settings, isOn: boolean) {
|
||||
if (isOn && !(await allowNotifications())) {
|
||||
setIsBlocked(true);
|
||||
return;
|
||||
}
|
||||
setIsBlocked(false);
|
||||
setNotificationSettings({ ...settings, [key]: isOn });
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="flex flex-col gap-4">
|
||||
<header className="flex flex-col gap-1">
|
||||
<h2 className="font-heading text-lg font-semibold">Notifications</h2>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Pop up a notification for new messages while this tab is open but you
|
||||
are looking at something else. Unread counts always show in the app
|
||||
and in the tab's title.
|
||||
</p>
|
||||
</header>
|
||||
{isSupported ? (
|
||||
<FieldGroup>
|
||||
{choices.map((choice) => (
|
||||
<Field key={choice.key} orientation="horizontal">
|
||||
<FieldContent>
|
||||
<FieldLabel htmlFor={`notify-${choice.key}`}>
|
||||
{choice.label}
|
||||
</FieldLabel>
|
||||
<FieldDescription>{choice.description}</FieldDescription>
|
||||
</FieldContent>
|
||||
<Switch
|
||||
id={`notify-${choice.key}`}
|
||||
checked={settings[choice.key]}
|
||||
onCheckedChange={(isOn) => void change(choice.key, isOn)}
|
||||
/>
|
||||
</Field>
|
||||
))}
|
||||
{isBlocked && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
Your browser is blocking notifications for this site. Allow them
|
||||
in the browser's site settings, then try again.
|
||||
</p>
|
||||
)}
|
||||
</FieldGroup>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
This browser doesn't support notifications.
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { UserSummary } from '@repo/contracts';
|
||||
import { UserAvatar } from '@/components/user-avatar';
|
||||
|
||||
/** One person in a list, with room for buttons on the right. */
|
||||
export function PersonRow({
|
||||
user,
|
||||
children,
|
||||
}: {
|
||||
user: UserSummary;
|
||||
children?: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<li className="flex items-center gap-3 py-2">
|
||||
<UserAvatar user={user} />
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate text-sm font-medium">{user.name}</p>
|
||||
{user.username && (
|
||||
<p className="truncate text-xs text-muted-foreground">
|
||||
@{user.username}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-2">{children}</div>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Link } from '@tanstack/react-router';
|
||||
import { cn } from '@repo/ui/lib/utils';
|
||||
import { CallMark } from '@/components/call-mark';
|
||||
import { UnreadDot } from '@/components/unread-dot';
|
||||
import { useCallPlaces } from '@/lib/calls';
|
||||
import { realmsQuery } from '@/lib/realms';
|
||||
|
||||
/** A realm's mark: its initial in a rounded square, to tell it from people. */
|
||||
export function RealmAvatar({
|
||||
name,
|
||||
className,
|
||||
}: {
|
||||
name: string;
|
||||
className?: string;
|
||||
}) {
|
||||
return (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
'flex size-8 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-sm font-medium text-primary',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{name.charAt(0).toUpperCase()}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/** Links to the realms the user is in. Renders nothing when there are none. */
|
||||
export function RealmList({ className }: { className?: string }) {
|
||||
const { data: realms } = useQuery(realmsQuery);
|
||||
const calls = useCallPlaces();
|
||||
if (!realms || realms.length === 0) return null;
|
||||
|
||||
return (
|
||||
<ul className={cn('flex flex-col gap-0.5', className)}>
|
||||
{realms.map((realm) => (
|
||||
<li key={realm.id}>
|
||||
<Link
|
||||
to="/app/r/$realmId"
|
||||
params={{ realmId: realm.id }}
|
||||
className="flex items-center gap-2 rounded-lg px-2 py-1.5 hover:bg-muted data-[status=active]:bg-muted"
|
||||
>
|
||||
<RealmAvatar name={realm.name} />
|
||||
<span className="min-w-0 flex-1 truncate text-sm font-medium">
|
||||
{realm.name}
|
||||
</span>
|
||||
{calls.realmIds.has(realm.id) && <CallMark />}
|
||||
{realm.hasUnread && <UnreadDot label="Unread messages" />}
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { Link } from '@tanstack/react-router';
|
||||
import { buttonVariants } from '@repo/ui/components/button';
|
||||
|
||||
/**
|
||||
* Shown for a realm that doesn't exist or that the user isn't in. Also where
|
||||
* someone lands when they are removed from a realm they have open.
|
||||
*/
|
||||
export function RealmMissing() {
|
||||
return (
|
||||
<div className="flex flex-1 flex-col items-center justify-center gap-3 p-6 text-center">
|
||||
<h1 className="font-heading text-xl font-semibold">Realm not found</h1>
|
||||
<p className="max-w-sm text-sm text-muted-foreground">
|
||||
It doesn't exist, or you aren't in it.
|
||||
</p>
|
||||
<Link to="/app" className={buttonVariants({ variant: 'outline' })}>
|
||||
Back to your conversations
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
import { Link, useNavigate } from '@tanstack/react-router';
|
||||
import type { Realm } from '@repo/contracts';
|
||||
import { Hash, Plus, Settings, UserPlus } from 'lucide-react';
|
||||
import { Badge } from '@repo/ui/components/badge';
|
||||
import { buttonVariants } from '@repo/ui/components/button';
|
||||
import { cn } from '@repo/ui/lib/utils';
|
||||
import { CallMark } from '@/components/call-mark';
|
||||
import { CauldronDialog } from '@/components/cauldron-dialog';
|
||||
import { InviteDialog } from '@/components/invite-dialog';
|
||||
import { useCallPlaces } from '@/lib/calls';
|
||||
import { can, realmMemberCount } from '@/lib/realms';
|
||||
import { formatUnread } from '@/lib/unread';
|
||||
|
||||
/**
|
||||
* A realm's own column: its name, the ways into its settings and invites,
|
||||
* and its cauldrons. Beside the chat on wide screens, a page of its own on
|
||||
* phones.
|
||||
*/
|
||||
export function RealmSidebar({
|
||||
realm,
|
||||
className,
|
||||
}: {
|
||||
realm: Realm;
|
||||
className?: string;
|
||||
}) {
|
||||
const navigate = useNavigate();
|
||||
const calls = useCallPlaces();
|
||||
|
||||
return (
|
||||
<div className={cn('flex min-h-0 flex-col', className)}>
|
||||
<header className="flex items-center gap-1 border-b py-2 pr-2 pl-4">
|
||||
<div className="min-w-0 flex-1">
|
||||
<h1 className="truncate text-sm font-medium">{realm.name}</h1>
|
||||
<p className="truncate text-xs text-muted-foreground">
|
||||
{realmMemberCount(realm.memberCount)}
|
||||
</p>
|
||||
</div>
|
||||
{can(realm, 'createInvites') && (
|
||||
<InviteDialog
|
||||
realmId={realm.id}
|
||||
realmName={realm.name}
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
aria-label="Invite people"
|
||||
title="Invite people"
|
||||
>
|
||||
<UserPlus aria-hidden="true" />
|
||||
</InviteDialog>
|
||||
)}
|
||||
<Link
|
||||
to="/app/r/$realmId/settings"
|
||||
params={{ realmId: realm.id }}
|
||||
aria-label="Realm settings"
|
||||
title="Realm settings"
|
||||
className={buttonVariants({ variant: 'ghost', size: 'icon-sm' })}
|
||||
>
|
||||
<Settings aria-hidden="true" />
|
||||
</Link>
|
||||
</header>
|
||||
|
||||
<nav
|
||||
aria-label="Cauldrons"
|
||||
className="flex min-h-0 flex-1 flex-col gap-1 overflow-y-auto p-2"
|
||||
>
|
||||
<div className="flex items-center justify-between pl-2">
|
||||
<h2 className="text-xs font-medium text-muted-foreground">
|
||||
Cauldrons
|
||||
</h2>
|
||||
{can(realm, 'manageCauldrons') && (
|
||||
<CauldronDialog
|
||||
realmId={realm.id}
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
aria-label="New cauldron"
|
||||
title="New cauldron"
|
||||
onCreated={(cauldron) =>
|
||||
void navigate({
|
||||
to: '/app/r/$realmId/$cauldronId',
|
||||
params: { realmId: realm.id, cauldronId: cauldron.id },
|
||||
})
|
||||
}
|
||||
>
|
||||
<Plus aria-hidden="true" />
|
||||
</CauldronDialog>
|
||||
)}
|
||||
</div>
|
||||
{realm.cauldrons.length === 0 ? (
|
||||
<p className="px-2 py-1 text-sm text-muted-foreground">
|
||||
No cauldrons yet.
|
||||
</p>
|
||||
) : (
|
||||
<ul className="flex flex-col gap-0.5">
|
||||
{realm.cauldrons.map((cauldron) => (
|
||||
<li key={cauldron.id}>
|
||||
<Link
|
||||
to="/app/r/$realmId/$cauldronId"
|
||||
params={{ realmId: realm.id, cauldronId: cauldron.id }}
|
||||
className={cn(
|
||||
'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',
|
||||
cauldron.unreadCount > 0 && 'font-medium text-foreground',
|
||||
)}
|
||||
>
|
||||
<Hash className="size-4 shrink-0" aria-hidden="true" />
|
||||
<span className="min-w-0 flex-1 truncate">
|
||||
{cauldron.name}
|
||||
</span>
|
||||
{calls.conversationIds.has(cauldron.id) && <CallMark />}
|
||||
{cauldron.unreadCount > 0 && (
|
||||
<Badge
|
||||
aria-label={`${formatUnread(cauldron.unreadCount)} unread`}
|
||||
>
|
||||
{formatUnread(cauldron.unreadCount)}
|
||||
</Badge>
|
||||
)}
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</nav>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
import { useState } from 'react';
|
||||
import { REALM_PERMISSIONS, ROLE_NAME_MAX_LENGTH } from '@repo/contracts';
|
||||
import type { Realm, RealmPermission, RealmRole } from '@repo/contracts';
|
||||
import { Button } from '@repo/ui/components/button';
|
||||
import { Checkbox } from '@repo/ui/components/checkbox';
|
||||
import {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@repo/ui/components/dialog';
|
||||
import { Field, FieldLabel } from '@repo/ui/components/field';
|
||||
import { Input } from '@repo/ui/components/input';
|
||||
import { Spinner } from '@repo/ui/components/spinner';
|
||||
import type { TriggerButtonProps } from '@/components/trigger-button';
|
||||
import { errorMessage } from '@/lib/errors';
|
||||
import {
|
||||
PERMISSION_LABELS,
|
||||
can,
|
||||
useCreateRole,
|
||||
useUpdateRole,
|
||||
} from '@/lib/realms';
|
||||
|
||||
interface RoleDialogProps extends TriggerButtonProps {
|
||||
realm: Realm;
|
||||
/** The role to change; a new one is created without it. */
|
||||
role?: RealmRole;
|
||||
}
|
||||
|
||||
/** A button that opens the form for a new role or an existing one. */
|
||||
export function RoleDialog({
|
||||
realm,
|
||||
role,
|
||||
children,
|
||||
...button
|
||||
}: RoleDialogProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger render={<Button {...button} />}>{children}</DialogTrigger>
|
||||
<DialogContent className="max-h-[85svh] overflow-y-auto sm:max-w-md">
|
||||
{/* Mounted only while open, so each opening starts from what is saved. */}
|
||||
<RoleForm realm={realm} role={role} onDone={() => setOpen(false)} />
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function RoleForm({
|
||||
realm,
|
||||
role,
|
||||
onDone,
|
||||
}: {
|
||||
realm: Realm;
|
||||
role?: RealmRole;
|
||||
onDone: () => void;
|
||||
}) {
|
||||
const create = useCreateRole(realm.id);
|
||||
const update = useUpdateRole(realm.id);
|
||||
const [name, setName] = useState(role?.name ?? '');
|
||||
const [permissions, setPermissions] = useState<RealmPermission[]>(
|
||||
role?.permissions ?? [],
|
||||
);
|
||||
const failure = create.error ?? update.error;
|
||||
const isPending = create.isPending || update.isPending;
|
||||
|
||||
function toggle(permission: RealmPermission, checked: boolean) {
|
||||
setPermissions((current) =>
|
||||
checked
|
||||
? [...current, permission]
|
||||
: current.filter((item) => item !== permission),
|
||||
);
|
||||
}
|
||||
|
||||
function handleSubmit(event: React.FormEvent) {
|
||||
event.preventDefault();
|
||||
const options = { onSuccess: onDone };
|
||||
if (!role) create.mutate({ name, permissions }, options);
|
||||
else if (role.isDefault) {
|
||||
// Its name is fixed, so only what it allows is sent.
|
||||
update.mutate({ roleId: role.id, permissions }, options);
|
||||
} else update.mutate({ roleId: role.id, name, permissions }, options);
|
||||
}
|
||||
|
||||
return (
|
||||
<form className="grid gap-4" onSubmit={handleSubmit}>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{role ? `Edit ${role.name}` : 'New role'}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{role?.isDefault
|
||||
? 'Every member has this role, so this is what anyone in the realm may do.'
|
||||
: 'Members get what all of their roles allow, on top of what everyone may do.'}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<Field>
|
||||
<FieldLabel htmlFor="role-name">Name</FieldLabel>
|
||||
<Input
|
||||
id="role-name"
|
||||
value={name}
|
||||
maxLength={ROLE_NAME_MAX_LENGTH}
|
||||
placeholder="Moderator"
|
||||
autoComplete="off"
|
||||
disabled={role?.isDefault}
|
||||
onChange={(event) => setName(event.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<fieldset className="grid gap-1">
|
||||
<legend className="pb-1 text-sm font-medium">Allows</legend>
|
||||
{REALM_PERMISSIONS.map((permission) => {
|
||||
const label = PERMISSION_LABELS[permission];
|
||||
// Nobody hands out what they can't do themselves.
|
||||
const isOutOfReach = !can(realm, permission);
|
||||
return (
|
||||
<label
|
||||
key={permission}
|
||||
className="grid cursor-pointer grid-cols-[auto_1fr] gap-x-3 rounded-lg px-2 py-1.5 hover:bg-muted has-disabled:cursor-not-allowed has-disabled:opacity-60"
|
||||
>
|
||||
<Checkbox
|
||||
aria-label={label.name}
|
||||
className="row-span-2 mt-0.5"
|
||||
checked={permissions.includes(permission)}
|
||||
disabled={isOutOfReach}
|
||||
onCheckedChange={(next) => toggle(permission, next)}
|
||||
/>
|
||||
<span className="min-w-0 text-sm">{label.name}</span>
|
||||
<span className="col-start-2 min-w-0 text-xs text-muted-foreground">
|
||||
{isOutOfReach
|
||||
? 'You can’t do this yourself, so you can’t give it.'
|
||||
: label.description}
|
||||
</span>
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
</fieldset>
|
||||
|
||||
{failure && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{errorMessage(failure)}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<DialogFooter>
|
||||
<DialogClose render={<Button type="button" variant="outline" />}>
|
||||
Cancel
|
||||
</DialogClose>
|
||||
<Button type="submit" disabled={name.trim() === '' || isPending}>
|
||||
{isPending && <Spinner />}
|
||||
{role ? 'Save' : 'Create role'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import type { Button } from '@repo/ui/components/button';
|
||||
|
||||
/**
|
||||
* What a dialog component takes to draw the button that opens it: the
|
||||
* button's look and, as children, what it says.
|
||||
*/
|
||||
export interface TriggerButtonProps extends Pick<
|
||||
React.ComponentProps<typeof Button>,
|
||||
'variant' | 'size' | 'className' | 'disabled' | 'aria-label' | 'title'
|
||||
> {
|
||||
children: React.ReactNode;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { cn } from '@repo/ui/lib/utils';
|
||||
|
||||
/** A small mark for "something here is unread", when there is no count. */
|
||||
export function UnreadDot({
|
||||
label,
|
||||
className,
|
||||
}: {
|
||||
label: string;
|
||||
className?: string;
|
||||
}) {
|
||||
return (
|
||||
<span className={cn('size-2 shrink-0 rounded-full bg-primary', className)}>
|
||||
<span className="sr-only">{label}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import {
|
||||
Avatar,
|
||||
AvatarFallback,
|
||||
AvatarImage,
|
||||
} from '@repo/ui/components/avatar';
|
||||
|
||||
interface UserAvatarProps {
|
||||
user: { name: string; image: string | null };
|
||||
size?: 'default' | 'sm' | 'lg';
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/** A user's picture, or their initial when they have none. */
|
||||
export function UserAvatar({ user, size, className }: UserAvatarProps) {
|
||||
return (
|
||||
<Avatar size={size} className={className}>
|
||||
{user.image && <AvatarImage src={user.image} alt="" />}
|
||||
<AvatarFallback>{user.name.charAt(0).toUpperCase()}</AvatarFallback>
|
||||
</Avatar>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
export const apiUrl: string =
|
||||
import.meta.env.VITE_API_URL ?? 'http://localhost:3001';
|
||||
|
||||
/** The API answered with an error status; `message` is safe to show. */
|
||||
export class ApiError extends Error {
|
||||
readonly status: number;
|
||||
|
||||
constructor(status: number, message: string) {
|
||||
super(message);
|
||||
this.name = 'ApiError';
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
interface RequestOptions<T> {
|
||||
/** A schema from @repo/contracts; the response is checked against it. */
|
||||
schema: { parse: (data: unknown) => T };
|
||||
method?: 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE';
|
||||
/** Sent as JSON. */
|
||||
body?: unknown;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
/** Calls the API as the signed-in user (the session cookie goes along). */
|
||||
export async function api<T>(
|
||||
path: string,
|
||||
{ schema, method = 'GET', body, signal }: RequestOptions<T>,
|
||||
): Promise<T> {
|
||||
const response = await fetch(`${apiUrl}${path}`, {
|
||||
method,
|
||||
signal,
|
||||
credentials: 'include',
|
||||
headers:
|
||||
body === undefined ? undefined : { 'Content-Type': 'application/json' },
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new ApiError(response.status, await readErrorMessage(response));
|
||||
}
|
||||
// 204 has no body to read.
|
||||
return schema.parse(
|
||||
response.status === 204 ? undefined : await response.json(),
|
||||
);
|
||||
}
|
||||
|
||||
/** The `schema` for routes that answer 204 with no body. */
|
||||
export const noContent = { parse: (): void => undefined };
|
||||
|
||||
// Errors come back as { statusCode, message, error }, where message is a
|
||||
// string or, for validation errors, a list of strings.
|
||||
async function readErrorMessage(response: Response): Promise<string> {
|
||||
const fallback = response.statusText || 'Something went wrong.';
|
||||
try {
|
||||
const data: unknown = await response.json();
|
||||
if (typeof data !== 'object' || data === null || !('message' in data)) {
|
||||
return fallback;
|
||||
}
|
||||
const { message } = data;
|
||||
if (typeof message === 'string') return message;
|
||||
if (Array.isArray(message)) return message.join(' ');
|
||||
return fallback;
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import {
|
||||
ATTACHMENT_MAX_SIZE,
|
||||
INLINE_IMAGE_TYPES,
|
||||
attachmentUploadSchema,
|
||||
} from '@repo/contracts';
|
||||
import type { Attachment } from '@repo/contracts';
|
||||
import { ApiError, api, apiUrl, noContent } from '@/lib/api';
|
||||
|
||||
/**
|
||||
* Where a file is fetched from: usable as an image source or a link. The
|
||||
* API checks that the signed-in user can read the message it is on.
|
||||
*/
|
||||
export function attachmentUrl(attachmentId: string): string {
|
||||
return `${apiUrl}/attachments/${attachmentId}`;
|
||||
}
|
||||
|
||||
/** "840 B", "12 KB", "3.4 MB". */
|
||||
export function formatFileSize(bytes: number): string {
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
|
||||
return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
|
||||
}
|
||||
|
||||
/** Why a file can't be attached, in words to show; nothing when it can. */
|
||||
export function fileProblem(file: File): string | undefined {
|
||||
if (file.size === 0) return `“${file.name}” is empty.`;
|
||||
if (file.size > ATTACHMENT_MAX_SIZE) {
|
||||
return `“${file.name}” is too big. Files can be at most ${formatFileSize(ATTACHMENT_MAX_SIZE)}.`;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** A picture's size in pixels; nothing for other files or unreadable ones. */
|
||||
async function pictureSize(
|
||||
file: File,
|
||||
): Promise<{ width: number; height: number } | undefined> {
|
||||
if (!INLINE_IMAGE_TYPES.includes(file.type)) return undefined;
|
||||
try {
|
||||
const bitmap = await createImageBitmap(file);
|
||||
const size = { width: bitmap.width, height: bitmap.height };
|
||||
bitmap.close();
|
||||
return size;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Uploads a file for a message that is about to be sent: tells the API
|
||||
* about it, then sends the bytes to the address the API answers with (the
|
||||
* storage itself, so no cookies go along). The attachment's id then goes in
|
||||
* the message.
|
||||
*/
|
||||
export async function uploadAttachment(
|
||||
file: File,
|
||||
signal?: AbortSignal,
|
||||
): Promise<Attachment> {
|
||||
const { attachment, upload } = await api('/attachments', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
filename: file.name,
|
||||
contentType: file.type || 'application/octet-stream',
|
||||
size: file.size,
|
||||
...(await pictureSize(file)),
|
||||
},
|
||||
schema: attachmentUploadSchema,
|
||||
signal,
|
||||
});
|
||||
const response = await fetch(upload.url, {
|
||||
method: upload.method,
|
||||
headers: upload.headers,
|
||||
body: file,
|
||||
signal,
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new ApiError(response.status, `Could not upload “${file.name}”.`);
|
||||
}
|
||||
return attachment;
|
||||
}
|
||||
|
||||
/** Takes back an upload that won't be sent after all. */
|
||||
export function discardAttachment(attachmentId: string): Promise<void> {
|
||||
return api(`/attachments/${attachmentId}`, {
|
||||
method: 'DELETE',
|
||||
schema: noContent,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { usernameClient } from 'better-auth/client/plugins';
|
||||
import { createAuthClient } from 'better-auth/react';
|
||||
import { apiUrl } from '@/lib/api';
|
||||
|
||||
export const authClient = createAuthClient({
|
||||
baseURL: apiUrl,
|
||||
// Mirrors the username plugin options in apps/api/src/auth/auth.ts.
|
||||
plugins: [usernameClient({ displayUsername: false })],
|
||||
});
|
||||
@@ -0,0 +1,131 @@
|
||||
import { useSyncExternalStore } from 'react';
|
||||
import { queryOptions, useQuery } from '@tanstack/react-query';
|
||||
import type { QueryClient } from '@tanstack/react-query';
|
||||
import { callAccessSchema, callsOverviewSchema } from '@repo/contracts';
|
||||
import type { Call, CallAccess } from '@repo/contracts';
|
||||
import { api } from '@/lib/api';
|
||||
|
||||
/**
|
||||
* The calls going on in the user's conversations and cauldrons, and whether
|
||||
* the server has calls at all. Kept current by "call:changed" events.
|
||||
*/
|
||||
export const callsQuery = queryOptions({
|
||||
queryKey: ['calls'],
|
||||
queryFn: ({ signal }) =>
|
||||
api('/calls', { schema: callsOverviewSchema, signal }),
|
||||
});
|
||||
|
||||
/** Asks to join the call of a conversation or cauldron, starting it if need be. */
|
||||
export function requestCallAccess(conversationId: string): Promise<CallAccess> {
|
||||
return api(`/conversations/${conversationId}/call`, {
|
||||
method: 'POST',
|
||||
schema: callAccessSchema,
|
||||
});
|
||||
}
|
||||
|
||||
/** False until known, and when the server has no calls set up. */
|
||||
export function useCallsEnabled(): boolean {
|
||||
const { data } = useQuery(callsQuery);
|
||||
return data?.enabled ?? false;
|
||||
}
|
||||
|
||||
/** The call going on in a conversation or cauldron, if there is one. */
|
||||
export function useCallIn(conversationId: string): Call | undefined {
|
||||
const { data } = useQuery(callsQuery);
|
||||
return data?.calls.find((call) => call.conversationId === conversationId);
|
||||
}
|
||||
|
||||
/** The ids of the conversations and cauldrons with a call going on. */
|
||||
export function useCallPlaces(): {
|
||||
conversationIds: ReadonlySet<string>;
|
||||
realmIds: ReadonlySet<string>;
|
||||
} {
|
||||
const { data } = useQuery(callsQuery);
|
||||
const calls = data?.calls ?? [];
|
||||
return {
|
||||
conversationIds: new Set(calls.map((call) => call.conversationId)),
|
||||
realmIds: new Set(calls.flatMap((call) => call.realmId ?? [])),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Folds a "call:changed" event into the cache. Answers whether it is news
|
||||
* of a call starting: one the cache was loaded without.
|
||||
*/
|
||||
export function applyCallChange(queryClient: QueryClient, call: Call): boolean {
|
||||
const before = queryClient.getQueryData(callsQuery.queryKey);
|
||||
if (!before) return false;
|
||||
const others = before.calls.filter(
|
||||
(item) => item.conversationId !== call.conversationId,
|
||||
);
|
||||
const isOver = call.participants.length === 0;
|
||||
queryClient.setQueryData(callsQuery.queryKey, {
|
||||
...before,
|
||||
calls: isOver ? others : [...others, call],
|
||||
});
|
||||
return !isOver && others.length === before.calls.length;
|
||||
}
|
||||
|
||||
/** "Ana is in a call", "Ana and Ben are in a call", "Ana and 2 others are in a call". */
|
||||
export function callSummary(call: Call): string {
|
||||
const [first, second, ...rest] = call.participants.map(
|
||||
(participant) => participant.name,
|
||||
);
|
||||
if (!first) return 'Nobody is in the call';
|
||||
if (!second) return `${first} is in a call`;
|
||||
if (rest.length === 0) return `${first} and ${second} are in a call`;
|
||||
return `${first} and ${rest.length + 1} others are in a call`;
|
||||
}
|
||||
|
||||
// Calls someone just started in one of the user's chats, which the app
|
||||
// offers to join for a while: "ringing". Not part of the query cache
|
||||
// because it is about this tab's moment, not about the server's state.
|
||||
|
||||
/** How long a call is offered before the offer goes away by itself. */
|
||||
const RING_MS = 30 * 1000;
|
||||
|
||||
let ringing: readonly Call[] = [];
|
||||
const timers = new Map<string, ReturnType<typeof setTimeout>>();
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
function setRinging(next: readonly Call[]) {
|
||||
ringing = next;
|
||||
for (const listener of listeners) listener();
|
||||
}
|
||||
|
||||
/** Offers a call that just started to the user. */
|
||||
export function ring(call: Call) {
|
||||
stopRinging(call.conversationId);
|
||||
setRinging([...ringing, call]);
|
||||
timers.set(
|
||||
call.conversationId,
|
||||
setTimeout(() => stopRinging(call.conversationId), RING_MS),
|
||||
);
|
||||
}
|
||||
|
||||
/** Takes the offer back: answered, dismissed, over, or run out. */
|
||||
export function stopRinging(conversationId: string) {
|
||||
clearTimeout(timers.get(conversationId));
|
||||
timers.delete(conversationId);
|
||||
if (ringing.some((call) => call.conversationId === conversationId)) {
|
||||
setRinging(
|
||||
ringing.filter((call) => call.conversationId !== conversationId),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function subscribe(onChange: () => void) {
|
||||
listeners.add(onChange);
|
||||
return () => listeners.delete(onChange);
|
||||
}
|
||||
|
||||
const NONE: readonly Call[] = [];
|
||||
|
||||
/** The calls being offered to the user right now, oldest first. */
|
||||
export function useRinging(): readonly Call[] {
|
||||
return useSyncExternalStore(
|
||||
subscribe,
|
||||
() => ringing,
|
||||
() => NONE,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,401 @@
|
||||
import {
|
||||
infiniteQueryOptions,
|
||||
queryOptions,
|
||||
useMutation,
|
||||
useQueryClient,
|
||||
} from '@tanstack/react-query';
|
||||
import type { QueryClient } from '@tanstack/react-query';
|
||||
import {
|
||||
conversationListSchema,
|
||||
conversationSchema,
|
||||
messagePageSchema,
|
||||
messageSchema,
|
||||
} from '@repo/contracts';
|
||||
import type {
|
||||
Conversation,
|
||||
CreateGroup,
|
||||
Message,
|
||||
MessageDeletion,
|
||||
Reaction,
|
||||
ReactionChange,
|
||||
UserSummary,
|
||||
} from '@repo/contracts';
|
||||
import { api, noContent } from '@/lib/api';
|
||||
import { realmQuery, realmsQuery } from '@/lib/realms';
|
||||
|
||||
/** The signed-in user's conversations, most recently active first. */
|
||||
export const conversationsQuery = queryOptions({
|
||||
queryKey: ['conversations', 'list'],
|
||||
queryFn: ({ signal }) =>
|
||||
api('/conversations', { schema: conversationListSchema, signal }),
|
||||
});
|
||||
|
||||
/**
|
||||
* A conversation's history. Pages run from newest to oldest and so do the
|
||||
* messages inside each page; `chronological()` turns them around for display.
|
||||
*/
|
||||
export const messagesQuery = (conversationId: string) =>
|
||||
infiniteQueryOptions({
|
||||
queryKey: ['conversations', 'messages', conversationId],
|
||||
queryFn: ({ pageParam, signal }) =>
|
||||
api(
|
||||
`/conversations/${conversationId}/messages${pageParam ? `?before=${pageParam}` : ''}`,
|
||||
{ schema: messagePageSchema, signal },
|
||||
),
|
||||
initialPageParam: null as string | null,
|
||||
getNextPageParam: (lastPage) => lastPage.nextCursor,
|
||||
});
|
||||
|
||||
/** Oldest first, the order a chat is read in. */
|
||||
export function chronological(pages: { items: Message[] }[]): Message[] {
|
||||
return pages.flatMap((page) => page.items).reverse();
|
||||
}
|
||||
|
||||
/** In a direct conversation: the person who isn't the signed-in user. */
|
||||
export function otherMember(
|
||||
conversation: Conversation,
|
||||
ownId: string,
|
||||
): UserSummary | undefined {
|
||||
return conversation.members.find((member) => member.id !== ownId);
|
||||
}
|
||||
|
||||
/**
|
||||
* What to call a conversation: the other person, the group's name or, for a
|
||||
* group without one, the people in it.
|
||||
*/
|
||||
export function conversationTitle(
|
||||
conversation: Conversation,
|
||||
ownId: string,
|
||||
): string {
|
||||
const others = conversation.members.filter((member) => member.id !== ownId);
|
||||
if (conversation.type === 'direct') {
|
||||
return others.at(0)?.name ?? 'Unknown user';
|
||||
}
|
||||
if (conversation.name) return conversation.name;
|
||||
return others.length > 0
|
||||
? others.map((member) => member.name).join(', ')
|
||||
: 'Just you';
|
||||
}
|
||||
|
||||
/** "1 member", "3 members". */
|
||||
export function memberCount(conversation: Conversation): string {
|
||||
const count = conversation.members.length;
|
||||
return count === 1 ? '1 member' : `${count} members`;
|
||||
}
|
||||
|
||||
/** A message in a line: its text, or what was attached when it has none. */
|
||||
export function messagePreview(message: Message): string {
|
||||
if (message.content) return message.content;
|
||||
const count = message.attachments.length;
|
||||
return count === 1 ? message.attachments[0].filename : `${count} files`;
|
||||
}
|
||||
|
||||
/** Replaces a conversation in the loaded list, or puts a new one on top. */
|
||||
function putConversationInCache(
|
||||
queryClient: QueryClient,
|
||||
conversation: Conversation,
|
||||
) {
|
||||
queryClient.setQueryData(conversationsQuery.queryKey, (conversations) => {
|
||||
if (!conversations) return conversations;
|
||||
return conversations.some((item) => item.id === conversation.id)
|
||||
? conversations.map((item) =>
|
||||
item.id === conversation.id ? conversation : item,
|
||||
)
|
||||
: [conversation, ...conversations];
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts a new message at the end of its conversation's (or cauldron's)
|
||||
* history, if that is loaded. Called for the answer to a send and for
|
||||
* "message:created" from the socket, which may both carry the same message,
|
||||
* so it does nothing the second time.
|
||||
*/
|
||||
export function addMessageToHistory(
|
||||
queryClient: QueryClient,
|
||||
message: Message,
|
||||
) {
|
||||
queryClient.setQueryData(
|
||||
messagesQuery(message.conversationId).queryKey,
|
||||
(history) => {
|
||||
if (!history) return history;
|
||||
const known = history.pages.some((page) =>
|
||||
page.items.some((item) => item.id === message.id),
|
||||
);
|
||||
if (known) return history;
|
||||
const [newest, ...older] = history.pages;
|
||||
return {
|
||||
...history,
|
||||
pages: [{ ...newest, items: [message, ...newest.items] }, ...older],
|
||||
};
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A new message in a direct or group chat: into its history and to the top
|
||||
* of the conversation list. Like `addMessageToHistory`, safe to call twice.
|
||||
*/
|
||||
export function addMessageToCache(queryClient: QueryClient, message: Message) {
|
||||
addMessageToHistory(queryClient, message);
|
||||
|
||||
const conversations = queryClient.getQueryData(conversationsQuery.queryKey);
|
||||
const conversation = conversations?.find(
|
||||
(item) => item.id === message.conversationId,
|
||||
);
|
||||
if (!conversations || !conversation) {
|
||||
// A conversation this tab hasn't seen yet (someone's first message).
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: conversationsQuery.queryKey,
|
||||
});
|
||||
return;
|
||||
}
|
||||
// Ids are time-ordered, so this also ignores a message older than the one
|
||||
// already shown.
|
||||
if (conversation.lastMessage && conversation.lastMessage.id >= message.id) {
|
||||
return;
|
||||
}
|
||||
queryClient.setQueryData(conversationsQuery.queryKey, [
|
||||
{
|
||||
...conversation,
|
||||
lastMessage: message,
|
||||
lastActivityAt: message.createdAt,
|
||||
},
|
||||
...conversations.filter((item) => item.id !== conversation.id),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes a deleted message out of the loaded history. What the lists show of
|
||||
* it (the last message of a chat, unread counts) is fetched again, since
|
||||
* what comes in its place isn't known here. Safe to call twice: once for
|
||||
* the user's own click, once for the socket's echo.
|
||||
*/
|
||||
export function removeMessageFromCache(
|
||||
queryClient: QueryClient,
|
||||
{ conversationId, messageId, realmId }: MessageDeletion,
|
||||
) {
|
||||
queryClient.setQueryData(
|
||||
messagesQuery(conversationId).queryKey,
|
||||
(history) =>
|
||||
history && {
|
||||
...history,
|
||||
pages: history.pages.map((page) => ({
|
||||
...page,
|
||||
items: page.items.filter((item) => item.id !== messageId),
|
||||
})),
|
||||
},
|
||||
);
|
||||
if (!realmId) {
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: conversationsQuery.queryKey,
|
||||
});
|
||||
return;
|
||||
}
|
||||
// A realm's details carry the unread counts of its cauldrons, and the
|
||||
// list of realms whether any of them has some.
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: realmQuery(realmId).queryKey,
|
||||
});
|
||||
void queryClient.invalidateQueries({ queryKey: realmsQuery.queryKey });
|
||||
}
|
||||
|
||||
/** Deletes a message for everyone who can read its conversation. */
|
||||
export function useDeleteMessage(
|
||||
conversationId: string,
|
||||
realmId: string | null,
|
||||
) {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (messageId: string) =>
|
||||
api(`/conversations/${conversationId}/messages/${messageId}`, {
|
||||
method: 'DELETE',
|
||||
schema: noContent,
|
||||
}),
|
||||
onSuccess: (_, messageId) =>
|
||||
removeMessageFromCache(queryClient, {
|
||||
conversationId,
|
||||
messageId,
|
||||
realmId,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
/** Opens the chat with a friend, creating it on first use. */
|
||||
export function useOpenDirectConversation() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (userId: string) =>
|
||||
api('/conversations/direct', {
|
||||
method: 'POST',
|
||||
body: { userId },
|
||||
schema: conversationSchema,
|
||||
}),
|
||||
onSuccess: (conversation) =>
|
||||
putConversationInCache(queryClient, conversation),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Posts in a conversation, or in a cauldron when `inRealm` is set: cauldrons
|
||||
* aren't in the conversation list, so only their history is updated.
|
||||
*/
|
||||
export function useSendMessage(conversationId: string, inRealm = false) {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (body: { content: string; attachmentIds: string[] }) =>
|
||||
api(`/conversations/${conversationId}/messages`, {
|
||||
method: 'POST',
|
||||
body,
|
||||
schema: messageSchema,
|
||||
}),
|
||||
onSuccess: (message) =>
|
||||
inRealm
|
||||
? addMessageToHistory(queryClient, message)
|
||||
: addMessageToCache(queryClient, message),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a reaction someone added or took back to the loaded history.
|
||||
* The change carries the emoji's new count, so applying it twice (once for
|
||||
* the user's own click, once for the socket's echo) does no harm.
|
||||
*/
|
||||
export function applyReactionChange(
|
||||
queryClient: QueryClient,
|
||||
change: ReactionChange,
|
||||
ownId: string | undefined,
|
||||
) {
|
||||
const update = (reactions: Reaction[]): Reaction[] => {
|
||||
const existing = reactions.find((item) => item.emoji === change.emoji);
|
||||
const mine =
|
||||
change.userId === ownId ? change.added : (existing?.mine ?? false);
|
||||
if (change.count <= 0) {
|
||||
return reactions.filter((item) => item.emoji !== change.emoji);
|
||||
}
|
||||
const next = { emoji: change.emoji, count: change.count, mine };
|
||||
return existing
|
||||
? reactions.map((item) => (item === existing ? next : item))
|
||||
: [...reactions, next];
|
||||
};
|
||||
queryClient.setQueryData(
|
||||
messagesQuery(change.conversationId).queryKey,
|
||||
(history) =>
|
||||
history && {
|
||||
...history,
|
||||
pages: history.pages.map((page) => ({
|
||||
...page,
|
||||
items: page.items.map((item) =>
|
||||
item.id === change.messageId
|
||||
? { ...item, reactions: update(item.reactions) }
|
||||
: item,
|
||||
),
|
||||
})),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the user's emoji to a message, or takes it back if it is there.
|
||||
* The chat shows it at once; if the API refuses, the history is fetched
|
||||
* again to put things right.
|
||||
*/
|
||||
export function useToggleReaction(conversationId: string, ownId: string) {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: ({ message, emoji }: { message: Message; emoji: string }) => {
|
||||
const mine = message.reactions.some(
|
||||
(item) => item.emoji === emoji && item.mine,
|
||||
);
|
||||
return api(
|
||||
`/conversations/${conversationId}/messages/${message.id}/reactions/${encodeURIComponent(emoji)}`,
|
||||
{ method: mine ? 'DELETE' : 'PUT', schema: noContent },
|
||||
);
|
||||
},
|
||||
onMutate: ({ message, emoji }) => {
|
||||
const existing = message.reactions.find((item) => item.emoji === emoji);
|
||||
const added = !existing?.mine;
|
||||
applyReactionChange(
|
||||
queryClient,
|
||||
{
|
||||
conversationId,
|
||||
messageId: message.id,
|
||||
emoji,
|
||||
count: (existing?.count ?? 0) + (added ? 1 : -1),
|
||||
userId: ownId,
|
||||
added,
|
||||
},
|
||||
ownId,
|
||||
);
|
||||
},
|
||||
onError: () =>
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: messagesQuery(conversationId).queryKey,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
// The group changes below also reach everyone in the group as
|
||||
// "conversations:changed" over the socket, which refetches the list.
|
||||
|
||||
/** Starts a group chat with some friends. */
|
||||
export function useCreateGroup() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (body: CreateGroup) =>
|
||||
api('/conversations/group', {
|
||||
method: 'POST',
|
||||
body,
|
||||
schema: conversationSchema,
|
||||
}),
|
||||
onSuccess: (conversation) =>
|
||||
putConversationInCache(queryClient, conversation),
|
||||
});
|
||||
}
|
||||
|
||||
export function useRenameGroup(conversationId: string) {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (name: string) =>
|
||||
api(`/conversations/${conversationId}`, {
|
||||
method: 'PATCH',
|
||||
body: { name },
|
||||
schema: conversationSchema,
|
||||
}),
|
||||
onSuccess: (conversation) =>
|
||||
putConversationInCache(queryClient, conversation),
|
||||
});
|
||||
}
|
||||
|
||||
export function useAddGroupMembers(conversationId: string) {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (userIds: string[]) =>
|
||||
api(`/conversations/${conversationId}/members`, {
|
||||
method: 'POST',
|
||||
body: { userIds },
|
||||
schema: conversationSchema,
|
||||
}),
|
||||
onSuccess: (conversation) =>
|
||||
putConversationInCache(queryClient, conversation),
|
||||
});
|
||||
}
|
||||
|
||||
/** Takes someone out of a group; with the user's own id, leaves it. */
|
||||
export function useRemoveGroupMember(conversationId: string) {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (userId: string) =>
|
||||
api(`/conversations/${conversationId}/members/${userId}`, {
|
||||
method: 'DELETE',
|
||||
schema: noContent,
|
||||
}),
|
||||
// Not awaited: callers move on (say, away from a group they left)
|
||||
// without waiting for the list to come back.
|
||||
onSuccess: () => {
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: conversationsQuery.queryKey,
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { toast } from '@repo/ui/components/toast';
|
||||
import { ApiError } from '@/lib/api';
|
||||
|
||||
/** The API's own words when it gave any, a general apology otherwise. */
|
||||
export function errorMessage(
|
||||
error: unknown,
|
||||
fallback = 'Something went wrong. Please try again.',
|
||||
): string {
|
||||
return error instanceof ApiError ? error.message : fallback;
|
||||
}
|
||||
|
||||
/** Shows a failed action as a toast. */
|
||||
export function showError(error: unknown) {
|
||||
toast.add({ title: errorMessage(error), type: 'error' });
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
const timeFormat = new Intl.DateTimeFormat(undefined, { timeStyle: 'short' });
|
||||
const dateTimeFormat = new Intl.DateTimeFormat(undefined, {
|
||||
dateStyle: 'medium',
|
||||
timeStyle: 'short',
|
||||
});
|
||||
|
||||
/** "14:05" for today, "2 Dec 2026, 14:05" for any other day. */
|
||||
export function formatMessageTime(iso: string): string {
|
||||
const date = new Date(iso);
|
||||
const isToday = date.toDateString() === new Date().toDateString();
|
||||
return isToday ? timeFormat.format(date) : dateTimeFormat.format(date);
|
||||
}
|
||||
|
||||
/** "2 Dec 2026, 14:05", whatever the day. */
|
||||
export function formatDateTime(iso: string): string {
|
||||
return dateTimeFormat.format(new Date(iso));
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import {
|
||||
queryOptions,
|
||||
useMutation,
|
||||
useQueryClient,
|
||||
} from '@tanstack/react-query';
|
||||
import {
|
||||
friendRequestResultSchema,
|
||||
friendsOverviewSchema,
|
||||
} from '@repo/contracts';
|
||||
import type { SendFriendRequest } from '@repo/contracts';
|
||||
import { api, noContent } from '@/lib/api';
|
||||
|
||||
/** Friends, the requests waiting in either direction, and who is blocked. */
|
||||
export const friendsQuery = queryOptions({
|
||||
queryKey: ['friends'],
|
||||
queryFn: ({ signal }) =>
|
||||
api('/friends', { schema: friendsOverviewSchema, signal }),
|
||||
});
|
||||
|
||||
// Each change refetches the overview. The API also sends "friends:changed"
|
||||
// over the socket, which does the same for the other person and other tabs.
|
||||
function useRefreshFriends() {
|
||||
const queryClient = useQueryClient();
|
||||
return () =>
|
||||
queryClient.invalidateQueries({ queryKey: friendsQuery.queryKey });
|
||||
}
|
||||
|
||||
export function useSendFriendRequest() {
|
||||
const refresh = useRefreshFriends();
|
||||
return useMutation({
|
||||
mutationFn: (body: SendFriendRequest) =>
|
||||
api('/friends/requests', {
|
||||
method: 'POST',
|
||||
body,
|
||||
schema: friendRequestResultSchema,
|
||||
}),
|
||||
onSuccess: refresh,
|
||||
});
|
||||
}
|
||||
|
||||
export function useAcceptFriendRequest() {
|
||||
const refresh = useRefreshFriends();
|
||||
return useMutation({
|
||||
mutationFn: (userId: string) =>
|
||||
api(`/friends/requests/${userId}/accept`, {
|
||||
method: 'POST',
|
||||
schema: noContent,
|
||||
}),
|
||||
onSuccess: refresh,
|
||||
});
|
||||
}
|
||||
|
||||
/** Unfriends, declines an incoming request or cancels an outgoing one. */
|
||||
export function useRemoveFriend() {
|
||||
const refresh = useRefreshFriends();
|
||||
return useMutation({
|
||||
mutationFn: (userId: string) =>
|
||||
api(`/friends/${userId}`, { method: 'DELETE', schema: noContent }),
|
||||
onSuccess: refresh,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Blocks someone: the friendship or any request between the two ends, and
|
||||
* they can't send another or message the user until it is lifted.
|
||||
*/
|
||||
export function useBlockUser() {
|
||||
const refresh = useRefreshFriends();
|
||||
return useMutation({
|
||||
mutationFn: (userId: string) =>
|
||||
api(`/friends/blocks/${userId}`, { method: 'PUT', schema: noContent }),
|
||||
onSuccess: refresh,
|
||||
});
|
||||
}
|
||||
|
||||
/** Lifts a block. The two aren't friends again until one asks. */
|
||||
export function useUnblockUser() {
|
||||
const refresh = useRefreshFriends();
|
||||
return useMutation({
|
||||
mutationFn: (userId: string) =>
|
||||
api(`/friends/blocks/${userId}`, { method: 'DELETE', schema: noContent }),
|
||||
onSuccess: refresh,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
import { useSyncExternalStore } from 'react';
|
||||
import type { QueryClient } from '@tanstack/react-query';
|
||||
import type { Call, Message } from '@repo/contracts';
|
||||
import { conversationTitle, conversationsQuery } from '@/lib/conversations';
|
||||
import { realmQuery, realmsQuery } from '@/lib/realms';
|
||||
import { isAttentive } from '@/lib/unread';
|
||||
|
||||
/** Which messages may pop up as desktop notifications. Kept per browser. */
|
||||
export interface NotificationSettings {
|
||||
/** Direct and group chats. */
|
||||
chats: boolean;
|
||||
/** Cauldrons of realms. */
|
||||
realms: boolean;
|
||||
}
|
||||
|
||||
const STORAGE_KEY = 'notifications';
|
||||
const OFF: NotificationSettings = { chats: false, realms: false };
|
||||
|
||||
let cached: NotificationSettings | undefined;
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
function read(): NotificationSettings {
|
||||
if (cached) return cached;
|
||||
cached = OFF;
|
||||
try {
|
||||
const stored: unknown = JSON.parse(
|
||||
localStorage.getItem(STORAGE_KEY) ?? 'null',
|
||||
);
|
||||
if (typeof stored === 'object' && stored !== null) {
|
||||
cached = {
|
||||
chats: 'chats' in stored && stored.chats === true,
|
||||
realms: 'realms' in stored && stored.realms === true,
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
// Storage is blocked or holds something else: notifications stay off.
|
||||
}
|
||||
return cached;
|
||||
}
|
||||
|
||||
function subscribe(onChange: () => void) {
|
||||
listeners.add(onChange);
|
||||
return () => listeners.delete(onChange);
|
||||
}
|
||||
|
||||
export function setNotificationSettings(settings: NotificationSettings) {
|
||||
cached = settings;
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(settings));
|
||||
} catch {
|
||||
// Kept for this visit only.
|
||||
}
|
||||
for (const listener of listeners) listener();
|
||||
}
|
||||
|
||||
export function useNotificationSettings(): NotificationSettings {
|
||||
return useSyncExternalStore(subscribe, read, () => OFF);
|
||||
}
|
||||
|
||||
export function notificationsSupported(): boolean {
|
||||
return typeof window !== 'undefined' && 'Notification' in window;
|
||||
}
|
||||
|
||||
/**
|
||||
* Asks the browser for leave to show notifications, if it hasn't been
|
||||
* asked. Call it from a click. Answers whether they may be shown.
|
||||
*/
|
||||
export async function allowNotifications(): Promise<boolean> {
|
||||
if (!notificationsSupported()) return false;
|
||||
if (Notification.permission === 'default') {
|
||||
await Notification.requestPermission();
|
||||
}
|
||||
return Notification.permission === 'granted';
|
||||
}
|
||||
|
||||
function describe(message: Message): string {
|
||||
if (message.content) return message.content;
|
||||
const count = message.attachments.length;
|
||||
return count === 1
|
||||
? `Sent ${message.attachments[0].filename}`
|
||||
: `Sent ${count} files`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows a desktop notification for a message from someone else, when the
|
||||
* user has asked for them and isn't looking at the app. `open` is called
|
||||
* with the place to go when the notification is clicked.
|
||||
*/
|
||||
export function notifyOfMessage(
|
||||
queryClient: QueryClient,
|
||||
message: Message,
|
||||
realmId: string | null,
|
||||
ownId: string,
|
||||
open: (to: { realmId: string | null; conversationId: string }) => void,
|
||||
) {
|
||||
const settings = read();
|
||||
if (!(realmId ? settings.realms : settings.chats)) return;
|
||||
if (!notificationsSupported() || Notification.permission !== 'granted')
|
||||
return;
|
||||
if (isAttentive()) return;
|
||||
|
||||
let title = message.author.name;
|
||||
let body = describe(message);
|
||||
if (realmId) {
|
||||
const realm = queryClient.getQueryData(realmQuery(realmId).queryKey);
|
||||
const cauldron = realm?.cauldrons.find(
|
||||
(item) => item.id === message.conversationId,
|
||||
);
|
||||
const realmName =
|
||||
realm?.name ??
|
||||
queryClient
|
||||
.getQueryData(realmsQuery.queryKey)
|
||||
?.find((item) => item.id === realmId)?.name;
|
||||
title =
|
||||
[cauldron && `#${cauldron.name}`, realmName]
|
||||
.filter(Boolean)
|
||||
.join(' · ') || title;
|
||||
body = `${message.author.name}: ${body}`;
|
||||
} else {
|
||||
const conversation = queryClient
|
||||
.getQueryData(conversationsQuery.queryKey)
|
||||
?.find((item) => item.id === message.conversationId);
|
||||
if (conversation?.type === 'group') {
|
||||
title = conversationTitle(conversation, ownId);
|
||||
body = `${message.author.name}: ${body}`;
|
||||
}
|
||||
}
|
||||
|
||||
const notification = new Notification(title, {
|
||||
body,
|
||||
// A newer message from the same place replaces the older notification.
|
||||
tag: message.conversationId,
|
||||
});
|
||||
notification.addEventListener('click', () => {
|
||||
window.focus();
|
||||
open({ realmId, conversationId: message.conversationId });
|
||||
notification.close();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows a desktop notification for a call a friend just started in one of
|
||||
* the user's chats, under the same conditions as for a message there.
|
||||
*/
|
||||
export function notifyOfCall(
|
||||
queryClient: QueryClient,
|
||||
call: Call,
|
||||
ownId: string,
|
||||
open: (to: { realmId: string | null; conversationId: string }) => void,
|
||||
) {
|
||||
if (!read().chats) return;
|
||||
if (!notificationsSupported() || Notification.permission !== 'granted')
|
||||
return;
|
||||
if (isAttentive()) return;
|
||||
const caller = call.participants.at(0);
|
||||
if (!caller) return;
|
||||
|
||||
const conversation = queryClient
|
||||
.getQueryData(conversationsQuery.queryKey)
|
||||
?.find((item) => item.id === call.conversationId);
|
||||
const isGroup = conversation?.type === 'group';
|
||||
const notification = new Notification(
|
||||
isGroup ? conversationTitle(conversation, ownId) : caller.name,
|
||||
{
|
||||
body: isGroup ? `${caller.name} started a call` : 'Incoming call',
|
||||
tag: `call:${call.conversationId}`,
|
||||
},
|
||||
);
|
||||
notification.addEventListener('click', () => {
|
||||
window.focus();
|
||||
open({ realmId: call.realmId, conversationId: call.conversationId });
|
||||
notification.close();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import {
|
||||
queryOptions,
|
||||
useMutation,
|
||||
useQueryClient,
|
||||
} from '@tanstack/react-query';
|
||||
import { ownProfileSchema } from '@repo/contracts';
|
||||
import type { UpdateProfile } from '@repo/contracts';
|
||||
import { api } from '@/lib/api';
|
||||
|
||||
/** The signed-in user's profile; fails with a 401 ApiError when signed out. */
|
||||
export const ownProfileQuery = queryOptions({
|
||||
queryKey: ['users', 'me'],
|
||||
queryFn: ({ signal }) =>
|
||||
api('/users/me', { schema: ownProfileSchema, signal }),
|
||||
staleTime: 60_000,
|
||||
});
|
||||
|
||||
export function useUpdateProfile() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (changes: UpdateProfile) =>
|
||||
api('/users/me', {
|
||||
method: 'PATCH',
|
||||
body: changes,
|
||||
schema: ownProfileSchema,
|
||||
}),
|
||||
onSuccess: (profile) => {
|
||||
queryClient.setQueryData(ownProfileQuery.queryKey, profile);
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,448 @@
|
||||
import {
|
||||
queryOptions,
|
||||
useMutation,
|
||||
useQueryClient,
|
||||
} from '@tanstack/react-query';
|
||||
import type { QueryClient } from '@tanstack/react-query';
|
||||
import {
|
||||
REALM_PERMISSIONS,
|
||||
cauldronSchema,
|
||||
hasPermissions,
|
||||
invitePreviewSchema,
|
||||
realmBanListSchema,
|
||||
realmInviteListSchema,
|
||||
realmInviteSchema,
|
||||
realmListSchema,
|
||||
realmMemberListSchema,
|
||||
realmMemberSchema,
|
||||
realmRoleSchema,
|
||||
realmSchema,
|
||||
} from '@repo/contracts';
|
||||
import type {
|
||||
BanMemberInput,
|
||||
CreateInviteInput,
|
||||
CreateRole,
|
||||
Realm,
|
||||
RealmMember,
|
||||
RealmPermission,
|
||||
UpdateRole,
|
||||
} from '@repo/contracts';
|
||||
import { api, noContent } from '@/lib/api';
|
||||
|
||||
/** The realms the signed-in user is in, in the order they joined them. */
|
||||
export const realmsQuery = queryOptions({
|
||||
queryKey: ['realms', 'list'],
|
||||
queryFn: ({ signal }) => api('/realms', { schema: realmListSchema, signal }),
|
||||
});
|
||||
|
||||
/** A realm with its cauldrons, roles and what the user may do in it. */
|
||||
export const realmQuery = (realmId: string) =>
|
||||
queryOptions({
|
||||
queryKey: ['realms', 'detail', realmId],
|
||||
queryFn: ({ signal }) =>
|
||||
api(`/realms/${realmId}`, { schema: realmSchema, signal }),
|
||||
});
|
||||
|
||||
export const realmMembersQuery = (realmId: string) =>
|
||||
queryOptions({
|
||||
queryKey: ['realms', 'members', realmId],
|
||||
queryFn: ({ signal }) =>
|
||||
api(`/realms/${realmId}/members`, {
|
||||
schema: realmMemberListSchema,
|
||||
signal,
|
||||
}),
|
||||
});
|
||||
|
||||
/** The invites that still work, as far as the user may see them. */
|
||||
export const realmInvitesQuery = (realmId: string) =>
|
||||
queryOptions({
|
||||
queryKey: ['realms', 'invites', realmId],
|
||||
queryFn: ({ signal }) =>
|
||||
api(`/realms/${realmId}/invites`, {
|
||||
schema: realmInviteListSchema,
|
||||
signal,
|
||||
}),
|
||||
});
|
||||
|
||||
/** The people banned from a realm, newest ban first. */
|
||||
export const realmBansQuery = (realmId: string) =>
|
||||
queryOptions({
|
||||
queryKey: ['realms', 'bans', realmId],
|
||||
queryFn: ({ signal }) =>
|
||||
api(`/realms/${realmId}/bans`, { schema: realmBanListSchema, signal }),
|
||||
});
|
||||
|
||||
/** Where an invite link leads. Always asked afresh: links run out. */
|
||||
export const invitePreviewQuery = (code: string) =>
|
||||
queryOptions({
|
||||
queryKey: ['invites', code],
|
||||
queryFn: ({ signal }) =>
|
||||
api(`/invites/${code}`, { schema: invitePreviewSchema, signal }),
|
||||
staleTime: 0,
|
||||
});
|
||||
|
||||
/** What each permission lets its holder do, in the words the app shows. */
|
||||
export const PERMISSION_LABELS: Record<
|
||||
RealmPermission,
|
||||
{ name: string; description: string }
|
||||
> = {
|
||||
manageRealm: {
|
||||
name: 'Manage realm',
|
||||
description: 'Rename the realm and revoke anyone’s invites.',
|
||||
},
|
||||
manageCauldrons: {
|
||||
name: 'Manage cauldrons',
|
||||
description: 'Create, rename and delete cauldrons.',
|
||||
},
|
||||
manageRoles: {
|
||||
name: 'Manage roles',
|
||||
description:
|
||||
'Create roles and give them to members, up to what they can do themselves.',
|
||||
},
|
||||
kickMembers: {
|
||||
name: 'Remove members',
|
||||
description: 'Remove members who can’t do more than they can.',
|
||||
},
|
||||
banMembers: {
|
||||
name: 'Ban members',
|
||||
description: 'Ban members who can’t do more than they can, and lift bans.',
|
||||
},
|
||||
createInvites: {
|
||||
name: 'Invite people',
|
||||
description: 'Make invite links.',
|
||||
},
|
||||
sendMessages: {
|
||||
name: 'Send messages',
|
||||
description: 'Post in cauldrons and join their calls.',
|
||||
},
|
||||
manageMessages: {
|
||||
name: 'Manage messages',
|
||||
description: 'Delete other people’s messages.',
|
||||
},
|
||||
};
|
||||
|
||||
/** Whether the signed-in user may do this in a realm. */
|
||||
export function can(realm: Realm, permission: RealmPermission): boolean {
|
||||
return realm.permissions.includes(permission);
|
||||
}
|
||||
|
||||
/** Whether the user may do everything this role allows, so may manage it. */
|
||||
export function canManageRole(
|
||||
realm: Realm,
|
||||
role: { permissions: RealmPermission[] },
|
||||
): boolean {
|
||||
return (
|
||||
can(realm, 'manageRoles') &&
|
||||
hasPermissions(realm.permissions, role.permissions)
|
||||
);
|
||||
}
|
||||
|
||||
/** What a member may do, worked out the way the API does it. */
|
||||
export function memberPermissions(
|
||||
realm: Realm,
|
||||
member: RealmMember,
|
||||
): RealmPermission[] {
|
||||
if (member.user.id === realm.ownerId) return [...REALM_PERMISSIONS];
|
||||
const roles = realm.roles.filter(
|
||||
(role) => role.isDefault || member.roleIds.includes(role.id),
|
||||
);
|
||||
return REALM_PERMISSIONS.filter((permission) =>
|
||||
roles.some((role) => role.permissions.includes(permission)),
|
||||
);
|
||||
}
|
||||
|
||||
/** Never the owner, and nobody who can do more than the user can. */
|
||||
function outranks(realm: Realm, member: RealmMember): boolean {
|
||||
return (
|
||||
member.user.id !== realm.ownerId &&
|
||||
hasPermissions(realm.permissions, memberPermissions(realm, member))
|
||||
);
|
||||
}
|
||||
|
||||
/** Whether the user may remove this member. */
|
||||
export function canRemoveMember(realm: Realm, member: RealmMember): boolean {
|
||||
return can(realm, 'kickMembers') && outranks(realm, member);
|
||||
}
|
||||
|
||||
/** Whether the user may ban this member. */
|
||||
export function canBanMember(realm: Realm, member: RealmMember): boolean {
|
||||
return can(realm, 'banMembers') && outranks(realm, member);
|
||||
}
|
||||
|
||||
/** The address to share for an invite code. */
|
||||
export function inviteLink(code: string): string {
|
||||
return `${window.location.origin}/app/invite/${code}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The code in what someone pasted: a whole invite link or the code alone.
|
||||
* Nothing when it can't be either.
|
||||
*/
|
||||
export function inviteCodeFrom(pasted: string): string | undefined {
|
||||
const last = pasted.trim().split(/[/?#]/).filter(Boolean).at(-1);
|
||||
return last && /^[A-Za-z0-9_-]{8,32}$/.test(last) ? last : undefined;
|
||||
}
|
||||
|
||||
/** "1 member", "3 members". */
|
||||
export function realmMemberCount(count: number): string {
|
||||
return count === 1 ? '1 member' : `${count} members`;
|
||||
}
|
||||
|
||||
/** Stores a realm the API just answered with, in the list as well. */
|
||||
function putRealmInCache(queryClient: QueryClient, realm: Realm) {
|
||||
queryClient.setQueryData(realmQuery(realm.id).queryKey, realm);
|
||||
const summary = {
|
||||
id: realm.id,
|
||||
name: realm.name,
|
||||
ownerId: realm.ownerId,
|
||||
hasUnread: realm.cauldrons.some((cauldron) => cauldron.unreadCount > 0),
|
||||
};
|
||||
queryClient.setQueryData(realmsQuery.queryKey, (realms) => {
|
||||
if (!realms) return realms;
|
||||
return realms.some((item) => item.id === realm.id)
|
||||
? realms.map((item) => (item.id === realm.id ? summary : item))
|
||||
: [...realms, summary];
|
||||
});
|
||||
}
|
||||
|
||||
// Every change below also reaches the realm's members as "realm:changed"
|
||||
// over the socket, which refetches what they have open. The refreshes here
|
||||
// are for the person who made the change, so they needn't wait for it.
|
||||
|
||||
function useRefreshRealm(realmId: string) {
|
||||
const queryClient = useQueryClient();
|
||||
return () =>
|
||||
queryClient.invalidateQueries({ queryKey: realmQuery(realmId).queryKey });
|
||||
}
|
||||
|
||||
function useRefreshMembers(realmId: string) {
|
||||
const queryClient = useQueryClient();
|
||||
return () =>
|
||||
Promise.all([
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: realmMembersQuery(realmId).queryKey,
|
||||
}),
|
||||
queryClient.invalidateQueries({ queryKey: realmQuery(realmId).queryKey }),
|
||||
]);
|
||||
}
|
||||
|
||||
export function useCreateRealm() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (name: string) =>
|
||||
api('/realms', { method: 'POST', body: { name }, schema: realmSchema }),
|
||||
onSuccess: (realm) => putRealmInCache(queryClient, realm),
|
||||
});
|
||||
}
|
||||
|
||||
export function useRenameRealm(realmId: string) {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (name: string) =>
|
||||
api(`/realms/${realmId}`, {
|
||||
method: 'PATCH',
|
||||
body: { name },
|
||||
schema: realmSchema,
|
||||
}),
|
||||
onSuccess: (realm) => putRealmInCache(queryClient, realm),
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeleteRealm(realmId: string) {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: () =>
|
||||
api(`/realms/${realmId}`, { method: 'DELETE', schema: noContent }),
|
||||
// Not awaited: callers move away from the realm without waiting.
|
||||
onSuccess: () => {
|
||||
void queryClient.invalidateQueries({ queryKey: realmsQuery.queryKey });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** Removes someone from a realm; with the user's own id, leaves it. */
|
||||
export function useRemoveRealmMember(realmId: string) {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (userId: string) =>
|
||||
api(`/realms/${realmId}/members/${userId}`, {
|
||||
method: 'DELETE',
|
||||
schema: noContent,
|
||||
}),
|
||||
onSuccess: () => {
|
||||
void queryClient.invalidateQueries({ queryKey: realmsQuery.queryKey });
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: realmMembersQuery(realmId).queryKey,
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** Puts a member out of a realm and keeps invites from letting them back. */
|
||||
export function useBanMember(realmId: string) {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: ({ userId, ...body }: BanMemberInput & { userId: string }) =>
|
||||
api(`/realms/${realmId}/bans/${userId}`, {
|
||||
method: 'PUT',
|
||||
body,
|
||||
schema: noContent,
|
||||
}),
|
||||
onSuccess: () => {
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: realmMembersQuery(realmId).queryKey,
|
||||
});
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: realmBansQuery(realmId).queryKey,
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** Lifts a ban. The person still needs an invite to come back. */
|
||||
export function useUnbanMember(realmId: string) {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (userId: string) =>
|
||||
api(`/realms/${realmId}/bans/${userId}`, {
|
||||
method: 'DELETE',
|
||||
schema: noContent,
|
||||
}),
|
||||
onSuccess: () =>
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: realmBansQuery(realmId).queryKey,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
export function useSetMemberRoles(realmId: string) {
|
||||
const refresh = useRefreshMembers(realmId);
|
||||
return useMutation({
|
||||
mutationFn: ({ userId, roleIds }: { userId: string; roleIds: string[] }) =>
|
||||
api(`/realms/${realmId}/members/${userId}/roles`, {
|
||||
method: 'PUT',
|
||||
body: { roleIds },
|
||||
schema: realmMemberSchema,
|
||||
}),
|
||||
onSuccess: refresh,
|
||||
});
|
||||
}
|
||||
|
||||
export function useCreateRole(realmId: string) {
|
||||
const refresh = useRefreshRealm(realmId);
|
||||
return useMutation({
|
||||
mutationFn: (body: CreateRole) =>
|
||||
api(`/realms/${realmId}/roles`, {
|
||||
method: 'POST',
|
||||
body,
|
||||
schema: realmRoleSchema,
|
||||
}),
|
||||
onSuccess: refresh,
|
||||
});
|
||||
}
|
||||
|
||||
export function useUpdateRole(realmId: string) {
|
||||
const refresh = useRefreshRealm(realmId);
|
||||
return useMutation({
|
||||
mutationFn: ({ roleId, ...body }: UpdateRole & { roleId: string }) =>
|
||||
api(`/realms/${realmId}/roles/${roleId}`, {
|
||||
method: 'PATCH',
|
||||
body,
|
||||
schema: realmRoleSchema,
|
||||
}),
|
||||
onSuccess: refresh,
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeleteRole(realmId: string) {
|
||||
const refresh = useRefreshMembers(realmId);
|
||||
return useMutation({
|
||||
mutationFn: (roleId: string) =>
|
||||
api(`/realms/${realmId}/roles/${roleId}`, {
|
||||
method: 'DELETE',
|
||||
schema: noContent,
|
||||
}),
|
||||
onSuccess: refresh,
|
||||
});
|
||||
}
|
||||
|
||||
export function useCreateCauldron(realmId: string) {
|
||||
const refresh = useRefreshRealm(realmId);
|
||||
return useMutation({
|
||||
mutationFn: (name: string) =>
|
||||
api(`/realms/${realmId}/cauldrons`, {
|
||||
method: 'POST',
|
||||
body: { name },
|
||||
schema: cauldronSchema,
|
||||
}),
|
||||
onSuccess: refresh,
|
||||
});
|
||||
}
|
||||
|
||||
export function useRenameCauldron(realmId: string) {
|
||||
const refresh = useRefreshRealm(realmId);
|
||||
return useMutation({
|
||||
mutationFn: ({ cauldronId, name }: { cauldronId: string; name: string }) =>
|
||||
api(`/realms/${realmId}/cauldrons/${cauldronId}`, {
|
||||
method: 'PATCH',
|
||||
body: { name },
|
||||
schema: cauldronSchema,
|
||||
}),
|
||||
onSuccess: refresh,
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeleteCauldron(realmId: string) {
|
||||
const refresh = useRefreshRealm(realmId);
|
||||
return useMutation({
|
||||
mutationFn: (cauldronId: string) =>
|
||||
api(`/realms/${realmId}/cauldrons/${cauldronId}`, {
|
||||
method: 'DELETE',
|
||||
schema: noContent,
|
||||
}),
|
||||
onSuccess: refresh,
|
||||
});
|
||||
}
|
||||
|
||||
function useRefreshInvites(realmId: string) {
|
||||
const queryClient = useQueryClient();
|
||||
return () =>
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: realmInvitesQuery(realmId).queryKey,
|
||||
});
|
||||
}
|
||||
|
||||
export function useCreateInvite(realmId: string) {
|
||||
const refresh = useRefreshInvites(realmId);
|
||||
return useMutation({
|
||||
mutationFn: (body: CreateInviteInput) =>
|
||||
api(`/realms/${realmId}/invites`, {
|
||||
method: 'POST',
|
||||
body,
|
||||
schema: realmInviteSchema,
|
||||
}),
|
||||
onSuccess: refresh,
|
||||
});
|
||||
}
|
||||
|
||||
export function useRevokeInvite(realmId: string) {
|
||||
const refresh = useRefreshInvites(realmId);
|
||||
return useMutation({
|
||||
mutationFn: (code: string) =>
|
||||
api(`/realms/${realmId}/invites/${code}`, {
|
||||
method: 'DELETE',
|
||||
schema: noContent,
|
||||
}),
|
||||
onSuccess: refresh,
|
||||
});
|
||||
}
|
||||
|
||||
/** Joins the realm an invite leads to. */
|
||||
export function useAcceptInvite() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (code: string) =>
|
||||
api(`/invites/${code}/accept`, { method: 'POST', schema: realmSchema }),
|
||||
onSuccess: (realm) => putRealmInCache(queryClient, realm),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { useRouter } from '@tanstack/react-router';
|
||||
import {
|
||||
callSchema,
|
||||
conversationReadSchema,
|
||||
messageDeletionSchema,
|
||||
messageSchema,
|
||||
reactionChangeSchema,
|
||||
} from '@repo/contracts';
|
||||
import type {
|
||||
ClientToServerEvents,
|
||||
ServerToClientEvents,
|
||||
} from '@repo/contracts';
|
||||
import { io } from 'socket.io-client';
|
||||
import type { Socket } from 'socket.io-client';
|
||||
import { apiUrl } from '@/lib/api';
|
||||
import { applyCallChange, callsQuery, ring, stopRinging } from '@/lib/calls';
|
||||
import {
|
||||
addMessageToCache,
|
||||
addMessageToHistory,
|
||||
applyReactionChange,
|
||||
conversationsQuery,
|
||||
removeMessageFromCache,
|
||||
} from '@/lib/conversations';
|
||||
import { friendsQuery } from '@/lib/friends';
|
||||
import { notifyOfCall, notifyOfMessage } from '@/lib/notifications';
|
||||
import { ownProfileQuery } from '@/lib/profile';
|
||||
import {
|
||||
realmBansQuery,
|
||||
realmMembersQuery,
|
||||
realmQuery,
|
||||
realmsQuery,
|
||||
} from '@/lib/realms';
|
||||
import { addUnread, isBeingRead, setUnreadCount } from '@/lib/unread';
|
||||
|
||||
/**
|
||||
* Keeps a socket to the API open while the component is mounted and folds
|
||||
* what it hears into the query cache, so every screen updates live. The
|
||||
* browser sends the session cookie with the connection.
|
||||
*/
|
||||
export function useRealtime() {
|
||||
const queryClient = useQueryClient();
|
||||
const router = useRouter();
|
||||
|
||||
useEffect(() => {
|
||||
const socket: Socket<ServerToClientEvents, ClientToServerEvents> = io(
|
||||
apiUrl,
|
||||
// The API accepts WebSocket connections only (no HTTP long-polling).
|
||||
{ transports: ['websocket'], withCredentials: true },
|
||||
);
|
||||
|
||||
let hasConnectedBefore = false;
|
||||
socket.on('connect', () => {
|
||||
// Events sent while the connection was down are gone; fetch again.
|
||||
if (hasConnectedBefore) {
|
||||
void queryClient.invalidateQueries({ queryKey: ['conversations'] });
|
||||
void queryClient.invalidateQueries({ queryKey: friendsQuery.queryKey });
|
||||
void queryClient.invalidateQueries({ queryKey: ['realms'] });
|
||||
void queryClient.invalidateQueries({ queryKey: callsQuery.queryKey });
|
||||
}
|
||||
hasConnectedBefore = true;
|
||||
});
|
||||
|
||||
socket.on('disconnect', (reason) => {
|
||||
// The API closes a socket when its session ends or runs out. After
|
||||
// that the client doesn't retry on its own, so try once: it gets back
|
||||
// in if the session was only renewed, and is refused if it is over.
|
||||
if (reason === 'io server disconnect') socket.connect();
|
||||
});
|
||||
|
||||
const ownId = () => queryClient.getQueryData(ownProfileQuery.queryKey)?.id;
|
||||
const open = (to: { realmId: string | null; conversationId: string }) =>
|
||||
void (to.realmId
|
||||
? router.navigate({
|
||||
to: '/app/r/$realmId/$cauldronId',
|
||||
params: { realmId: to.realmId, cauldronId: to.conversationId },
|
||||
})
|
||||
: router.navigate({
|
||||
to: '/app/c/$conversationId',
|
||||
params: { conversationId: to.conversationId },
|
||||
}));
|
||||
|
||||
socket.on('message:created', (payload, context) => {
|
||||
const parsed = messageSchema.safeParse(payload);
|
||||
if (!parsed.success) return;
|
||||
const message = parsed.data;
|
||||
const { realmId } = context;
|
||||
// A cauldron's message belongs to its realm, not the list of chats.
|
||||
if (realmId) addMessageToHistory(queryClient, message);
|
||||
else addMessageToCache(queryClient, message);
|
||||
|
||||
const me = ownId();
|
||||
if (!me || message.author.id === me) return;
|
||||
// A message arriving in front of the reader is marked read by the
|
||||
// chat itself; any other one counts as unread.
|
||||
if (!isBeingRead(message.conversationId)) {
|
||||
addUnread(queryClient, message.conversationId, realmId);
|
||||
}
|
||||
notifyOfMessage(queryClient, message, realmId, me, open);
|
||||
});
|
||||
|
||||
socket.on('message:deleted', (payload) => {
|
||||
const deletion = messageDeletionSchema.safeParse(payload);
|
||||
if (deletion.success) removeMessageFromCache(queryClient, deletion.data);
|
||||
});
|
||||
|
||||
socket.on('reaction:changed', (payload) => {
|
||||
const change = reactionChangeSchema.safeParse(payload);
|
||||
if (change.success)
|
||||
applyReactionChange(queryClient, change.data, ownId());
|
||||
});
|
||||
|
||||
socket.on('conversation:read', (payload) => {
|
||||
const read = conversationReadSchema.safeParse(payload);
|
||||
if (read.success) setUnreadCount(queryClient, read.data);
|
||||
});
|
||||
|
||||
socket.on('call:changed', (payload) => {
|
||||
const parsed = callSchema.safeParse(payload);
|
||||
if (!parsed.success) return;
|
||||
const call = parsed.data;
|
||||
const hasStarted = applyCallChange(queryClient, call);
|
||||
const me = ownId();
|
||||
const isIn = call.participants.some((person) => person.id === me);
|
||||
// A friend starting a call in a chat is a call to the user. A realm's
|
||||
// cauldron is a room people drop into; it only shows there.
|
||||
if (hasStarted && me && !isIn && call.realmId === null) {
|
||||
ring(call);
|
||||
notifyOfCall(queryClient, call, me, open);
|
||||
} else if (isIn || call.participants.length === 0) {
|
||||
stopRinging(call.conversationId);
|
||||
}
|
||||
});
|
||||
|
||||
socket.on('realm:changed', (realmId, what) => {
|
||||
// Either kind can change what the realm's own details carry (the
|
||||
// member count, what the user may do there).
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: realmQuery(realmId).queryKey,
|
||||
});
|
||||
if (what === 'members') {
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: realmMembersQuery(realmId).queryKey,
|
||||
});
|
||||
// A member may have gone by being banned.
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: realmBansQuery(realmId).queryKey,
|
||||
});
|
||||
} else {
|
||||
// Renamed, deleted, joined or left: the list of realms shows those.
|
||||
void queryClient.invalidateQueries({ queryKey: realmsQuery.queryKey });
|
||||
// A cauldron that is gone, or a realm the user is out of, takes its
|
||||
// calls along without a word about each.
|
||||
void queryClient.invalidateQueries({ queryKey: callsQuery.queryKey });
|
||||
}
|
||||
});
|
||||
|
||||
socket.on('conversations:changed', () => {
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: conversationsQuery.queryKey,
|
||||
});
|
||||
// Someone taken out of a group hears no more about its call.
|
||||
void queryClient.invalidateQueries({ queryKey: callsQuery.queryKey });
|
||||
});
|
||||
|
||||
socket.on('friends:changed', () => {
|
||||
void queryClient.invalidateQueries({ queryKey: friendsQuery.queryKey });
|
||||
});
|
||||
|
||||
return () => {
|
||||
socket.disconnect();
|
||||
};
|
||||
}, [queryClient, router]);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
/** Where the app sends people once they are signed in. */
|
||||
export const DEFAULT_SIGNED_IN_PATH = '/app';
|
||||
|
||||
export interface AuthSearch {
|
||||
/** The page that asked for sign-in, to return to afterwards. */
|
||||
redirect?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the value only when it is a path on this site ("/app/settings"),
|
||||
* so a crafted link can't send someone to another site after they log in.
|
||||
* Absolute URLs, "//host" and "/\host" are all refused.
|
||||
*/
|
||||
export function toSitePath(value: unknown): string | undefined {
|
||||
return typeof value === 'string' && /^\/(?![/\\])/.test(value)
|
||||
? value
|
||||
: undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* `validateSearch` for the login and register routes. It always returns the
|
||||
* `redirect` key: the router fills any key left out from the raw query
|
||||
* string, which would let an unchecked value through.
|
||||
*/
|
||||
export function validateAuthSearch(
|
||||
search: Record<string, unknown>,
|
||||
): AuthSearch {
|
||||
return { redirect: toSitePath(search.redirect) };
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
/** Shown in the page title and on the welcome page. Change it in one place. */
|
||||
export const site = {
|
||||
name: 'electro4ort',
|
||||
tagline: 'Chat, gather and call in one place',
|
||||
};
|
||||
@@ -0,0 +1,167 @@
|
||||
import { useEffect, useSyncExternalStore } from 'react';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import type { QueryClient } from '@tanstack/react-query';
|
||||
import { UNREAD_COUNT_MAX, conversationReadSchema } from '@repo/contracts';
|
||||
import type { ConversationRead } from '@repo/contracts';
|
||||
import { api } from '@/lib/api';
|
||||
import { conversationsQuery } from '@/lib/conversations';
|
||||
import { realmQuery, realmsQuery } from '@/lib/realms';
|
||||
import { site } from '@/lib/site';
|
||||
|
||||
/** "3", or "99+" once the count has reached where the API stops counting. */
|
||||
export function formatUnread(count: number): string {
|
||||
return count >= UNREAD_COUNT_MAX ? `${UNREAD_COUNT_MAX - 1}+` : String(count);
|
||||
}
|
||||
|
||||
/** Stores a conversation's or cauldron's unread count wherever it shows. */
|
||||
export function setUnreadCount(
|
||||
queryClient: QueryClient,
|
||||
{ conversationId, realmId, unreadCount }: ConversationRead,
|
||||
) {
|
||||
if (!realmId) {
|
||||
queryClient.setQueryData(conversationsQuery.queryKey, (conversations) =>
|
||||
conversations?.map((item) =>
|
||||
item.id === conversationId ? { ...item, unreadCount } : item,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
queryClient.setQueryData(realmQuery(realmId).queryKey, (realm) =>
|
||||
realm
|
||||
? {
|
||||
...realm,
|
||||
cauldrons: realm.cauldrons.map((item) =>
|
||||
item.id === conversationId ? { ...item, unreadCount } : item,
|
||||
),
|
||||
}
|
||||
: realm,
|
||||
);
|
||||
// The list of realms only says whether anything in a realm is unread.
|
||||
const realm = queryClient.getQueryData(realmQuery(realmId).queryKey);
|
||||
if (realm) {
|
||||
const hasUnread = realm.cauldrons.some((item) => item.unreadCount > 0);
|
||||
queryClient.setQueryData(realmsQuery.queryKey, (realms) =>
|
||||
realms?.map((item) =>
|
||||
item.id === realmId ? { ...item, hasUnread } : item,
|
||||
),
|
||||
);
|
||||
} else if (unreadCount > 0) {
|
||||
queryClient.setQueryData(realmsQuery.queryKey, (realms) =>
|
||||
realms?.map((item) =>
|
||||
item.id === realmId ? { ...item, hasUnread: true } : item,
|
||||
),
|
||||
);
|
||||
} else {
|
||||
// Other cauldrons of a realm that isn't loaded may still have some.
|
||||
void queryClient.invalidateQueries({ queryKey: realmsQuery.queryKey });
|
||||
}
|
||||
}
|
||||
|
||||
/** Counts one more unread message, for one that just came in. */
|
||||
export function addUnread(
|
||||
queryClient: QueryClient,
|
||||
conversationId: string,
|
||||
realmId: string | null,
|
||||
) {
|
||||
const current = realmId
|
||||
? queryClient
|
||||
.getQueryData(realmQuery(realmId).queryKey)
|
||||
?.cauldrons.find((item) => item.id === conversationId)?.unreadCount
|
||||
: queryClient
|
||||
.getQueryData(conversationsQuery.queryKey)
|
||||
?.find((item) => item.id === conversationId)?.unreadCount;
|
||||
setUnreadCount(queryClient, {
|
||||
conversationId,
|
||||
realmId,
|
||||
unreadCount: Math.min((current ?? 0) + 1, UNREAD_COUNT_MAX),
|
||||
});
|
||||
}
|
||||
|
||||
// Which conversation is on screen with its newest messages in view. New
|
||||
// messages there are read as they arrive, so they are never counted.
|
||||
let onScreen: string | null = null;
|
||||
|
||||
/** Called by the chat as it is shown, scrolled and hidden. */
|
||||
export function setConversationOnScreen(
|
||||
conversationId: string,
|
||||
isOnScreen: boolean,
|
||||
) {
|
||||
if (isOnScreen) onScreen = conversationId;
|
||||
else if (onScreen === conversationId) onScreen = null;
|
||||
}
|
||||
|
||||
/** Whether the app is in front of the person: tab showing, window focused. */
|
||||
export function isAttentive(): boolean {
|
||||
return document.visibilityState === 'visible' && document.hasFocus();
|
||||
}
|
||||
|
||||
/** Whether a new message in this conversation is being looked at right now. */
|
||||
export function isBeingRead(conversationId: string): boolean {
|
||||
return onScreen === conversationId && isAttentive();
|
||||
}
|
||||
|
||||
function subscribeToAttention(onChange: () => void) {
|
||||
window.addEventListener('focus', onChange);
|
||||
window.addEventListener('blur', onChange);
|
||||
document.addEventListener('visibilitychange', onChange);
|
||||
return () => {
|
||||
window.removeEventListener('focus', onChange);
|
||||
window.removeEventListener('blur', onChange);
|
||||
document.removeEventListener('visibilitychange', onChange);
|
||||
};
|
||||
}
|
||||
|
||||
/** `isAttentive()` as state: re-renders when the person leaves or returns. */
|
||||
export function useAttentive(): boolean {
|
||||
return useSyncExternalStore(subscribeToAttention, isAttentive, () => true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells the API how far the user has read. The badge goes at once; the
|
||||
* answer (and "conversation:read" in other tabs) brings the true count.
|
||||
*/
|
||||
export function useMarkRead(conversationId: string, realmId: string | null) {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (messageId: string) =>
|
||||
api(`/conversations/${conversationId}/read`, {
|
||||
method: 'PUT',
|
||||
body: { messageId },
|
||||
schema: conversationReadSchema,
|
||||
}),
|
||||
onMutate: () =>
|
||||
setUnreadCount(queryClient, { conversationId, realmId, unreadCount: 0 }),
|
||||
onSuccess: (read) => setUnreadCount(queryClient, read),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* What is waiting across the app: unread messages in the user's chats, and
|
||||
* whether any realm has something new.
|
||||
*/
|
||||
export function useUnreadSummary() {
|
||||
const { data: conversations } = useQuery(conversationsQuery);
|
||||
const { data: realms } = useQuery(realmsQuery);
|
||||
const messages = (conversations ?? []).reduce(
|
||||
(total, item) => total + item.unreadCount,
|
||||
0,
|
||||
);
|
||||
const inRealms = (realms ?? []).some((item) => item.hasUnread);
|
||||
return { messages, inRealms, any: messages > 0 || inRealms };
|
||||
}
|
||||
|
||||
/** Shows what is unread in the tab's title: "(3) name", or a dot for realms. */
|
||||
export function useUnreadTitle() {
|
||||
const { messages, inRealms } = useUnreadSummary();
|
||||
const mark =
|
||||
messages > 0 ? `(${formatUnread(messages)}) ` : inRealms ? '• ' : '';
|
||||
|
||||
useEffect(() => {
|
||||
const original = document.title;
|
||||
document.title = `${mark}${site.name}`;
|
||||
return () => {
|
||||
document.title = original;
|
||||
};
|
||||
}, [mark]);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { useCallback, useLayoutEffect, useRef, useState } from 'react';
|
||||
|
||||
// Closer to the bottom than this counts as "reading the newest messages".
|
||||
const END_THRESHOLD_PX = 80;
|
||||
|
||||
interface Snapshot {
|
||||
firstId: string | undefined;
|
||||
lastId: string | undefined;
|
||||
scrollHeight: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Scrolling for a message list that grows at both ends:
|
||||
* - it opens at the newest message;
|
||||
* - a new message scrolls into view only if the reader was at the bottom;
|
||||
* - older messages loaded above leave the ones being read where they are.
|
||||
*
|
||||
* Put `viewportRef` and `onScroll` on the scrolling element, which also needs
|
||||
* `overflow-anchor: none` so the browser doesn't adjust the position as well.
|
||||
*/
|
||||
export function useChatScroll(messages: { id: string }[]) {
|
||||
const viewportRef = useRef<HTMLDivElement>(null);
|
||||
const atEndRef = useRef(true);
|
||||
const [isAtEnd, setIsAtEnd] = useState(true);
|
||||
const previous = useRef<Snapshot | null>(null);
|
||||
|
||||
const firstId = messages.at(0)?.id;
|
||||
const lastId = messages.at(-1)?.id;
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const viewport = viewportRef.current;
|
||||
if (!viewport) return;
|
||||
const before = previous.current;
|
||||
const prepended =
|
||||
before !== null && before.firstId !== firstId && before.lastId === lastId;
|
||||
if (prepended) {
|
||||
viewport.scrollTop += viewport.scrollHeight - before.scrollHeight;
|
||||
} else if (atEndRef.current) {
|
||||
viewport.scrollTop = viewport.scrollHeight;
|
||||
}
|
||||
previous.current = { firstId, lastId, scrollHeight: viewport.scrollHeight };
|
||||
}, [firstId, lastId, messages.length]);
|
||||
|
||||
const onScroll = useCallback(() => {
|
||||
const viewport = viewportRef.current;
|
||||
if (!viewport) return;
|
||||
const distance =
|
||||
viewport.scrollHeight - viewport.scrollTop - viewport.clientHeight;
|
||||
atEndRef.current = distance < END_THRESHOLD_PX;
|
||||
setIsAtEnd(atEndRef.current);
|
||||
}, []);
|
||||
|
||||
/** Jumps to the newest message and follows new ones again. */
|
||||
const scrollToEnd = useCallback(() => {
|
||||
atEndRef.current = true;
|
||||
setIsAtEnd(true);
|
||||
const viewport = viewportRef.current;
|
||||
if (viewport) viewport.scrollTop = viewport.scrollHeight;
|
||||
}, []);
|
||||
|
||||
return { viewportRef, onScroll, isAtEnd, scrollToEnd };
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { useCallback, useSyncExternalStore } from 'react';
|
||||
|
||||
/** Whether a CSS media query matches right now; follows the window. */
|
||||
export function useMediaQuery(query: string): boolean {
|
||||
const subscribe = useCallback(
|
||||
(onChange: () => void) => {
|
||||
const list = window.matchMedia(query);
|
||||
list.addEventListener('change', onChange);
|
||||
return () => list.removeEventListener('change', onChange);
|
||||
},
|
||||
[query],
|
||||
);
|
||||
return useSyncExternalStore(
|
||||
subscribe,
|
||||
() => window.matchMedia(query).matches,
|
||||
() => false,
|
||||
);
|
||||
}
|
||||
|
||||
/** Tailwind's `md` breakpoint: wide enough for the side columns. */
|
||||
export const WIDE_SCREEN = '(min-width: 48rem)';
|
||||
@@ -10,33 +10,180 @@
|
||||
|
||||
import { Route as rootRouteImport } from './routes/__root'
|
||||
import { Route as IndexRouteImport } from './routes/index'
|
||||
import { Route as AppRouteRouteImport } from './routes/app/route'
|
||||
import { Route as LoginRouteImport } from './routes/login'
|
||||
import { Route as RegisterRouteImport } from './routes/register'
|
||||
import { Route as AppIndexRouteImport } from './routes/app/index'
|
||||
import { Route as AppFriendsRouteImport } from './routes/app/friends'
|
||||
import { Route as AppSettingsRouteImport } from './routes/app/settings'
|
||||
import { Route as AppCConversationIdRouteImport } from './routes/app/c/$conversationId'
|
||||
import { Route as AppInviteCodeRouteImport } from './routes/app/invite/$code'
|
||||
import { Route as AppRRealmIdRouteRouteImport } from './routes/app/r/$realmId/route'
|
||||
import { Route as AppRRealmIdIndexRouteImport } from './routes/app/r/$realmId/index'
|
||||
import { Route as AppRRealmIdCauldronIdRouteImport } from './routes/app/r/$realmId/$cauldronId'
|
||||
import { Route as AppRRealmIdSettingsRouteImport } from './routes/app/r/$realmId/settings'
|
||||
|
||||
const IndexRoute = IndexRouteImport.update({
|
||||
id: '/',
|
||||
path: '/',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const AppRouteRoute = AppRouteRouteImport.update({
|
||||
id: '/app',
|
||||
path: '/app',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const LoginRoute = LoginRouteImport.update({
|
||||
id: '/login',
|
||||
path: '/login',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const RegisterRoute = RegisterRouteImport.update({
|
||||
id: '/register',
|
||||
path: '/register',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const AppIndexRoute = AppIndexRouteImport.update({
|
||||
id: '/',
|
||||
path: '/',
|
||||
getParentRoute: () => AppRouteRoute,
|
||||
} as any)
|
||||
const AppFriendsRoute = AppFriendsRouteImport.update({
|
||||
id: '/friends',
|
||||
path: '/friends',
|
||||
getParentRoute: () => AppRouteRoute,
|
||||
} as any)
|
||||
const AppSettingsRoute = AppSettingsRouteImport.update({
|
||||
id: '/settings',
|
||||
path: '/settings',
|
||||
getParentRoute: () => AppRouteRoute,
|
||||
} as any)
|
||||
const AppCConversationIdRoute = AppCConversationIdRouteImport.update({
|
||||
id: '/c/$conversationId',
|
||||
path: '/c/$conversationId',
|
||||
getParentRoute: () => AppRouteRoute,
|
||||
} as any)
|
||||
const AppInviteCodeRoute = AppInviteCodeRouteImport.update({
|
||||
id: '/invite/$code',
|
||||
path: '/invite/$code',
|
||||
getParentRoute: () => AppRouteRoute,
|
||||
} as any)
|
||||
const AppRRealmIdRouteRoute = AppRRealmIdRouteRouteImport.update({
|
||||
id: '/r/$realmId',
|
||||
path: '/r/$realmId',
|
||||
getParentRoute: () => AppRouteRoute,
|
||||
} as any)
|
||||
const AppRRealmIdIndexRoute = AppRRealmIdIndexRouteImport.update({
|
||||
id: '/',
|
||||
path: '/',
|
||||
getParentRoute: () => AppRRealmIdRouteRoute,
|
||||
} as any)
|
||||
const AppRRealmIdCauldronIdRoute = AppRRealmIdCauldronIdRouteImport.update({
|
||||
id: '/$cauldronId',
|
||||
path: '/$cauldronId',
|
||||
getParentRoute: () => AppRRealmIdRouteRoute,
|
||||
} as any)
|
||||
const AppRRealmIdSettingsRoute = AppRRealmIdSettingsRouteImport.update({
|
||||
id: '/settings',
|
||||
path: '/settings',
|
||||
getParentRoute: () => AppRRealmIdRouteRoute,
|
||||
} as any)
|
||||
|
||||
export interface FileRoutesByFullPath {
|
||||
'/': typeof IndexRoute
|
||||
'/app': typeof AppRouteRouteWithChildren
|
||||
'/login': typeof LoginRoute
|
||||
'/register': typeof RegisterRoute
|
||||
'/app/friends': typeof AppFriendsRoute
|
||||
'/app/settings': typeof AppSettingsRoute
|
||||
'/app/': typeof AppIndexRoute
|
||||
'/app/r/$realmId': typeof AppRRealmIdRouteRouteWithChildren
|
||||
'/app/c/$conversationId': typeof AppCConversationIdRoute
|
||||
'/app/invite/$code': typeof AppInviteCodeRoute
|
||||
'/app/r/$realmId/$cauldronId': typeof AppRRealmIdCauldronIdRoute
|
||||
'/app/r/$realmId/settings': typeof AppRRealmIdSettingsRoute
|
||||
'/app/r/$realmId/': typeof AppRRealmIdIndexRoute
|
||||
}
|
||||
export interface FileRoutesByTo {
|
||||
'/': typeof IndexRoute
|
||||
'/login': typeof LoginRoute
|
||||
'/register': typeof RegisterRoute
|
||||
'/app/friends': typeof AppFriendsRoute
|
||||
'/app/settings': typeof AppSettingsRoute
|
||||
'/app': typeof AppIndexRoute
|
||||
'/app/c/$conversationId': typeof AppCConversationIdRoute
|
||||
'/app/invite/$code': typeof AppInviteCodeRoute
|
||||
'/app/r/$realmId/$cauldronId': typeof AppRRealmIdCauldronIdRoute
|
||||
'/app/r/$realmId/settings': typeof AppRRealmIdSettingsRoute
|
||||
'/app/r/$realmId': typeof AppRRealmIdIndexRoute
|
||||
}
|
||||
export interface FileRoutesById {
|
||||
__root__: typeof rootRouteImport
|
||||
'/': typeof IndexRoute
|
||||
'/app': typeof AppRouteRouteWithChildren
|
||||
'/login': typeof LoginRoute
|
||||
'/register': typeof RegisterRoute
|
||||
'/app/friends': typeof AppFriendsRoute
|
||||
'/app/settings': typeof AppSettingsRoute
|
||||
'/app/': typeof AppIndexRoute
|
||||
'/app/r/$realmId': typeof AppRRealmIdRouteRouteWithChildren
|
||||
'/app/c/$conversationId': typeof AppCConversationIdRoute
|
||||
'/app/invite/$code': typeof AppInviteCodeRoute
|
||||
'/app/r/$realmId/$cauldronId': typeof AppRRealmIdCauldronIdRoute
|
||||
'/app/r/$realmId/settings': typeof AppRRealmIdSettingsRoute
|
||||
'/app/r/$realmId/': typeof AppRRealmIdIndexRoute
|
||||
}
|
||||
export interface FileRouteTypes {
|
||||
fileRoutesByFullPath: FileRoutesByFullPath
|
||||
fullPaths: '/'
|
||||
fullPaths:
|
||||
| '/'
|
||||
| '/app'
|
||||
| '/login'
|
||||
| '/register'
|
||||
| '/app/friends'
|
||||
| '/app/settings'
|
||||
| '/app/'
|
||||
| '/app/r/$realmId'
|
||||
| '/app/c/$conversationId'
|
||||
| '/app/invite/$code'
|
||||
| '/app/r/$realmId/$cauldronId'
|
||||
| '/app/r/$realmId/settings'
|
||||
| '/app/r/$realmId/'
|
||||
fileRoutesByTo: FileRoutesByTo
|
||||
to: '/'
|
||||
id: '__root__' | '/'
|
||||
to:
|
||||
| '/'
|
||||
| '/login'
|
||||
| '/register'
|
||||
| '/app/friends'
|
||||
| '/app/settings'
|
||||
| '/app'
|
||||
| '/app/c/$conversationId'
|
||||
| '/app/invite/$code'
|
||||
| '/app/r/$realmId/$cauldronId'
|
||||
| '/app/r/$realmId/settings'
|
||||
| '/app/r/$realmId'
|
||||
id:
|
||||
| '__root__'
|
||||
| '/'
|
||||
| '/app'
|
||||
| '/login'
|
||||
| '/register'
|
||||
| '/app/friends'
|
||||
| '/app/settings'
|
||||
| '/app/'
|
||||
| '/app/r/$realmId'
|
||||
| '/app/c/$conversationId'
|
||||
| '/app/invite/$code'
|
||||
| '/app/r/$realmId/$cauldronId'
|
||||
| '/app/r/$realmId/settings'
|
||||
| '/app/r/$realmId/'
|
||||
fileRoutesById: FileRoutesById
|
||||
}
|
||||
export interface RootRouteChildren {
|
||||
IndexRoute: typeof IndexRoute
|
||||
AppRouteRoute: typeof AppRouteRouteWithChildren
|
||||
LoginRoute: typeof LoginRoute
|
||||
RegisterRoute: typeof RegisterRoute
|
||||
}
|
||||
|
||||
declare module '@tanstack/react-router' {
|
||||
@@ -48,11 +195,135 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof IndexRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/app': {
|
||||
id: '/app'
|
||||
path: '/app'
|
||||
fullPath: '/app'
|
||||
preLoaderRoute: typeof AppRouteRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/login': {
|
||||
id: '/login'
|
||||
path: '/login'
|
||||
fullPath: '/login'
|
||||
preLoaderRoute: typeof LoginRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/register': {
|
||||
id: '/register'
|
||||
path: '/register'
|
||||
fullPath: '/register'
|
||||
preLoaderRoute: typeof RegisterRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/app/': {
|
||||
id: '/app/'
|
||||
path: '/'
|
||||
fullPath: '/app/'
|
||||
preLoaderRoute: typeof AppIndexRouteImport
|
||||
parentRoute: typeof AppRouteRoute
|
||||
}
|
||||
'/app/friends': {
|
||||
id: '/app/friends'
|
||||
path: '/friends'
|
||||
fullPath: '/app/friends'
|
||||
preLoaderRoute: typeof AppFriendsRouteImport
|
||||
parentRoute: typeof AppRouteRoute
|
||||
}
|
||||
'/app/settings': {
|
||||
id: '/app/settings'
|
||||
path: '/settings'
|
||||
fullPath: '/app/settings'
|
||||
preLoaderRoute: typeof AppSettingsRouteImport
|
||||
parentRoute: typeof AppRouteRoute
|
||||
}
|
||||
'/app/c/$conversationId': {
|
||||
id: '/app/c/$conversationId'
|
||||
path: '/c/$conversationId'
|
||||
fullPath: '/app/c/$conversationId'
|
||||
preLoaderRoute: typeof AppCConversationIdRouteImport
|
||||
parentRoute: typeof AppRouteRoute
|
||||
}
|
||||
'/app/invite/$code': {
|
||||
id: '/app/invite/$code'
|
||||
path: '/invite/$code'
|
||||
fullPath: '/app/invite/$code'
|
||||
preLoaderRoute: typeof AppInviteCodeRouteImport
|
||||
parentRoute: typeof AppRouteRoute
|
||||
}
|
||||
'/app/r/$realmId': {
|
||||
id: '/app/r/$realmId'
|
||||
path: '/r/$realmId'
|
||||
fullPath: '/app/r/$realmId'
|
||||
preLoaderRoute: typeof AppRRealmIdRouteRouteImport
|
||||
parentRoute: typeof AppRouteRoute
|
||||
}
|
||||
'/app/r/$realmId/': {
|
||||
id: '/app/r/$realmId/'
|
||||
path: '/'
|
||||
fullPath: '/app/r/$realmId/'
|
||||
preLoaderRoute: typeof AppRRealmIdIndexRouteImport
|
||||
parentRoute: typeof AppRRealmIdRouteRoute
|
||||
}
|
||||
'/app/r/$realmId/$cauldronId': {
|
||||
id: '/app/r/$realmId/$cauldronId'
|
||||
path: '/$cauldronId'
|
||||
fullPath: '/app/r/$realmId/$cauldronId'
|
||||
preLoaderRoute: typeof AppRRealmIdCauldronIdRouteImport
|
||||
parentRoute: typeof AppRRealmIdRouteRoute
|
||||
}
|
||||
'/app/r/$realmId/settings': {
|
||||
id: '/app/r/$realmId/settings'
|
||||
path: '/settings'
|
||||
fullPath: '/app/r/$realmId/settings'
|
||||
preLoaderRoute: typeof AppRRealmIdSettingsRouteImport
|
||||
parentRoute: typeof AppRRealmIdRouteRoute
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
interface AppRRealmIdRouteRouteChildren {
|
||||
AppRRealmIdCauldronIdRoute: typeof AppRRealmIdCauldronIdRoute
|
||||
AppRRealmIdSettingsRoute: typeof AppRRealmIdSettingsRoute
|
||||
AppRRealmIdIndexRoute: typeof AppRRealmIdIndexRoute
|
||||
}
|
||||
|
||||
const AppRRealmIdRouteRouteChildren: AppRRealmIdRouteRouteChildren = {
|
||||
AppRRealmIdCauldronIdRoute: AppRRealmIdCauldronIdRoute,
|
||||
AppRRealmIdSettingsRoute: AppRRealmIdSettingsRoute,
|
||||
AppRRealmIdIndexRoute: AppRRealmIdIndexRoute,
|
||||
}
|
||||
|
||||
const AppRRealmIdRouteRouteWithChildren =
|
||||
AppRRealmIdRouteRoute._addFileChildren(AppRRealmIdRouteRouteChildren)
|
||||
|
||||
interface AppRouteRouteChildren {
|
||||
AppFriendsRoute: typeof AppFriendsRoute
|
||||
AppSettingsRoute: typeof AppSettingsRoute
|
||||
AppIndexRoute: typeof AppIndexRoute
|
||||
AppRRealmIdRouteRoute: typeof AppRRealmIdRouteRouteWithChildren
|
||||
AppCConversationIdRoute: typeof AppCConversationIdRoute
|
||||
AppInviteCodeRoute: typeof AppInviteCodeRoute
|
||||
}
|
||||
|
||||
const AppRouteRouteChildren: AppRouteRouteChildren = {
|
||||
AppFriendsRoute: AppFriendsRoute,
|
||||
AppSettingsRoute: AppSettingsRoute,
|
||||
AppIndexRoute: AppIndexRoute,
|
||||
AppRRealmIdRouteRoute: AppRRealmIdRouteRouteWithChildren,
|
||||
AppCConversationIdRoute: AppCConversationIdRoute,
|
||||
AppInviteCodeRoute: AppInviteCodeRoute,
|
||||
}
|
||||
|
||||
const AppRouteRouteWithChildren = AppRouteRoute._addFileChildren(
|
||||
AppRouteRouteChildren,
|
||||
)
|
||||
|
||||
const rootRouteChildren: RootRouteChildren = {
|
||||
IndexRoute: IndexRoute,
|
||||
AppRouteRoute: AppRouteRouteWithChildren,
|
||||
LoginRoute: LoginRoute,
|
||||
RegisterRoute: RegisterRoute,
|
||||
}
|
||||
export const routeTree = rootRouteImport
|
||||
._addFileChildren(rootRouteChildren)
|
||||
|
||||
@@ -1,15 +1,34 @@
|
||||
import { QueryClient } from '@tanstack/react-query';
|
||||
import { createRouter as createTanStackRouter } from '@tanstack/react-router';
|
||||
import { setupRouterSsrQueryIntegration } from '@tanstack/react-router-ssr-query';
|
||||
import { routeTree } from './routeTree.gen';
|
||||
import { ApiError } from '@/lib/api';
|
||||
|
||||
export function getRouter() {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
// A 4xx answer (signed out, not found) won't change on a retry.
|
||||
retry: (failureCount, error) =>
|
||||
!(error instanceof ApiError && error.status < 500) &&
|
||||
failureCount < 2,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const router = createTanStackRouter({
|
||||
routeTree,
|
||||
context: { queryClient },
|
||||
|
||||
scrollRestoration: true,
|
||||
defaultPreload: 'intent',
|
||||
defaultPreloadStaleTime: 0,
|
||||
});
|
||||
|
||||
// Provides the QueryClient to components and carries server-fetched
|
||||
// query data over to the browser.
|
||||
setupRouterSsrQueryIntegration({ router, queryClient });
|
||||
|
||||
return router;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,18 @@
|
||||
import { HeadContent, Scripts, createRootRoute } from '@tanstack/react-router';
|
||||
import {
|
||||
HeadContent,
|
||||
Scripts,
|
||||
createRootRouteWithContext,
|
||||
} from '@tanstack/react-router';
|
||||
import type { QueryClient } from '@tanstack/react-query';
|
||||
|
||||
import appCss from '@repo/ui/globals.css?url';
|
||||
import { Toaster } from '@repo/ui/components/toast';
|
||||
import { TooltipProvider } from '@repo/ui/components/tooltip';
|
||||
import { site } from '@/lib/site';
|
||||
|
||||
export const Route = createRootRoute({
|
||||
export const Route = createRootRouteWithContext<{
|
||||
queryClient: QueryClient;
|
||||
}>()({
|
||||
head: () => ({
|
||||
meta: [
|
||||
{
|
||||
@@ -14,7 +23,7 @@ export const Route = createRootRoute({
|
||||
content: 'width=device-width, initial-scale=1',
|
||||
},
|
||||
{
|
||||
title: 'TanStack Start Starter',
|
||||
title: `${site.name} | ${site.tagline}`,
|
||||
},
|
||||
],
|
||||
links: [
|
||||
@@ -40,7 +49,9 @@ function RootDocument({ children }: { children: React.ReactNode }) {
|
||||
<HeadContent />
|
||||
</head>
|
||||
<body>
|
||||
<TooltipProvider>{children}</TooltipProvider>
|
||||
<TooltipProvider>
|
||||
<Toaster>{children}</Toaster>
|
||||
</TooltipProvider>
|
||||
<Scripts />
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
import { useQuery, useSuspenseQuery } from '@tanstack/react-query';
|
||||
import { Link, createFileRoute } from '@tanstack/react-router';
|
||||
import type { Conversation } from '@repo/contracts';
|
||||
import { Ban } from 'lucide-react';
|
||||
import { Button, buttonVariants } from '@repo/ui/components/button';
|
||||
import { toast } from '@repo/ui/components/toast';
|
||||
import { CallButton } from '@/components/call-button';
|
||||
import { ChatView } from '@/components/chat-view';
|
||||
import { ConfirmButton } from '@/components/confirm-button';
|
||||
import { ConversationAvatar } from '@/components/conversation-avatar';
|
||||
import { GroupDetailsDialog } from '@/components/group-details-dialog';
|
||||
import {
|
||||
conversationTitle,
|
||||
conversationsQuery,
|
||||
memberCount,
|
||||
messagesQuery,
|
||||
otherMember,
|
||||
} from '@/lib/conversations';
|
||||
import { showError } from '@/lib/errors';
|
||||
import { friendsQuery, useBlockUser, useUnblockUser } from '@/lib/friends';
|
||||
import { ownProfileQuery } from '@/lib/profile';
|
||||
|
||||
export const Route = createFileRoute('/app/c/$conversationId')({
|
||||
loader: async ({ context: { queryClient }, params: { conversationId } }) => {
|
||||
const [conversations] = await Promise.all([
|
||||
queryClient.ensureQueryData(conversationsQuery),
|
||||
queryClient.ensureInfiniteQueryData(messagesQuery(conversationId)),
|
||||
]);
|
||||
// The history loaded, so the conversation exists; a list without it was
|
||||
// fetched before it was created.
|
||||
if (!conversations.some((item) => item.id === conversationId)) {
|
||||
await queryClient.fetchQuery(conversationsQuery);
|
||||
}
|
||||
},
|
||||
errorComponent: ConversationMissing,
|
||||
component: ConversationPage,
|
||||
});
|
||||
|
||||
function ConversationPage() {
|
||||
const { conversationId } = Route.useParams();
|
||||
const { data: profile } = useSuspenseQuery(ownProfileQuery);
|
||||
const { data: conversations } = useSuspenseQuery(conversationsQuery);
|
||||
const conversation = conversations.find((item) => item.id === conversationId);
|
||||
|
||||
// Also where someone lands when they are taken out of a group they have
|
||||
// open: the list is fetched again and no longer has it.
|
||||
if (!conversation) return <ConversationMissing />;
|
||||
// The key gives each conversation its own draft and scroll position.
|
||||
return (
|
||||
<Chat
|
||||
key={conversation.id}
|
||||
conversation={conversation}
|
||||
ownId={profile.id}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function ConversationMissing() {
|
||||
return (
|
||||
<div className="flex flex-1 flex-col items-center justify-center gap-3 p-6 text-center">
|
||||
<h1 className="font-heading text-xl font-semibold">
|
||||
Conversation not found
|
||||
</h1>
|
||||
<p className="max-w-sm text-sm text-muted-foreground">
|
||||
It doesn't exist, or you aren't part of it.
|
||||
</p>
|
||||
<Link to="/app" className={buttonVariants({ variant: 'outline' })}>
|
||||
Back to your conversations
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Chat({
|
||||
conversation,
|
||||
ownId,
|
||||
}: {
|
||||
conversation: Conversation;
|
||||
/** The signed-in user's id. */
|
||||
ownId: string;
|
||||
}) {
|
||||
const title = conversationTitle(conversation, ownId);
|
||||
const isGroup = conversation.type === 'group';
|
||||
// A direct chat needs the friendship to post in; a group only membership.
|
||||
// Until the friends have loaded, assume it is there: the API has the final
|
||||
// say either way.
|
||||
const other = isGroup ? undefined : otherMember(conversation, ownId);
|
||||
const { data: friends } = useQuery(friendsQuery);
|
||||
const canPost =
|
||||
!other || (friends?.friends.some((f) => f.id === other.id) ?? true);
|
||||
// The other person, when the user has blocked them.
|
||||
const blocked =
|
||||
other && friends?.blocked.some((person) => person.id === other.id)
|
||||
? other
|
||||
: undefined;
|
||||
const block = useBlockUser();
|
||||
const unblock = useUnblockUser();
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col">
|
||||
<header className="flex items-center gap-3 border-b px-4 py-3">
|
||||
<ConversationAvatar conversation={conversation} ownId={ownId} />
|
||||
<div className="min-w-0 flex-1">
|
||||
<h1 className="truncate text-sm font-medium">{title}</h1>
|
||||
<p className="truncate text-xs text-muted-foreground">
|
||||
{isGroup
|
||||
? memberCount(conversation)
|
||||
: other?.username && `@${other.username}`}
|
||||
</p>
|
||||
</div>
|
||||
<CallButton
|
||||
place={{ conversationId: conversation.id, realmId: null, title }}
|
||||
canJoin={canPost}
|
||||
/>
|
||||
{other && friends && !blocked && (
|
||||
<ConfirmButton
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
aria-label={`Block ${title}`}
|
||||
title={`Block ${title}`}
|
||||
question={`Block ${title}?`}
|
||||
consequence="You stop being friends, and they can’t message you, call you or send you a friend request until you unblock them. They aren’t told."
|
||||
confirmLabel="Block"
|
||||
onConfirm={() =>
|
||||
block
|
||||
.mutateAsync(other.id)
|
||||
.then(() =>
|
||||
toast.add({ title: `${title} is blocked`, type: 'success' }),
|
||||
)
|
||||
}
|
||||
>
|
||||
<Ban aria-hidden="true" />
|
||||
</ConfirmButton>
|
||||
)}
|
||||
{isGroup && (
|
||||
<GroupDetailsDialog conversation={conversation} ownId={ownId} />
|
||||
)}
|
||||
</header>
|
||||
|
||||
<ChatView
|
||||
conversationId={conversation.id}
|
||||
title={title}
|
||||
unreadCount={conversation.unreadCount}
|
||||
canReact={canPost}
|
||||
canModerate={isGroup && conversation.ownerId === ownId}
|
||||
startOfHistory={
|
||||
isGroup
|
||||
? 'This is the start of the group.'
|
||||
: `This is the start of your conversation with ${title}.`
|
||||
}
|
||||
blockedNotice={
|
||||
canPost ? undefined : blocked ? (
|
||||
<>
|
||||
You blocked {title}, so neither of you can send messages here.{' '}
|
||||
<Button
|
||||
variant="link"
|
||||
size="sm"
|
||||
className="h-auto p-0"
|
||||
disabled={unblock.isPending}
|
||||
onClick={() =>
|
||||
unblock.mutate(blocked.id, { onError: showError })
|
||||
}
|
||||
>
|
||||
Unblock
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
`You and ${title} aren’t friends any more, so you can’t send messages here.`
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
import { useState } from 'react';
|
||||
import { useSuspenseQuery } from '@tanstack/react-query';
|
||||
import { createFileRoute, useNavigate } from '@tanstack/react-router';
|
||||
import { sendFriendRequestSchema } from '@repo/contracts';
|
||||
import type { UserSummary } from '@repo/contracts';
|
||||
import { Button } from '@repo/ui/components/button';
|
||||
import {
|
||||
Field,
|
||||
FieldDescription,
|
||||
FieldError,
|
||||
FieldLabel,
|
||||
} from '@repo/ui/components/field';
|
||||
import { Input } from '@repo/ui/components/input';
|
||||
import { Spinner } from '@repo/ui/components/spinner';
|
||||
import { toast } from '@repo/ui/components/toast';
|
||||
import { ConfirmButton } from '@/components/confirm-button';
|
||||
import { NewGroupDialog } from '@/components/new-group-dialog';
|
||||
import { PersonRow } from '@/components/person-row';
|
||||
import { useOpenDirectConversation } from '@/lib/conversations';
|
||||
import { errorMessage, showError } from '@/lib/errors';
|
||||
import {
|
||||
friendsQuery,
|
||||
useAcceptFriendRequest,
|
||||
useBlockUser,
|
||||
useRemoveFriend,
|
||||
useSendFriendRequest,
|
||||
useUnblockUser,
|
||||
} from '@/lib/friends';
|
||||
|
||||
export const Route = createFileRoute('/app/friends')({
|
||||
loader: ({ context }) => context.queryClient.ensureQueryData(friendsQuery),
|
||||
component: FriendsPage,
|
||||
});
|
||||
|
||||
function FriendsPage() {
|
||||
const { data } = useSuspenseQuery(friendsQuery);
|
||||
const navigate = useNavigate();
|
||||
const accept = useAcceptFriendRequest();
|
||||
const remove = useRemoveFriend();
|
||||
const openConversation = useOpenDirectConversation();
|
||||
const block = useBlockUser();
|
||||
const unblock = useUnblockUser();
|
||||
|
||||
function message(friend: UserSummary) {
|
||||
openConversation.mutate(friend.id, {
|
||||
onSuccess: (conversation) =>
|
||||
navigate({
|
||||
to: '/app/c/$conversationId',
|
||||
params: { conversationId: conversation.id },
|
||||
}),
|
||||
onError: showError,
|
||||
});
|
||||
}
|
||||
|
||||
// One request at a time per person keeps double clicks from racing.
|
||||
const busyWith = accept.isPending
|
||||
? accept.variables
|
||||
: remove.isPending
|
||||
? remove.variables
|
||||
: openConversation.isPending
|
||||
? openConversation.variables
|
||||
: unblock.isPending
|
||||
? unblock.variables
|
||||
: null;
|
||||
|
||||
const blockButton = (user: UserSummary) => (
|
||||
<ConfirmButton
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
disabled={busyWith === user.id}
|
||||
aria-label={`Block ${user.name}`}
|
||||
question={`Block ${user.name}?`}
|
||||
consequence="You stop being friends, and they can’t message you, call you or send you a friend request until you unblock them. They aren’t told."
|
||||
confirmLabel="Block"
|
||||
onConfirm={() => block.mutateAsync(user.id)}
|
||||
>
|
||||
Block
|
||||
</ConfirmButton>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="mx-auto flex w-full max-w-2xl flex-col gap-8 p-6 md:py-10">
|
||||
<header className="flex flex-col gap-1">
|
||||
<h1 className="font-heading text-2xl font-semibold">Friends</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Add people by username, then message them directly or start a group.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<AddFriendForm />
|
||||
|
||||
{data.incoming.length > 0 && (
|
||||
<Section title={`Requests for you (${data.incoming.length})`}>
|
||||
{data.incoming.map(({ user }) => (
|
||||
<PersonRow key={user.id} user={user}>
|
||||
<Button
|
||||
size="sm"
|
||||
disabled={busyWith === user.id}
|
||||
onClick={() => accept.mutate(user.id, { onError: showError })}
|
||||
>
|
||||
Accept
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={busyWith === user.id}
|
||||
onClick={() => remove.mutate(user.id, { onError: showError })}
|
||||
>
|
||||
Decline
|
||||
</Button>
|
||||
{blockButton(user)}
|
||||
</PersonRow>
|
||||
))}
|
||||
</Section>
|
||||
)}
|
||||
|
||||
{data.outgoing.length > 0 && (
|
||||
<Section title={`Requests you sent (${data.outgoing.length})`}>
|
||||
{data.outgoing.map(({ user }) => (
|
||||
<PersonRow key={user.id} user={user}>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={busyWith === user.id}
|
||||
onClick={() => remove.mutate(user.id, { onError: showError })}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
</PersonRow>
|
||||
))}
|
||||
</Section>
|
||||
)}
|
||||
|
||||
<Section
|
||||
title={`All friends (${data.friends.length})`}
|
||||
action={<NewGroupDialog variant="text" />}
|
||||
>
|
||||
{data.friends.length === 0 && (
|
||||
<li className="py-2 text-sm text-muted-foreground">
|
||||
No friends yet. Send a request above to get started.
|
||||
</li>
|
||||
)}
|
||||
{data.friends.map((friend) => (
|
||||
<PersonRow key={friend.id} user={friend}>
|
||||
<Button
|
||||
size="sm"
|
||||
disabled={busyWith === friend.id}
|
||||
onClick={() => message(friend)}
|
||||
>
|
||||
Message
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
disabled={busyWith === friend.id}
|
||||
onClick={() => remove.mutate(friend.id, { onError: showError })}
|
||||
>
|
||||
Remove
|
||||
</Button>
|
||||
{blockButton(friend)}
|
||||
</PersonRow>
|
||||
))}
|
||||
</Section>
|
||||
|
||||
{data.blocked.length > 0 && (
|
||||
<Section title={`Blocked (${data.blocked.length})`}>
|
||||
{data.blocked.map((user) => (
|
||||
<PersonRow key={user.id} user={user}>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={busyWith === user.id}
|
||||
aria-label={`Unblock ${user.name}`}
|
||||
onClick={() => unblock.mutate(user.id, { onError: showError })}
|
||||
>
|
||||
Unblock
|
||||
</Button>
|
||||
</PersonRow>
|
||||
))}
|
||||
</Section>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Section({
|
||||
title,
|
||||
action,
|
||||
children,
|
||||
}: {
|
||||
title: string;
|
||||
/** A button shown at the end of the heading's line. */
|
||||
action?: React.ReactNode;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<section className="flex flex-col gap-1">
|
||||
<div className="flex min-h-7 items-center justify-between gap-2">
|
||||
<h2 className="text-sm font-medium text-muted-foreground">{title}</h2>
|
||||
{action}
|
||||
</div>
|
||||
<ul className="flex flex-col divide-y">{children}</ul>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function AddFriendForm() {
|
||||
const sendRequest = useSendFriendRequest();
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
const form = event.currentTarget;
|
||||
const parsed = sendFriendRequestSchema.safeParse({
|
||||
username: new FormData(form).get('username'),
|
||||
});
|
||||
if (!parsed.success) {
|
||||
setError(parsed.error.issues[0]?.message ?? 'Enter a username.');
|
||||
return;
|
||||
}
|
||||
|
||||
setError(null);
|
||||
sendRequest.mutate(parsed.data, {
|
||||
onSuccess: ({ status, user }) => {
|
||||
form.reset();
|
||||
toast.add({
|
||||
title:
|
||||
status === 'accepted'
|
||||
? `You and ${user.name} are now friends`
|
||||
: `Request sent to ${user.name}`,
|
||||
type: 'success',
|
||||
});
|
||||
},
|
||||
onError: (failure) => {
|
||||
setError(
|
||||
errorMessage(
|
||||
failure,
|
||||
'Could not send the request. Please try again.',
|
||||
),
|
||||
);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} noValidate>
|
||||
<Field data-invalid={error ? true : undefined}>
|
||||
<FieldLabel htmlFor="friend-username">Add a friend</FieldLabel>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
id="friend-username"
|
||||
name="username"
|
||||
placeholder="Their username"
|
||||
autoComplete="off"
|
||||
autoCapitalize="none"
|
||||
spellCheck={false}
|
||||
aria-invalid={error ? true : undefined}
|
||||
/>
|
||||
<Button type="submit" disabled={sendRequest.isPending}>
|
||||
{sendRequest.isPending && <Spinner />}
|
||||
Send request
|
||||
</Button>
|
||||
</div>
|
||||
<FieldDescription>
|
||||
They'll see your request the moment you send it.
|
||||
</FieldDescription>
|
||||
<FieldError>{error}</FieldError>
|
||||
</Field>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { useQuery, useSuspenseQuery } from '@tanstack/react-query';
|
||||
import { Link, createFileRoute } from '@tanstack/react-router';
|
||||
import { MessagesSquare } from 'lucide-react';
|
||||
import { buttonVariants } from '@repo/ui/components/button';
|
||||
import {
|
||||
Empty,
|
||||
EmptyContent,
|
||||
EmptyDescription,
|
||||
EmptyHeader,
|
||||
EmptyMedia,
|
||||
EmptyTitle,
|
||||
} from '@repo/ui/components/empty';
|
||||
import { ConversationList } from '@/components/conversation-list';
|
||||
import { NewGroupDialog } from '@/components/new-group-dialog';
|
||||
import { NewRealmDialog } from '@/components/new-realm-dialog';
|
||||
import { RealmList } from '@/components/realm-list';
|
||||
import { conversationsQuery } from '@/lib/conversations';
|
||||
import { ownProfileQuery } from '@/lib/profile';
|
||||
import { realmsQuery } from '@/lib/realms';
|
||||
|
||||
export const Route = createFileRoute('/app/')({ component: AppHome });
|
||||
|
||||
function AppHome() {
|
||||
const { data: profile } = useSuspenseQuery(ownProfileQuery);
|
||||
const { data: conversations } = useQuery(conversationsQuery);
|
||||
const { data: realms } = useQuery(realmsQuery);
|
||||
const hasConversations = (conversations?.length ?? 0) > 0;
|
||||
const hasRealms = (realms?.length ?? 0) > 0;
|
||||
const hasLists = hasConversations || hasRealms;
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Phones have no sidebar, so realms and conversations are listed here. */}
|
||||
{hasLists && (
|
||||
<div className="flex flex-col gap-4 p-3 md:hidden">
|
||||
<section>
|
||||
<div className="flex items-center justify-between pb-2 pl-2">
|
||||
<h1 className="text-xs font-medium text-muted-foreground">
|
||||
Realms
|
||||
</h1>
|
||||
<NewRealmDialog />
|
||||
</div>
|
||||
<RealmList />
|
||||
</section>
|
||||
<section>
|
||||
<div className="flex items-center justify-between pb-2 pl-2">
|
||||
<h1 className="text-xs font-medium text-muted-foreground">
|
||||
Messages
|
||||
</h1>
|
||||
<NewGroupDialog />
|
||||
</div>
|
||||
<ConversationList ownId={profile.id} />
|
||||
</section>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className={hasLists ? 'hidden flex-1 md:flex' : 'flex flex-1'}>
|
||||
<Empty>
|
||||
<EmptyHeader>
|
||||
<EmptyMedia variant="icon">
|
||||
<MessagesSquare aria-hidden="true" />
|
||||
</EmptyMedia>
|
||||
<EmptyTitle>
|
||||
{hasConversations
|
||||
? 'Pick a conversation'
|
||||
: `Welcome, ${profile.name}`}
|
||||
</EmptyTitle>
|
||||
<EmptyDescription>
|
||||
{hasConversations
|
||||
? 'Choose someone from the list to keep talking.'
|
||||
: 'Add a friend to start your first conversation, or gather people in a realm.'}
|
||||
</EmptyDescription>
|
||||
</EmptyHeader>
|
||||
<EmptyContent className="flex-row justify-center">
|
||||
<Link
|
||||
to="/app/friends"
|
||||
className={buttonVariants({ variant: 'outline' })}
|
||||
>
|
||||
{hasConversations ? 'See your friends' : 'Find friends'}
|
||||
</Link>
|
||||
{!hasRealms && <NewRealmDialog variant="text" />}
|
||||
</EmptyContent>
|
||||
</Empty>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import { useSuspenseQuery } from '@tanstack/react-query';
|
||||
import { Link, createFileRoute, useNavigate } from '@tanstack/react-router';
|
||||
import { inviteCodeSchema } from '@repo/contracts';
|
||||
import { Button, buttonVariants } from '@repo/ui/components/button';
|
||||
import { Spinner } from '@repo/ui/components/spinner';
|
||||
import { RealmAvatar } from '@/components/realm-list';
|
||||
import { errorMessage } from '@/lib/errors';
|
||||
import {
|
||||
invitePreviewQuery,
|
||||
realmMemberCount,
|
||||
useAcceptInvite,
|
||||
} from '@/lib/realms';
|
||||
|
||||
export const Route = createFileRoute('/app/invite/$code')({
|
||||
loader: ({ context: { queryClient }, params: { code } }) => {
|
||||
// Not worth asking the API about something that can't be a code.
|
||||
if (!inviteCodeSchema.safeParse(code).success) {
|
||||
throw new Error('Not an invite code.');
|
||||
}
|
||||
return queryClient.fetchQuery(invitePreviewQuery(code));
|
||||
},
|
||||
errorComponent: InviteInvalid,
|
||||
component: InvitePage,
|
||||
});
|
||||
|
||||
function InvitePage() {
|
||||
const { code } = Route.useParams();
|
||||
const { data: invite } = useSuspenseQuery(invitePreviewQuery(code));
|
||||
const accept = useAcceptInvite();
|
||||
const navigate = useNavigate();
|
||||
const { realm } = invite;
|
||||
|
||||
return (
|
||||
<div className="flex flex-1 flex-col items-center justify-center gap-4 p-6 text-center">
|
||||
<RealmAvatar name={realm.name} className="size-14 text-2xl" />
|
||||
<div className="flex flex-col gap-1">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{invite.isBanned
|
||||
? 'You were banned from'
|
||||
: invite.isMember
|
||||
? 'You’re already in'
|
||||
: 'You’ve been invited to join'}
|
||||
</p>
|
||||
<h1 className="font-heading text-2xl font-semibold">{realm.name}</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{realmMemberCount(realm.memberCount)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{accept.isError && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{errorMessage(accept.error)}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{invite.isBanned ? (
|
||||
<>
|
||||
<p className="max-w-sm text-sm text-muted-foreground">
|
||||
This invite can’t let you back in. Someone who runs the realm would
|
||||
have to lift the ban first.
|
||||
</p>
|
||||
<Link to="/app" className={buttonVariants({ variant: 'outline' })}>
|
||||
Back to your conversations
|
||||
</Link>
|
||||
</>
|
||||
) : invite.isMember ? (
|
||||
<Link
|
||||
to="/app/r/$realmId"
|
||||
params={{ realmId: realm.id }}
|
||||
className={buttonVariants()}
|
||||
>
|
||||
Open {realm.name}
|
||||
</Link>
|
||||
) : (
|
||||
<div className="flex gap-2">
|
||||
<Link to="/app" className={buttonVariants({ variant: 'outline' })}>
|
||||
Not now
|
||||
</Link>
|
||||
<Button
|
||||
disabled={accept.isPending}
|
||||
onClick={() =>
|
||||
accept.mutate(code, {
|
||||
onSuccess: (joined) =>
|
||||
navigate({
|
||||
to: '/app/r/$realmId',
|
||||
params: { realmId: joined.id },
|
||||
}),
|
||||
})
|
||||
}
|
||||
>
|
||||
{accept.isPending && <Spinner />}
|
||||
Join {realm.name}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function InviteInvalid() {
|
||||
return (
|
||||
<div className="flex flex-1 flex-col items-center justify-center gap-3 p-6 text-center">
|
||||
<h1 className="font-heading text-xl font-semibold">
|
||||
This invite isn't valid
|
||||
</h1>
|
||||
<p className="max-w-sm text-sm text-muted-foreground">
|
||||
It may have expired, been used up or been taken back. Ask whoever sent
|
||||
it for a new link.
|
||||
</p>
|
||||
<Link to="/app" className={buttonVariants({ variant: 'outline' })}>
|
||||
Back to your conversations
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import { useSuspenseQuery } from '@tanstack/react-query';
|
||||
import { Link, createFileRoute } from '@tanstack/react-router';
|
||||
import { ArrowLeft, Hash, Users } from 'lucide-react';
|
||||
import { buttonVariants } from '@repo/ui/components/button';
|
||||
import { CallButton } from '@/components/call-button';
|
||||
import { ChatView } from '@/components/chat-view';
|
||||
import { messagesQuery } from '@/lib/conversations';
|
||||
import { can, realmMemberCount, realmQuery } from '@/lib/realms';
|
||||
|
||||
export const Route = createFileRoute('/app/r/$realmId/$cauldronId')({
|
||||
loader: ({ context: { queryClient }, params: { cauldronId } }) =>
|
||||
queryClient.ensureInfiniteQueryData(messagesQuery(cauldronId)),
|
||||
errorComponent: CauldronMissing,
|
||||
component: CauldronPage,
|
||||
});
|
||||
|
||||
function CauldronPage() {
|
||||
const { realmId, cauldronId } = Route.useParams();
|
||||
const { data: realm } = useSuspenseQuery(realmQuery(realmId));
|
||||
const cauldron = realm.cauldrons.find((item) => item.id === cauldronId);
|
||||
|
||||
// Also where everyone looking at a cauldron lands when it is deleted.
|
||||
if (!cauldron) return <CauldronMissing />;
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col">
|
||||
<header className="flex items-center gap-2 border-b px-4 py-3">
|
||||
<Link
|
||||
to="/app/r/$realmId"
|
||||
params={{ realmId }}
|
||||
aria-label={`Back to ${realm.name}`}
|
||||
className={buttonVariants({
|
||||
variant: 'ghost',
|
||||
size: 'icon-sm',
|
||||
className: 'md:hidden',
|
||||
})}
|
||||
>
|
||||
<ArrowLeft aria-hidden="true" />
|
||||
</Link>
|
||||
<Hash className="size-4 shrink-0 text-muted-foreground" aria-hidden />
|
||||
<div className="min-w-0 flex-1">
|
||||
<h1 className="truncate text-sm font-medium">{cauldron.name}</h1>
|
||||
<p className="truncate text-xs text-muted-foreground md:hidden">
|
||||
{realm.name}
|
||||
</p>
|
||||
</div>
|
||||
<CallButton
|
||||
place={{
|
||||
conversationId: cauldron.id,
|
||||
realmId,
|
||||
title: `#${cauldron.name}`,
|
||||
}}
|
||||
canJoin={can(realm, 'sendMessages')}
|
||||
/>
|
||||
<Link
|
||||
to="/app/r/$realmId/settings"
|
||||
params={{ realmId }}
|
||||
search={{ tab: 'members' }}
|
||||
aria-label={`Members, ${realmMemberCount(realm.memberCount)}`}
|
||||
title="Members"
|
||||
className={buttonVariants({ variant: 'ghost', size: 'sm' })}
|
||||
>
|
||||
<Users aria-hidden="true" />
|
||||
{realm.memberCount}
|
||||
</Link>
|
||||
</header>
|
||||
|
||||
{/* The key gives each cauldron its own draft and scroll position. */}
|
||||
<ChatView
|
||||
key={cauldron.id}
|
||||
conversationId={cauldron.id}
|
||||
title={`#${cauldron.name}`}
|
||||
startOfHistory={`This is the start of #${cauldron.name}.`}
|
||||
realmId={realmId}
|
||||
unreadCount={cauldron.unreadCount}
|
||||
canModerate={can(realm, 'manageMessages')}
|
||||
blockedNotice={
|
||||
can(realm, 'sendMessages')
|
||||
? undefined
|
||||
: 'You don’t have permission to post in this realm.'
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CauldronMissing() {
|
||||
const { realmId } = Route.useParams();
|
||||
return (
|
||||
<div className="flex flex-1 flex-col items-center justify-center gap-3 p-6 text-center">
|
||||
<h1 className="font-heading text-xl font-semibold">Cauldron not found</h1>
|
||||
<p className="max-w-sm text-sm text-muted-foreground">
|
||||
It may have been deleted.
|
||||
</p>
|
||||
<Link
|
||||
to="/app/r/$realmId"
|
||||
params={{ realmId }}
|
||||
className={buttonVariants({ variant: 'outline' })}
|
||||
>
|
||||
Back to the realm
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { useSuspenseQuery } from '@tanstack/react-query';
|
||||
import { Navigate, createFileRoute } from '@tanstack/react-router';
|
||||
import { FlaskConical } from 'lucide-react';
|
||||
import {
|
||||
Empty,
|
||||
EmptyDescription,
|
||||
EmptyHeader,
|
||||
EmptyMedia,
|
||||
EmptyTitle,
|
||||
} from '@repo/ui/components/empty';
|
||||
import { RealmSidebar } from '@/components/realm-sidebar';
|
||||
import { can, realmQuery } from '@/lib/realms';
|
||||
import { WIDE_SCREEN, useMediaQuery } from '@/lib/use-media-query';
|
||||
|
||||
export const Route = createFileRoute('/app/r/$realmId/')({
|
||||
component: RealmHome,
|
||||
});
|
||||
|
||||
function RealmHome() {
|
||||
const { realmId } = Route.useParams();
|
||||
const { data: realm } = useSuspenseQuery(realmQuery(realmId));
|
||||
const isWide = useMediaQuery(WIDE_SCREEN);
|
||||
const first = realm.cauldrons.at(0);
|
||||
|
||||
// Phones have no column for the realm, so its cauldrons are listed here.
|
||||
if (!isWide) return <RealmSidebar realm={realm} className="flex-1" />;
|
||||
// Wide screens show that column already: go straight to a cauldron.
|
||||
if (first) {
|
||||
return (
|
||||
<Navigate
|
||||
to="/app/r/$realmId/$cauldronId"
|
||||
params={{ realmId, cauldronId: first.id }}
|
||||
replace
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Empty>
|
||||
<EmptyHeader>
|
||||
<EmptyMedia variant="icon">
|
||||
<FlaskConical aria-hidden="true" />
|
||||
</EmptyMedia>
|
||||
<EmptyTitle>No cauldrons yet</EmptyTitle>
|
||||
<EmptyDescription>
|
||||
{can(realm, 'manageCauldrons')
|
||||
? 'Add one with the plus next to “Cauldrons”.'
|
||||
: 'Someone who looks after this realm has to add one.'}
|
||||
</EmptyDescription>
|
||||
</EmptyHeader>
|
||||
</Empty>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { useSuspenseQuery } from '@tanstack/react-query';
|
||||
import { Outlet, createFileRoute } from '@tanstack/react-router';
|
||||
import { RealmMissing } from '@/components/realm-missing';
|
||||
import { RealmSidebar } from '@/components/realm-sidebar';
|
||||
import { realmQuery, realmsQuery } from '@/lib/realms';
|
||||
|
||||
export const Route = createFileRoute('/app/r/$realmId')({
|
||||
loader: async ({ context: { queryClient }, params: { realmId } }) => {
|
||||
const [realms] = await Promise.all([
|
||||
queryClient.ensureQueryData(realmsQuery),
|
||||
queryClient.ensureQueryData(realmQuery(realmId)),
|
||||
]);
|
||||
// The realm loaded, so the user is in it; a list without it was fetched
|
||||
// before they joined.
|
||||
if (!realms.some((item) => item.id === realmId)) {
|
||||
await queryClient.fetchQuery(realmsQuery);
|
||||
}
|
||||
},
|
||||
errorComponent: RealmMissing,
|
||||
component: RealmLayout,
|
||||
});
|
||||
|
||||
function RealmLayout() {
|
||||
const { realmId } = Route.useParams();
|
||||
const { data: realms } = useSuspenseQuery(realmsQuery);
|
||||
const { data: realm } = useSuspenseQuery(realmQuery(realmId));
|
||||
|
||||
// The list is what says whether the user is still in the realm: once they
|
||||
// leave or are removed it is fetched again, while the realm's own details
|
||||
// stay as they last were.
|
||||
if (!realms.some((item) => item.id === realmId)) return <RealmMissing />;
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1">
|
||||
{/* On phones the realm's own page shows this instead. */}
|
||||
<RealmSidebar
|
||||
realm={realm}
|
||||
className="hidden w-56 shrink-0 border-r md:flex"
|
||||
/>
|
||||
<div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-y-auto">
|
||||
<Outlet />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,645 @@
|
||||
import { useState } from 'react';
|
||||
import { useQuery, useSuspenseQuery } from '@tanstack/react-query';
|
||||
import { Link, createFileRoute, useNavigate } from '@tanstack/react-router';
|
||||
import { REALM_MAX_ROLES, REALM_NAME_MAX_LENGTH } from '@repo/contracts';
|
||||
import type { Realm, RealmBan, RealmInvite } from '@repo/contracts';
|
||||
import { ArrowLeft, Copy, Hash, Plus } from 'lucide-react';
|
||||
import { Badge } from '@repo/ui/components/badge';
|
||||
import { Button, buttonVariants } from '@repo/ui/components/button';
|
||||
import { Field, FieldLabel } from '@repo/ui/components/field';
|
||||
import { Input } from '@repo/ui/components/input';
|
||||
import { Spinner } from '@repo/ui/components/spinner';
|
||||
import {
|
||||
Tabs,
|
||||
TabsContent,
|
||||
TabsList,
|
||||
TabsTrigger,
|
||||
} from '@repo/ui/components/tabs';
|
||||
import { toast } from '@repo/ui/components/toast';
|
||||
import { BanDialog } from '@/components/ban-dialog';
|
||||
import { CauldronDialog } from '@/components/cauldron-dialog';
|
||||
import { ConfirmButton } from '@/components/confirm-button';
|
||||
import { InviteDialog, copyInviteLink } from '@/components/invite-dialog';
|
||||
import { MemberRolesDialog } from '@/components/member-roles-dialog';
|
||||
import { PersonRow } from '@/components/person-row';
|
||||
import { RoleDialog } from '@/components/role-dialog';
|
||||
import { showError } from '@/lib/errors';
|
||||
import { formatDateTime } from '@/lib/format';
|
||||
import { ownProfileQuery } from '@/lib/profile';
|
||||
import {
|
||||
PERMISSION_LABELS,
|
||||
can,
|
||||
canBanMember,
|
||||
canManageRole,
|
||||
canRemoveMember,
|
||||
realmBansQuery,
|
||||
realmInvitesQuery,
|
||||
realmMemberCount,
|
||||
realmMembersQuery,
|
||||
realmQuery,
|
||||
useDeleteCauldron,
|
||||
useDeleteRealm,
|
||||
useDeleteRole,
|
||||
useRemoveRealmMember,
|
||||
useRenameRealm,
|
||||
useRevokeInvite,
|
||||
useUnbanMember,
|
||||
} from '@/lib/realms';
|
||||
|
||||
const TABS = [
|
||||
'overview',
|
||||
'cauldrons',
|
||||
'members',
|
||||
'roles',
|
||||
'invites',
|
||||
'bans',
|
||||
] as const;
|
||||
type Tab = (typeof TABS)[number];
|
||||
|
||||
const TAB_LABELS: Record<Tab, string> = {
|
||||
overview: 'Overview',
|
||||
cauldrons: 'Cauldrons',
|
||||
members: 'Members',
|
||||
roles: 'Roles',
|
||||
invites: 'Invites',
|
||||
bans: 'Bans',
|
||||
};
|
||||
|
||||
export const Route = createFileRoute('/app/r/$realmId/settings')({
|
||||
// Always returns the key, so an unknown ?tab= can't slip through.
|
||||
validateSearch: (search: Record<string, unknown>): { tab?: Tab } => ({
|
||||
tab: TABS.find((tab) => tab === search.tab),
|
||||
}),
|
||||
component: RealmSettings,
|
||||
});
|
||||
|
||||
function RealmSettings() {
|
||||
const { realmId } = Route.useParams();
|
||||
const { tab } = Route.useSearch();
|
||||
const navigate = Route.useNavigate();
|
||||
const { data: realm } = useSuspenseQuery(realmQuery(realmId));
|
||||
const { data: profile } = useSuspenseQuery(ownProfileQuery);
|
||||
|
||||
// People only see the tabs they can do something in.
|
||||
const visible = TABS.filter((item) => {
|
||||
if (item === 'cauldrons') return can(realm, 'manageCauldrons');
|
||||
if (item === 'roles') return can(realm, 'manageRoles');
|
||||
if (item === 'bans') return can(realm, 'banMembers');
|
||||
if (item === 'invites') {
|
||||
return can(realm, 'createInvites') || can(realm, 'manageRealm');
|
||||
}
|
||||
return true;
|
||||
});
|
||||
const current = tab && visible.includes(tab) ? tab : 'overview';
|
||||
|
||||
return (
|
||||
<div className="mx-auto flex w-full max-w-2xl flex-col gap-6 p-6 md:py-10">
|
||||
<header className="flex items-center gap-2">
|
||||
<Link
|
||||
to="/app/r/$realmId"
|
||||
params={{ realmId }}
|
||||
aria-label={`Back to ${realm.name}`}
|
||||
className={buttonVariants({ variant: 'ghost', size: 'icon-sm' })}
|
||||
>
|
||||
<ArrowLeft aria-hidden="true" />
|
||||
</Link>
|
||||
<div className="min-w-0">
|
||||
<h1 className="truncate font-heading text-2xl font-semibold">
|
||||
{realm.name}
|
||||
</h1>
|
||||
<p className="text-sm text-muted-foreground">Realm settings</p>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<Tabs
|
||||
value={current}
|
||||
onValueChange={(value) =>
|
||||
void navigate({
|
||||
search: { tab: TABS.find((item) => item === value) },
|
||||
replace: true,
|
||||
})
|
||||
}
|
||||
className="gap-6"
|
||||
>
|
||||
<TabsList className="max-w-full overflow-x-auto">
|
||||
{visible.map((item) => (
|
||||
<TabsTrigger key={item} value={item}>
|
||||
{TAB_LABELS[item]}
|
||||
</TabsTrigger>
|
||||
))}
|
||||
</TabsList>
|
||||
<TabsContent value="overview">
|
||||
<OverviewTab realm={realm} ownId={profile.id} />
|
||||
</TabsContent>
|
||||
<TabsContent value="cauldrons">
|
||||
<CauldronsTab realm={realm} />
|
||||
</TabsContent>
|
||||
<TabsContent value="members">
|
||||
<MembersTab realm={realm} ownId={profile.id} />
|
||||
</TabsContent>
|
||||
<TabsContent value="roles">
|
||||
<RolesTab realm={realm} />
|
||||
</TabsContent>
|
||||
<TabsContent value="invites">
|
||||
<InvitesTab realm={realm} ownId={profile.id} />
|
||||
</TabsContent>
|
||||
<TabsContent value="bans">
|
||||
<BansTab realm={realm} ownId={profile.id} />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface TabProps {
|
||||
realm: Realm;
|
||||
}
|
||||
interface OwnTabProps extends TabProps {
|
||||
/** The signed-in user's id. */
|
||||
ownId: string;
|
||||
}
|
||||
|
||||
function Section({
|
||||
title,
|
||||
action,
|
||||
children,
|
||||
}: {
|
||||
title: string;
|
||||
action?: React.ReactNode;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<section className="flex flex-col gap-2">
|
||||
<div className="flex min-h-7 items-center justify-between gap-2">
|
||||
<h2 className="text-sm font-medium text-muted-foreground">{title}</h2>
|
||||
{action}
|
||||
</div>
|
||||
{children}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function OverviewTab({ realm, ownId }: OwnTabProps) {
|
||||
const isOwner = realm.ownerId === ownId;
|
||||
const navigate = useNavigate();
|
||||
const leave = useRemoveRealmMember(realm.id);
|
||||
const deleteRealm = useDeleteRealm(realm.id);
|
||||
|
||||
function goHome(message: string) {
|
||||
toast.add({ title: message, type: 'success' });
|
||||
void navigate({ to: '/app' });
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-8">
|
||||
{can(realm, 'manageRealm') ? (
|
||||
<RenameForm realm={realm} />
|
||||
) : (
|
||||
<Section title="About">
|
||||
<p className="text-sm">
|
||||
{realm.name} has {realmMemberCount(realm.memberCount)} and{' '}
|
||||
{realm.cauldrons.length === 1
|
||||
? '1 cauldron'
|
||||
: `${realm.cauldrons.length} cauldrons`}
|
||||
.
|
||||
</p>
|
||||
</Section>
|
||||
)}
|
||||
|
||||
{isOwner ? (
|
||||
<Section title="Delete realm">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
You own this realm, so you can’t leave it. Deleting it removes its
|
||||
cauldrons and every message in them, for everyone.
|
||||
</p>
|
||||
<ConfirmButton
|
||||
variant="destructive"
|
||||
className="self-start"
|
||||
question={`Delete ${realm.name}?`}
|
||||
consequence="Its cauldrons, messages, roles and invites are deleted for all of its members. This can’t be undone."
|
||||
confirmLabel="Delete realm"
|
||||
onConfirm={() =>
|
||||
deleteRealm
|
||||
.mutateAsync()
|
||||
.then(() => goHome(`${realm.name} was deleted`))
|
||||
}
|
||||
>
|
||||
Delete realm
|
||||
</ConfirmButton>
|
||||
</Section>
|
||||
) : (
|
||||
<Section title="Leave realm">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
You lose your roles here. To come back you need a new invite.
|
||||
</p>
|
||||
<ConfirmButton
|
||||
variant="destructive"
|
||||
className="self-start"
|
||||
question={`Leave ${realm.name}?`}
|
||||
consequence="Your messages stay. To come back you need a new invite, and you start without your roles."
|
||||
confirmLabel="Leave realm"
|
||||
onConfirm={() =>
|
||||
leave
|
||||
.mutateAsync(ownId)
|
||||
.then(() => goHome(`You left ${realm.name}`))
|
||||
}
|
||||
>
|
||||
Leave realm
|
||||
</ConfirmButton>
|
||||
</Section>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function RenameForm({ realm }: TabProps) {
|
||||
const rename = useRenameRealm(realm.id);
|
||||
const [name, setName] = useState(realm.name);
|
||||
|
||||
return (
|
||||
<form
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
rename.mutate(name, {
|
||||
onSuccess: (updated) => {
|
||||
setName(updated.name);
|
||||
toast.add({ title: 'Realm renamed', type: 'success' });
|
||||
},
|
||||
onError: showError,
|
||||
});
|
||||
}}
|
||||
>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="realm-rename">Name</FieldLabel>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
id="realm-rename"
|
||||
value={name}
|
||||
maxLength={REALM_NAME_MAX_LENGTH}
|
||||
autoComplete="off"
|
||||
onChange={(event) => setName(event.target.value)}
|
||||
/>
|
||||
<Button
|
||||
type="submit"
|
||||
variant="outline"
|
||||
disabled={
|
||||
name.trim() === '' ||
|
||||
name.trim() === realm.name ||
|
||||
rename.isPending
|
||||
}
|
||||
>
|
||||
{rename.isPending && <Spinner />}
|
||||
Save
|
||||
</Button>
|
||||
</div>
|
||||
</Field>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function CauldronsTab({ realm }: TabProps) {
|
||||
const deleteCauldron = useDeleteCauldron(realm.id);
|
||||
|
||||
return (
|
||||
<Section
|
||||
title={`Cauldrons (${realm.cauldrons.length})`}
|
||||
action={
|
||||
<CauldronDialog realmId={realm.id} variant="outline" size="sm">
|
||||
<Plus aria-hidden="true" />
|
||||
New cauldron
|
||||
</CauldronDialog>
|
||||
}
|
||||
>
|
||||
{realm.cauldrons.length === 0 ? (
|
||||
<p className="py-2 text-sm text-muted-foreground">
|
||||
This realm has no cauldrons, so there is nowhere to talk yet.
|
||||
</p>
|
||||
) : (
|
||||
<ul className="flex flex-col divide-y">
|
||||
{realm.cauldrons.map((cauldron) => (
|
||||
<li key={cauldron.id} className="flex items-center gap-2 py-2">
|
||||
<Hash
|
||||
className="size-4 shrink-0 text-muted-foreground"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span className="min-w-0 flex-1 truncate text-sm font-medium">
|
||||
{cauldron.name}
|
||||
</span>
|
||||
<CauldronDialog
|
||||
realmId={realm.id}
|
||||
cauldron={cauldron}
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
aria-label={`Rename ${cauldron.name}`}
|
||||
>
|
||||
Rename
|
||||
</CauldronDialog>
|
||||
<ConfirmButton
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
aria-label={`Delete ${cauldron.name}`}
|
||||
question={`Delete #${cauldron.name}?`}
|
||||
consequence="Every message in it is deleted for everyone. This can’t be undone."
|
||||
confirmLabel="Delete cauldron"
|
||||
onConfirm={() => deleteCauldron.mutateAsync(cauldron.id)}
|
||||
>
|
||||
Delete
|
||||
</ConfirmButton>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
|
||||
function MembersTab({ realm, ownId }: OwnTabProps) {
|
||||
const { data: members } = useQuery(realmMembersQuery(realm.id));
|
||||
const remove = useRemoveRealmMember(realm.id);
|
||||
const assignable = realm.roles.filter((role) => !role.isDefault);
|
||||
const isOwner = realm.ownerId === ownId;
|
||||
|
||||
if (!members) return <Spinner aria-label="Loading members" />;
|
||||
|
||||
return (
|
||||
<Section title={`Members (${members.length})`}>
|
||||
<ul className="flex flex-col divide-y">
|
||||
{members.map((member) => {
|
||||
const { user } = member;
|
||||
const isRealmOwner = user.id === realm.ownerId;
|
||||
return (
|
||||
<PersonRow key={user.id} user={user}>
|
||||
<div className="hidden flex-wrap justify-end gap-1 sm:flex">
|
||||
{isRealmOwner && <Badge variant="secondary">Owner</Badge>}
|
||||
{assignable
|
||||
.filter((role) => member.roleIds.includes(role.id))
|
||||
.map((role) => (
|
||||
<Badge key={role.id} variant="outline">
|
||||
{role.name}
|
||||
</Badge>
|
||||
))}
|
||||
{user.id === ownId && <Badge variant="outline">You</Badge>}
|
||||
</div>
|
||||
{can(realm, 'manageRoles') &&
|
||||
assignable.length > 0 &&
|
||||
(isOwner || !isRealmOwner) && (
|
||||
<MemberRolesDialog
|
||||
realm={realm}
|
||||
member={member}
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
aria-label={`Roles of ${user.name}`}
|
||||
>
|
||||
Roles
|
||||
</MemberRolesDialog>
|
||||
)}
|
||||
{user.id !== ownId && canRemoveMember(realm, member) && (
|
||||
<ConfirmButton
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
aria-label={`Remove ${user.name}`}
|
||||
question={`Remove ${user.name} from ${realm.name}?`}
|
||||
consequence="Their messages stay. They can come back with an invite link, without their roles."
|
||||
confirmLabel="Remove"
|
||||
onConfirm={() => remove.mutateAsync(user.id)}
|
||||
>
|
||||
Remove
|
||||
</ConfirmButton>
|
||||
)}
|
||||
{user.id !== ownId && canBanMember(realm, member) && (
|
||||
<BanDialog
|
||||
realmId={realm.id}
|
||||
realmName={realm.name}
|
||||
user={user}
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
aria-label={`Ban ${user.name}`}
|
||||
>
|
||||
Ban
|
||||
</BanDialog>
|
||||
)}
|
||||
</PersonRow>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
|
||||
function RolesTab({ realm }: TabProps) {
|
||||
const deleteRole = useDeleteRole(realm.id);
|
||||
|
||||
return (
|
||||
<Section
|
||||
title={`Roles (${realm.roles.length} of ${REALM_MAX_ROLES})`}
|
||||
action={
|
||||
<RoleDialog
|
||||
realm={realm}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={realm.roles.length >= REALM_MAX_ROLES}
|
||||
>
|
||||
<Plus aria-hidden="true" />
|
||||
New role
|
||||
</RoleDialog>
|
||||
}
|
||||
>
|
||||
<ul className="flex flex-col divide-y">
|
||||
{realm.roles.map((role) => {
|
||||
const isManageable = canManageRole(realm, role);
|
||||
return (
|
||||
<li key={role.id} className="flex items-center gap-2 py-2">
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="flex items-center gap-2 text-sm font-medium">
|
||||
<span className="truncate">{role.name}</span>
|
||||
{role.isDefault && (
|
||||
<Badge variant="secondary">All members</Badge>
|
||||
)}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{role.permissions.length === 0
|
||||
? 'Allows nothing extra'
|
||||
: role.permissions
|
||||
.map((permission) => PERMISSION_LABELS[permission].name)
|
||||
.join(', ')}
|
||||
</p>
|
||||
</div>
|
||||
{isManageable ? (
|
||||
<>
|
||||
<RoleDialog
|
||||
realm={realm}
|
||||
role={role}
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
aria-label={`Edit ${role.name}`}
|
||||
>
|
||||
Edit
|
||||
</RoleDialog>
|
||||
{!role.isDefault && (
|
||||
<ConfirmButton
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
aria-label={`Delete ${role.name}`}
|
||||
question={`Delete the ${role.name} role?`}
|
||||
consequence="Everyone who holds it loses what it allows."
|
||||
confirmLabel="Delete role"
|
||||
onConfirm={() => deleteRole.mutateAsync(role.id)}
|
||||
>
|
||||
Delete
|
||||
</ConfirmButton>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
Allows more than you can do
|
||||
</span>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
|
||||
function InvitesTab({ realm, ownId }: OwnTabProps) {
|
||||
const { data: invites } = useQuery(realmInvitesQuery(realm.id));
|
||||
const revoke = useRevokeInvite(realm.id);
|
||||
const seesAll = can(realm, 'manageRealm');
|
||||
|
||||
return (
|
||||
<Section
|
||||
title={seesAll ? 'Invite links' : 'Your invite links'}
|
||||
action={
|
||||
can(realm, 'createInvites') && (
|
||||
<InviteDialog
|
||||
realmId={realm.id}
|
||||
realmName={realm.name}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
>
|
||||
<Plus aria-hidden="true" />
|
||||
New invite
|
||||
</InviteDialog>
|
||||
)
|
||||
}
|
||||
>
|
||||
{!invites ? (
|
||||
<Spinner aria-label="Loading invites" />
|
||||
) : invites.length === 0 ? (
|
||||
<p className="py-2 text-sm text-muted-foreground">
|
||||
No invite links that still work.
|
||||
</p>
|
||||
) : (
|
||||
<ul className="flex flex-col divide-y">
|
||||
{invites.map((invite) => (
|
||||
<li key={invite.code} className="flex items-center gap-2 py-2">
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate font-mono text-sm">{invite.code}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{describeInvite(invite, ownId)}
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
aria-label={`Copy the link of invite ${invite.code}`}
|
||||
onClick={() => void copyInviteLink(invite.code)}
|
||||
>
|
||||
<Copy aria-hidden="true" />
|
||||
Copy
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
aria-label={`Revoke invite ${invite.code}`}
|
||||
disabled={revoke.isPending}
|
||||
onClick={() =>
|
||||
revoke.mutate(invite.code, { onError: showError })
|
||||
}
|
||||
>
|
||||
Revoke
|
||||
</Button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
|
||||
function BansTab({ realm, ownId }: OwnTabProps) {
|
||||
const { data: bans } = useQuery(realmBansQuery(realm.id));
|
||||
const unban = useUnbanMember(realm.id);
|
||||
|
||||
if (!bans) return <Spinner aria-label="Loading bans" />;
|
||||
|
||||
return (
|
||||
<Section title={`Banned (${bans.length})`}>
|
||||
{bans.length === 0 ? (
|
||||
<p className="py-2 text-sm text-muted-foreground">
|
||||
Nobody is banned from {realm.name}.
|
||||
</p>
|
||||
) : (
|
||||
<ul className="flex flex-col divide-y">
|
||||
{bans.map((ban) => (
|
||||
<li key={ban.user.id} className="flex items-center gap-2 py-2">
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate text-sm font-medium">
|
||||
{ban.user.name}
|
||||
{ban.user.username && (
|
||||
<span className="font-normal text-muted-foreground">
|
||||
{' '}
|
||||
@{ban.user.username}
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{describeBan(ban, ownId)}
|
||||
</p>
|
||||
{ban.reason && (
|
||||
<p className="text-xs wrap-break-word">{ban.reason}</p>
|
||||
)}
|
||||
</div>
|
||||
<ConfirmButton
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
aria-label={`Unban ${ban.user.name}`}
|
||||
question={`Lift the ban on ${ban.user.name}?`}
|
||||
consequence="They can join again with an invite link. They aren’t brought back by this."
|
||||
confirmLabel="Unban"
|
||||
onConfirm={() => unban.mutateAsync(ban.user.id)}
|
||||
>
|
||||
Unban
|
||||
</ConfirmButton>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
|
||||
/** "By Mia · 9 Dec 2026, 11:20". */
|
||||
function describeBan(ban: RealmBan, ownId: string): string {
|
||||
const by = !ban.bannedBy
|
||||
? 'By someone who has left'
|
||||
: ban.bannedBy.id === ownId
|
||||
? 'By you'
|
||||
: `By ${ban.bannedBy.name}`;
|
||||
return `${by} · ${formatDateTime(ban.createdAt)}`;
|
||||
}
|
||||
|
||||
/** "By Mia · used 2 of 5 times · expires 9 Dec 2026, 11:20". */
|
||||
function describeInvite(invite: RealmInvite, ownId: string): string {
|
||||
const by =
|
||||
invite.createdBy.id === ownId ? 'By you' : `By ${invite.createdBy.name}`;
|
||||
const uses =
|
||||
invite.maxUses === null
|
||||
? `used ${invite.uses === 1 ? 'once' : `${invite.uses} times`}`
|
||||
: `used ${invite.uses} of ${invite.maxUses} times`;
|
||||
const expiry = invite.expiresAt
|
||||
? `expires ${formatDateTime(invite.expiresAt)}`
|
||||
: 'never expires';
|
||||
return [by, uses, expiry].join(' · ');
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
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'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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
import { useState } from 'react';
|
||||
import { useSuspenseQuery } from '@tanstack/react-query';
|
||||
import { createFileRoute } from '@tanstack/react-router';
|
||||
import {
|
||||
BIO_MAX_LENGTH,
|
||||
NAME_MAX_LENGTH,
|
||||
USERNAME_MAX_LENGTH,
|
||||
USERNAME_MIN_LENGTH,
|
||||
updateProfileSchema,
|
||||
} from '@repo/contracts';
|
||||
import { Alert, AlertDescription } from '@repo/ui/components/alert';
|
||||
import { Button } from '@repo/ui/components/button';
|
||||
import {
|
||||
Field,
|
||||
FieldDescription,
|
||||
FieldError,
|
||||
FieldGroup,
|
||||
FieldLabel,
|
||||
} from '@repo/ui/components/field';
|
||||
import { Input } from '@repo/ui/components/input';
|
||||
import { Separator } from '@repo/ui/components/separator';
|
||||
import { Spinner } from '@repo/ui/components/spinner';
|
||||
import { Textarea } from '@repo/ui/components/textarea';
|
||||
import { toast } from '@repo/ui/components/toast';
|
||||
import { NotificationSettings } from '@/components/notification-settings';
|
||||
import { ApiError } from '@/lib/api';
|
||||
import { ownProfileQuery, useUpdateProfile } from '@/lib/profile';
|
||||
|
||||
export const Route = createFileRoute('/app/settings')({
|
||||
component: ProfileSettings,
|
||||
});
|
||||
|
||||
type FieldName = 'name' | 'username' | 'bio';
|
||||
type FieldErrors = Partial<Record<FieldName, string>>;
|
||||
|
||||
function ProfileSettings() {
|
||||
const { data: profile } = useSuspenseQuery(ownProfileQuery);
|
||||
const updateProfile = useUpdateProfile();
|
||||
const [fieldErrors, setFieldErrors] = useState<FieldErrors>({});
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
|
||||
function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
const form = new FormData(event.currentTarget);
|
||||
const parsed = updateProfileSchema.safeParse({
|
||||
name: form.get('name'),
|
||||
username: form.get('username'),
|
||||
bio: form.get('bio'),
|
||||
});
|
||||
|
||||
setFormError(null);
|
||||
if (!parsed.success) {
|
||||
const errors: FieldErrors = {};
|
||||
for (const issue of parsed.error.issues) {
|
||||
const field = issue.path[0] as FieldName;
|
||||
errors[field] ??= issue.message;
|
||||
}
|
||||
setFieldErrors(errors);
|
||||
return;
|
||||
}
|
||||
|
||||
setFieldErrors({});
|
||||
updateProfile.mutate(parsed.data, {
|
||||
onSuccess: () => {
|
||||
toast.add({ title: 'Profile saved', type: 'success' });
|
||||
},
|
||||
onError: (error) => {
|
||||
// 409 is the API's answer for a username someone else has.
|
||||
if (error instanceof ApiError && error.status === 409) {
|
||||
setFieldErrors({ username: error.message });
|
||||
} else if (error instanceof ApiError) {
|
||||
setFormError(error.message);
|
||||
} else {
|
||||
setFormError('Could not save your profile. Please try again.');
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mx-auto flex w-full max-w-xl flex-col gap-6 p-6 md:py-10">
|
||||
<header className="flex flex-col gap-1">
|
||||
<h1 className="font-heading text-2xl font-semibold">Profile</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
How you appear to other people.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
{profile.username === null && (
|
||||
<Alert>
|
||||
<AlertDescription>
|
||||
Choose a username to finish setting up your account.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* Remounts with the saved values, e.g. a username the API lower-cased. */}
|
||||
<form
|
||||
key={`${profile.name}|${profile.username}|${profile.bio}`}
|
||||
onSubmit={handleSubmit}
|
||||
noValidate
|
||||
>
|
||||
<FieldGroup>
|
||||
<Field data-invalid={fieldErrors.name ? true : undefined}>
|
||||
<FieldLabel htmlFor="name">Name</FieldLabel>
|
||||
<Input
|
||||
id="name"
|
||||
name="name"
|
||||
autoComplete="name"
|
||||
defaultValue={profile.name}
|
||||
maxLength={NAME_MAX_LENGTH}
|
||||
aria-invalid={fieldErrors.name ? true : undefined}
|
||||
/>
|
||||
<FieldError>{fieldErrors.name}</FieldError>
|
||||
</Field>
|
||||
|
||||
<Field data-invalid={fieldErrors.username ? true : undefined}>
|
||||
<FieldLabel htmlFor="username">Username</FieldLabel>
|
||||
<Input
|
||||
id="username"
|
||||
name="username"
|
||||
autoComplete="username"
|
||||
autoCapitalize="none"
|
||||
spellCheck={false}
|
||||
defaultValue={profile.username ?? ''}
|
||||
minLength={USERNAME_MIN_LENGTH}
|
||||
maxLength={USERNAME_MAX_LENGTH}
|
||||
aria-invalid={fieldErrors.username ? true : undefined}
|
||||
/>
|
||||
<FieldDescription>
|
||||
How friends find you. Letters, numbers, underscores and dots.
|
||||
</FieldDescription>
|
||||
<FieldError>{fieldErrors.username}</FieldError>
|
||||
</Field>
|
||||
|
||||
<Field data-invalid={fieldErrors.bio ? true : undefined}>
|
||||
<FieldLabel htmlFor="bio">Bio</FieldLabel>
|
||||
<Textarea
|
||||
id="bio"
|
||||
name="bio"
|
||||
rows={3}
|
||||
defaultValue={profile.bio ?? ''}
|
||||
maxLength={BIO_MAX_LENGTH}
|
||||
aria-invalid={fieldErrors.bio ? true : undefined}
|
||||
/>
|
||||
<FieldDescription>
|
||||
Up to {BIO_MAX_LENGTH} characters.
|
||||
</FieldDescription>
|
||||
<FieldError>{fieldErrors.bio}</FieldError>
|
||||
</Field>
|
||||
|
||||
<Field>
|
||||
<FieldLabel htmlFor="email">Email</FieldLabel>
|
||||
<Input id="email" type="email" value={profile.email} disabled />
|
||||
<FieldDescription>
|
||||
Used to log in. Only you can see it.
|
||||
</FieldDescription>
|
||||
</Field>
|
||||
|
||||
{formError && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{formError}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<Field orientation="horizontal">
|
||||
<Button type="submit" disabled={updateProfile.isPending}>
|
||||
{updateProfile.isPending && <Spinner />}
|
||||
Save changes
|
||||
</Button>
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
</form>
|
||||
|
||||
<Separator />
|
||||
<NotificationSettings />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+126
-12
@@ -1,19 +1,133 @@
|
||||
import { createFileRoute } from '@tanstack/react-router';
|
||||
import { Button } from '@repo/ui/components/button';
|
||||
import { useState } from 'react';
|
||||
import { Link, createFileRoute } from '@tanstack/react-router';
|
||||
import { Castle, MessagesSquare, UserPlus, Video } from 'lucide-react';
|
||||
import { Button, buttonVariants } from '@repo/ui/components/button';
|
||||
import { Spinner } from '@repo/ui/components/spinner';
|
||||
import { Brand } from '@/components/brand';
|
||||
import { authClient } from '@/lib/auth-client';
|
||||
|
||||
export const Route = createFileRoute('/')({ component: App });
|
||||
export const Route = createFileRoute('/')({ component: Welcome });
|
||||
|
||||
const features = [
|
||||
{
|
||||
icon: UserPlus,
|
||||
title: 'Friends',
|
||||
text: 'Add people you know and message them directly.',
|
||||
},
|
||||
{
|
||||
icon: MessagesSquare,
|
||||
title: 'Group chats',
|
||||
text: 'Pull a few friends into one conversation.',
|
||||
},
|
||||
{
|
||||
icon: Castle,
|
||||
title: 'Realms & cauldrons',
|
||||
text: 'Build a community with its own rooms for every topic.',
|
||||
},
|
||||
{
|
||||
icon: Video,
|
||||
title: 'Voice & video',
|
||||
text: 'Jump from typing to talking with one click.',
|
||||
},
|
||||
];
|
||||
|
||||
function Welcome() {
|
||||
const { data: session, isPending } = authClient.useSession();
|
||||
const [isSigningOut, setIsSigningOut] = useState(false);
|
||||
|
||||
async function handleSignOut() {
|
||||
setIsSigningOut(true);
|
||||
await authClient.signOut();
|
||||
setIsSigningOut(false);
|
||||
}
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<div className="flex min-h-svh p-6">
|
||||
<div className="flex max-w-md min-w-0 flex-col gap-4 text-sm leading-loose">
|
||||
<div>
|
||||
<h1 className="font-medium">Project ready!</h1>
|
||||
<p>You may now add components and start building.</p>
|
||||
<p>We've already added the button component for you.</p>
|
||||
<Button className="mt-2">Button</Button>
|
||||
<div className="flex min-h-svh flex-col">
|
||||
<header className="flex items-center justify-between px-6 py-4">
|
||||
<Brand />
|
||||
{/* Hidden until the session is known, so the buttons don't flicker. */}
|
||||
<nav
|
||||
className={`flex items-center gap-2 ${isPending ? 'invisible' : ''}`}
|
||||
>
|
||||
{session ? (
|
||||
<>
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={handleSignOut}
|
||||
disabled={isSigningOut}
|
||||
>
|
||||
{isSigningOut && <Spinner />}
|
||||
Sign out
|
||||
</Button>
|
||||
<Link to="/app" className={buttonVariants()}>
|
||||
Open app
|
||||
</Link>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Link
|
||||
to="/login"
|
||||
className={buttonVariants({ variant: 'ghost' })}
|
||||
>
|
||||
Log in
|
||||
</Link>
|
||||
<Link to="/register" className={buttonVariants()}>
|
||||
Register
|
||||
</Link>
|
||||
</>
|
||||
)}
|
||||
</nav>
|
||||
</header>
|
||||
|
||||
<main className="flex flex-1 flex-col items-center justify-center gap-10 px-6 pb-10 text-center">
|
||||
<div className="flex max-w-2xl flex-col items-center gap-4">
|
||||
<h1 className="font-heading text-4xl font-semibold tracking-tight text-balance sm:text-6xl">
|
||||
{session
|
||||
? `Welcome back, ${session.user.name}`
|
||||
: 'Your people, your realms, one place to talk'}
|
||||
</h1>
|
||||
<p className="max-w-xl text-base text-balance text-muted-foreground sm:text-lg">
|
||||
Message friends, start group chats, gather communities in realms,
|
||||
and switch to a voice or video call whenever typing isn't
|
||||
enough.
|
||||
</p>
|
||||
<div className={`mt-2 flex gap-3 ${isPending ? 'invisible' : ''}`}>
|
||||
{session ? (
|
||||
<Link to="/app" className={buttonVariants({ size: 'lg' })}>
|
||||
Open the app
|
||||
</Link>
|
||||
) : (
|
||||
<>
|
||||
<Link to="/register" className={buttonVariants({ size: 'lg' })}>
|
||||
Create an account
|
||||
</Link>
|
||||
<Link
|
||||
to="/login"
|
||||
className={buttonVariants({ variant: 'outline', size: 'lg' })}
|
||||
>
|
||||
Log in
|
||||
</Link>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ul className="grid w-full max-w-4xl grid-cols-2 gap-3 text-left lg:grid-cols-4">
|
||||
{features.map((feature) => (
|
||||
<li
|
||||
key={feature.title}
|
||||
className="flex flex-col gap-1.5 rounded-xl bg-card p-4 ring-1 ring-foreground/10"
|
||||
>
|
||||
<feature.icon
|
||||
className="size-5 text-primary"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<h2 className="text-sm font-medium">{feature.title}</h2>
|
||||
<p className="text-sm text-muted-foreground">{feature.text}</p>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import { createFileRoute } from '@tanstack/react-router';
|
||||
import { AuthForm } from '@/components/auth-form';
|
||||
import { validateAuthSearch } from '@/lib/redirect';
|
||||
|
||||
export const Route = createFileRoute('/login')({
|
||||
validateSearch: validateAuthSearch,
|
||||
component: Login,
|
||||
});
|
||||
|
||||
function Login() {
|
||||
const { redirect } = Route.useSearch();
|
||||
return <AuthForm mode="login" redirectTo={redirect} />;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { createFileRoute } from '@tanstack/react-router';
|
||||
import { AuthForm } from '@/components/auth-form';
|
||||
import { validateAuthSearch } from '@/lib/redirect';
|
||||
|
||||
export const Route = createFileRoute('/register')({
|
||||
validateSearch: validateAuthSearch,
|
||||
component: Register,
|
||||
});
|
||||
|
||||
function Register() {
|
||||
const { redirect } = Route.useSearch();
|
||||
return <AuthForm mode="register" redirectTo={redirect} />;
|
||||
}
|
||||
Reference in New Issue
Block a user