Lobby Membership

This commit is contained in:
Vico 2025-03-25 22:38:40 +01:00
parent 53c3e39b6a
commit e2d5447a3c
11 changed files with 471 additions and 9 deletions

View File

@ -23,6 +23,7 @@
"@auth/drizzle-adapter": "^1.7.2",
"@hookform/resolvers": "^4.1.3",
"@paralleldrive/cuid2": "^2.2.2",
"@radix-ui/react-alert-dialog": "^1.1.6",
"@radix-ui/react-avatar": "^1.1.3",
"@radix-ui/react-dialog": "^1.1.6",
"@radix-ui/react-label": "^2.1.2",

30
pnpm-lock.yaml generated
View File

@ -17,6 +17,9 @@ importers:
'@paralleldrive/cuid2':
specifier: ^2.2.2
version: 2.2.2
'@radix-ui/react-alert-dialog':
specifier: ^1.1.6
version: 1.1.6(@types/react-dom@19.0.4(@types/react@19.0.12))(@types/react@19.0.12)(react-dom@19.0.0(react@19.0.0))(react@19.0.0)
'@radix-ui/react-avatar':
specifier: ^1.1.3
version: 1.1.3(@types/react-dom@19.0.4(@types/react@19.0.12))(@types/react@19.0.12)(react-dom@19.0.0(react@19.0.0))(react@19.0.0)
@ -729,6 +732,19 @@ packages:
'@radix-ui/primitive@1.1.1':
resolution: {integrity: sha512-SJ31y+Q/zAyShtXJc8x83i9TYdbAfHZ++tUZnvjJJqFjzsdUnKsxPL6IEtBlxKkU7yzer//GQtZSV4GbldL3YA==}
'@radix-ui/react-alert-dialog@1.1.6':
resolution: {integrity: sha512-p4XnPqgej8sZAAReCAKgz1REYZEBLR8hU9Pg27wFnCWIMc8g1ccCs0FjBcy05V15VTu8pAePw/VDYeOm/uZ6yQ==}
peerDependencies:
'@types/react': '*'
'@types/react-dom': '*'
react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
peerDependenciesMeta:
'@types/react':
optional: true
'@types/react-dom':
optional: true
'@radix-ui/react-avatar@1.1.3':
resolution: {integrity: sha512-Paen00T4P8L8gd9bNsRMw7Cbaz85oxiv+hzomsRZgFm2byltPFDtfcoqlWJ8GyZlIBWgLssJlzLCnKU0G0302g==}
peerDependencies:
@ -3160,6 +3176,20 @@ snapshots:
'@radix-ui/primitive@1.1.1': {}
'@radix-ui/react-alert-dialog@1.1.6(@types/react-dom@19.0.4(@types/react@19.0.12))(@types/react@19.0.12)(react-dom@19.0.0(react@19.0.0))(react@19.0.0)':
dependencies:
'@radix-ui/primitive': 1.1.1
'@radix-ui/react-compose-refs': 1.1.1(@types/react@19.0.12)(react@19.0.0)
'@radix-ui/react-context': 1.1.1(@types/react@19.0.12)(react@19.0.0)
'@radix-ui/react-dialog': 1.1.6(@types/react-dom@19.0.4(@types/react@19.0.12))(@types/react@19.0.12)(react-dom@19.0.0(react@19.0.0))(react@19.0.0)
'@radix-ui/react-primitive': 2.0.2(@types/react-dom@19.0.4(@types/react@19.0.12))(@types/react@19.0.12)(react-dom@19.0.0(react@19.0.0))(react@19.0.0)
'@radix-ui/react-slot': 1.1.2(@types/react@19.0.12)(react@19.0.0)
react: 19.0.0
react-dom: 19.0.0(react@19.0.0)
optionalDependencies:
'@types/react': 19.0.12
'@types/react-dom': 19.0.4(@types/react@19.0.12)
'@radix-ui/react-avatar@1.1.3(@types/react-dom@19.0.4(@types/react@19.0.12))(@types/react@19.0.12)(react-dom@19.0.0(react@19.0.0))(react@19.0.0)':
dependencies:
'@radix-ui/react-context': 1.1.1(@types/react@19.0.12)(react@19.0.0)

View File

@ -4,6 +4,11 @@ import { notFound } from "next/navigation";
import React from "react";
import UserCard from "@/components/user-card";
import type { PublicUser } from "@/server/auth/config";
import { Button } from "@/components/ui/button";
import { auth } from "@/server/auth";
import DeleteLobbyDialog from "@/app/_components/delete-lobby-dialog";
import LobbyMembershipDialog from "@/app/_components/lobby-membership-dialog";
async function Page({
params,
}: {
@ -11,7 +16,7 @@ async function Page({
id: string;
}>;
}) {
const session = { user: {} as User }; //await auth();
const session = await auth();
const { id } = await params;
const lobby = await api.lobby.get({ id });
if (!lobby) return notFound();
@ -20,18 +25,26 @@ async function Page({
{ ...lobby.leader, leader: true },
...(lobby?.members?.map(({ user }) => ({ ...user, leader: false })) ?? []),
];
const isJoined = members.find((member) => member.id === session?.user.id);
const isOwner = lobby.createdById === session?.user.id;
return (
<div>
<h1 className="text-2xl font-bold capitalize">{lobby.name}</h1>
<ul>
{members?.map((member) => (
<li>
{members?.map((member, idx) => (
<li key={idx}>
<UserCard name={member.name!} image={member.image!}>
{member?.leader && <label>Leader</label>}
</UserCard>
</li>
))}
</ul>
{isOwner && <DeleteLobbyDialog lobbyId={lobby.id} />}
{!isOwner && (
<LobbyMembershipDialog lobbyId={lobby.id} join={!isJoined} />
)}
</div>
);
}

View File

@ -1,7 +1,21 @@
import React from "react";
import { api } from "@/trpc/server";
import Link from "next/link";
function Page() {
return <div>All lobbies</div>;
async function Page() {
const lobbies = await api.lobby.getAll();
return (
<div>
<menu>
{lobbies.map((lobby) => (
<li key={lobby.id}>
<Link href={`/lobby/${lobby.id}`}>{lobby.name}</Link>
</li>
))}
</menu>
</div>
);
}
export default Page;

View File

@ -3,10 +3,9 @@ import { Button } from "@/components/ui/button";
import { Sparkles, Users, Plus } from "lucide-react";
import CreateLobbyDialog from "../_components/create-lobby-dialog";
import { auth } from "@/server/auth";
import type { User } from "next-auth";
export default async function QuizGameStartPage() {
const session = { user: {} as User }; //await auth();
const session = await auth();
return (
<div className="relative z-10 w-full max-w-md px-4">
<div className="mb-8 text-center">

View File

@ -0,0 +1,57 @@
"use client";
import React from "react";
import { Button } from "@/components/ui/button";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { api } from "@/trpc/react";
import { toast } from "sonner";
import { useRouter } from "next/navigation";
function DeleteLobbyDialog({ lobbyId }: { lobbyId: string }) {
const [loading, setLoading] = React.useState(false);
const { mutateAsync } = api.lobby.delete.useMutation();
const router = useRouter();
const handleConfirm = async () => {
setLoading(true);
const result = await mutateAsync({ lobbyId });
if (result) {
router.push("/");
} else toast.error("Something went wrong");
setLoading(false);
};
return (
<AlertDialog>
<Button asChild variant={"destructive"}>
<AlertDialogTrigger>Remove Lobby</AlertDialogTrigger>
</Button>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
<AlertDialogDescription>
This action cannot be undone. You will permanently delete this
lobby!
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={handleConfirm} disabled={loading}>
Delete Lobby
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
);
}
export default DeleteLobbyDialog;

View File

@ -0,0 +1,73 @@
"use client";
import React from "react";
import { Button } from "@/components/ui/button";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { api } from "@/trpc/react";
import { toast } from "sonner";
import { useRouter } from "next/navigation";
function LobbyMembershipDialog({
lobbyId,
join,
}: {
lobbyId: string;
join: boolean;
}) {
const [loading, setLoading] = React.useState(false);
const { mutateAsync } = api.lobby.membership.useMutation();
const router = useRouter();
const handleConfirm = async () => {
setLoading(true);
const result = await mutateAsync({ lobbyId, join });
if (result) {
if (!join) router.push("/");
else toast.success("Successfully joined the lobby.");
} else toast.error("Something went wrong");
setLoading(false);
};
const labelText = join ? "join" : "leave";
return (
<AlertDialog>
<Button asChild>
<AlertDialogTrigger className="capitalize">
{labelText} Lobby
</AlertDialogTrigger>
</Button>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle className="capitalize">
{labelText} Lobby
</AlertDialogTitle>
<AlertDialogDescription>
You are about to {labelText} the lobby.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={handleConfirm}
disabled={loading}
className="capitalize"
>
{labelText}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
);
}
export default LobbyMembershipDialog;

View File

@ -0,0 +1,157 @@
"use client"
import * as React from "react"
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog"
import { cn } from "@/lib/utils"
import { buttonVariants } from "@/components/ui/button"
function AlertDialog({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {
return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />
}
function AlertDialogTrigger({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {
return (
<AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />
)
}
function AlertDialogPortal({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
return (
<AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />
)
}
function AlertDialogOverlay({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {
return (
<AlertDialogPrimitive.Overlay
data-slot="alert-dialog-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className
)}
{...props}
/>
)
}
function AlertDialogContent({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Content>) {
return (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
data-slot="alert-dialog-content"
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
className
)}
{...props}
/>
</AlertDialogPortal>
)
}
function AlertDialogHeader({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-header"
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
{...props}
/>
)
}
function AlertDialogFooter({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className
)}
{...props}
/>
)
}
function AlertDialogTitle({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
return (
<AlertDialogPrimitive.Title
data-slot="alert-dialog-title"
className={cn("text-lg font-semibold", className)}
{...props}
/>
)
}
function AlertDialogDescription({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
return (
<AlertDialogPrimitive.Description
data-slot="alert-dialog-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
function AlertDialogAction({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Action>) {
return (
<AlertDialogPrimitive.Action
className={cn(buttonVariants(), className)}
{...props}
/>
)
}
function AlertDialogCancel({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Cancel>) {
return (
<AlertDialogPrimitive.Cancel
className={cn(buttonVariants({ variant: "outline" }), className)}
{...props}
/>
)
}
export {
AlertDialog,
AlertDialogPortal,
AlertDialogOverlay,
AlertDialogTrigger,
AlertDialogContent,
AlertDialogHeader,
AlertDialogFooter,
AlertDialogTitle,
AlertDialogDescription,
AlertDialogAction,
AlertDialogCancel,
}

View File

@ -0,0 +1,66 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const alertVariants = cva(
"relative w-full rounded-lg border px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",
{
variants: {
variant: {
default: "bg-card text-card-foreground",
destructive:
"text-destructive bg-card [&>svg]:text-current *:data-[slot=alert-description]:text-destructive/90",
},
},
defaultVariants: {
variant: "default",
},
}
)
function Alert({
className,
variant,
...props
}: React.ComponentProps<"div"> & VariantProps<typeof alertVariants>) {
return (
<div
data-slot="alert"
role="alert"
className={cn(alertVariants({ variant }), className)}
{...props}
/>
)
}
function AlertTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-title"
className={cn(
"col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",
className
)}
{...props}
/>
)
}
function AlertDescription({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-description"
className={cn(
"text-muted-foreground col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed",
className
)}
{...props}
/>
)
}
export { Alert, AlertTitle, AlertDescription }

View File

@ -1,6 +1,6 @@
import { z } from "zod";
import { lobbies } from "@/server/db/schema";
import { lobbies, lobbyMembers } from "@/server/db/schema";
import {
createTRPCRouter,
protectedProcedure,
@ -11,6 +11,23 @@ import { and, eq } from "drizzle-orm";
export const lobbyRouter = createTRPCRouter({
// queries
getAll: protectedProcedure.query(async ({ ctx }) => {
const ownedLobbies = await ctx.db.query.lobbies.findMany({
where: eq(lobbies.createdById, ctx.session.user.id),
});
const joinedLobbies = await ctx.db.query.lobbyMembers.findMany({
where: eq(lobbyMembers.userId, ctx.session.user.id),
with: {
lobby: true,
},
});
return [
...ownedLobbies,
...(joinedLobbies?.map(({ lobby }) => lobby) ?? []),
];
}),
get: publicProcedure
.input(
z.object({
@ -26,6 +43,7 @@ export const lobbyRouter = createTRPCRouter({
columns: {
image: true,
name: true,
id: true,
},
},
members: {
@ -34,6 +52,7 @@ export const lobbyRouter = createTRPCRouter({
columns: {
image: true,
name: true,
id: true,
},
},
},
@ -97,4 +116,37 @@ export const lobbyRouter = createTRPCRouter({
.returning({ id: lobbies.id });
return lobby;
}),
membership: protectedProcedure
.input(
z.object({
lobbyId: z.string(),
join: z.boolean(),
}),
)
.mutation(async ({ ctx, input }) => {
if (input.join) {
return (
await ctx.db
.insert(lobbyMembers)
.values({
lobbyId: input.lobbyId,
userId: ctx.session.user.id,
})
.returning()
)[0];
} else {
return (
await ctx.db
.delete(lobbyMembers)
.where(
and(
eq(lobbyMembers.lobbyId, input.lobbyId),
eq(lobbyMembers.userId, ctx.session.user.id),
),
)
.returning()
)[0];
}
}),
});

View File

@ -30,7 +30,7 @@ declare module "next-auth" {
// // role: UserRole;
// }
}
export type PublicUser = Pick<User, "name" | "image">;
export type PublicUser = Pick<User, "name" | "image" | "id">;
/**
* Options for NextAuth.js used to configure adapters, providers, callbacks, etc.