mirror of
https://github.com/soconnor0919/hristudio.git
synced 2025-12-11 22:54:45 -05:00
feat: rewrite project
This commit is contained in:
118
src/app/_components/auth/sign-in-form.tsx
Normal file
118
src/app/_components/auth/sign-in-form.tsx
Normal file
@@ -0,0 +1,118 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { signIn } from "next-auth/react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "~/components/ui/form";
|
||||
import { Input } from "~/components/ui/input";
|
||||
import { useToast } from "~/components/ui/use-toast";
|
||||
|
||||
const formSchema = z.object({
|
||||
email: z.string().email(),
|
||||
password: z.string().min(8),
|
||||
});
|
||||
|
||||
type FormValues = z.infer<typeof formSchema>;
|
||||
|
||||
export function SignInForm() {
|
||||
const router = useRouter();
|
||||
const { toast } = useToast();
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
const form = useForm<FormValues>({
|
||||
resolver: zodResolver(formSchema),
|
||||
defaultValues: {
|
||||
email: "",
|
||||
password: "",
|
||||
},
|
||||
});
|
||||
|
||||
async function onSubmit(data: FormValues) {
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
const result = await signIn("credentials", {
|
||||
redirect: false,
|
||||
email: data.email,
|
||||
password: data.password,
|
||||
});
|
||||
|
||||
if (result?.error) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
description: "Invalid email or password",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
router.refresh();
|
||||
router.push("/");
|
||||
} catch (error) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
description: "Something went wrong. Please try again.",
|
||||
});
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="email"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Email</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="email"
|
||||
placeholder="name@example.com"
|
||||
{...field}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="password"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Password</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="password"
|
||||
placeholder="Enter your password"
|
||||
{...field}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<Button type="submit" className="w-full" disabled={isLoading}>
|
||||
{isLoading ? "Signing in..." : "Sign in"}
|
||||
</Button>
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
149
src/app/_components/auth/sign-up-form.tsx
Normal file
149
src/app/_components/auth/sign-up-form.tsx
Normal file
@@ -0,0 +1,149 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { signIn } from "next-auth/react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "~/components/ui/form";
|
||||
import { Input } from "~/components/ui/input";
|
||||
import { useToast } from "~/components/ui/use-toast";
|
||||
import { api } from "~/trpc/react";
|
||||
|
||||
const formSchema = z.object({
|
||||
email: z.string().email(),
|
||||
password: z.string().min(8),
|
||||
name: z.string().min(1).max(256).optional(),
|
||||
});
|
||||
|
||||
type FormValues = z.infer<typeof formSchema>;
|
||||
|
||||
export function SignUpForm() {
|
||||
const router = useRouter();
|
||||
const { toast } = useToast();
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const createUser = api.user.create.useMutation();
|
||||
|
||||
const form = useForm<FormValues>({
|
||||
resolver: zodResolver(formSchema),
|
||||
defaultValues: {
|
||||
email: "",
|
||||
password: "",
|
||||
name: "",
|
||||
},
|
||||
});
|
||||
|
||||
async function onSubmit(data: FormValues) {
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
await createUser.mutateAsync(data);
|
||||
|
||||
const result = await signIn("credentials", {
|
||||
redirect: false,
|
||||
email: data.email,
|
||||
password: data.password,
|
||||
});
|
||||
|
||||
if (result?.error) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
description: "Something went wrong. Please try again.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
router.refresh();
|
||||
router.push("/");
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
description: error.message,
|
||||
});
|
||||
} else {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
description: "Something went wrong. Please try again.",
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="email"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Email</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="email"
|
||||
placeholder="name@example.com"
|
||||
{...field}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="password"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Password</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="password"
|
||||
placeholder="Enter your password"
|
||||
{...field}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="name"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Name</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
placeholder="John Doe"
|
||||
{...field}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<Button type="submit" className="w-full" disabled={isLoading}>
|
||||
{isLoading ? "Creating account..." : "Create account"}
|
||||
</Button>
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
6
src/app/api/auth/[...nextauth]/route.ts
Normal file
6
src/app/api/auth/[...nextauth]/route.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
import NextAuth from "next-auth";
|
||||
import { authOptions } from "~/server/auth";
|
||||
|
||||
const handler = NextAuth(authOptions);
|
||||
|
||||
export { handler as GET, handler as POST };
|
||||
62
src/app/api/auth/register/route.ts
Normal file
62
src/app/api/auth/register/route.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
import { hash } from "bcryptjs";
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { db } from "~/server/db";
|
||||
import { users } from "~/server/db/schema";
|
||||
|
||||
const registerSchema = z.object({
|
||||
firstName: z.string().min(1, "First name is required"),
|
||||
lastName: z.string().min(1, "Last name is required"),
|
||||
email: z.string().email(),
|
||||
password: z.string().min(8),
|
||||
});
|
||||
|
||||
export async function POST(req: Request) {
|
||||
try {
|
||||
const form = await req.formData();
|
||||
const data = {
|
||||
firstName: form.get("firstName"),
|
||||
lastName: form.get("lastName"),
|
||||
email: form.get("email"),
|
||||
password: form.get("password"),
|
||||
};
|
||||
|
||||
const parsed = registerSchema.safeParse(data);
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: "Invalid input" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const { firstName, lastName, email, password } = parsed.data;
|
||||
|
||||
const exists = await db.query.users.findFirst({
|
||||
where: (users, { eq }) => eq(users.email, email),
|
||||
});
|
||||
|
||||
if (exists) {
|
||||
return NextResponse.json(
|
||||
{ error: "User already exists" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const hashedPassword = await hash(password, 10);
|
||||
|
||||
await db.insert(users).values({
|
||||
firstName,
|
||||
lastName,
|
||||
email,
|
||||
password: hashedPassword,
|
||||
});
|
||||
|
||||
return NextResponse.redirect(new URL("/login", req.url));
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
return NextResponse.json(
|
||||
{ error: "Something went wrong" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
71
src/app/api/images/[key]/route.ts
Normal file
71
src/app/api/images/[key]/route.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { getObjectFromS3 } from "~/server/storage/s3";
|
||||
import { Readable } from "stream";
|
||||
|
||||
export async function GET(
|
||||
req: Request,
|
||||
{ params }: { params: { key: string } }
|
||||
) {
|
||||
try {
|
||||
// Ensure params.key is awaited
|
||||
const { key } = params;
|
||||
const decodedKey = decodeURIComponent(key);
|
||||
console.log("Fetching image with key:", decodedKey);
|
||||
|
||||
const response = await getObjectFromS3(decodedKey);
|
||||
console.log("S3 response received:", {
|
||||
contentType: response.ContentType,
|
||||
contentLength: response.ContentLength,
|
||||
});
|
||||
|
||||
if (!response.Body) {
|
||||
console.error("No image data in response body");
|
||||
return NextResponse.json(
|
||||
{ error: "Image data not found" },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
const stream = response.Body as Readable;
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const chunk of stream) {
|
||||
chunks.push(Buffer.from(chunk));
|
||||
}
|
||||
const buffer = Buffer.concat(chunks);
|
||||
|
||||
console.log("Image buffer created, size:", buffer.length);
|
||||
|
||||
// Ensure we set the correct image content type
|
||||
const contentType = response.ContentType ?? 'image/jpeg';
|
||||
|
||||
// Create response headers
|
||||
const headers = {
|
||||
"Content-Type": contentType,
|
||||
"Content-Length": buffer.length.toString(),
|
||||
"Cache-Control": "public, max-age=31536000, immutable",
|
||||
"Access-Control-Allow-Origin": "*",
|
||||
"Access-Control-Allow-Methods": "GET, OPTIONS",
|
||||
"Access-Control-Allow-Headers": "Content-Type",
|
||||
};
|
||||
|
||||
console.log("Sending response with headers:", headers);
|
||||
|
||||
// Return the response with explicit headers object
|
||||
return new Response(buffer, {
|
||||
status: 200,
|
||||
headers,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error serving image:", error);
|
||||
if ((error as any)?.name === "NoSuchKey") {
|
||||
return NextResponse.json(
|
||||
{ error: "Image not found" },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
return NextResponse.json(
|
||||
{ error: "Internal server error" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
// @ts-nocheck
|
||||
/* eslint-disable */
|
||||
/* tslint:disable */
|
||||
|
||||
import { eq } from "drizzle-orm";
|
||||
import { NextRequest } from "next/server";
|
||||
import { db } from "~/db";
|
||||
import { invitationsTable } from "~/db/schema";
|
||||
import { PERMISSIONS, checkPermissions } from "~/lib/permissions-server";
|
||||
import { ApiError, createApiResponse } from "~/lib/api-utils";
|
||||
|
||||
export async function DELETE(req: NextRequest, { params }: { params: { id: string } }) {
|
||||
try {
|
||||
const { id } = params;
|
||||
const invitationId = parseInt(id, 10);
|
||||
|
||||
if (isNaN(invitationId)) {
|
||||
return ApiError.BadRequest("Invalid invitation ID");
|
||||
}
|
||||
|
||||
// Get the invitation to check the study ID
|
||||
const invitation = await db
|
||||
.select()
|
||||
.from(invitationsTable)
|
||||
.where(eq(invitationsTable.id, invitationId))
|
||||
.limit(1);
|
||||
|
||||
if (!invitation[0]) {
|
||||
return ApiError.NotFound("Invitation");
|
||||
}
|
||||
|
||||
const permissionCheck = await checkPermissions({
|
||||
studyId: invitation[0].studyId,
|
||||
permission: PERMISSIONS.MANAGE_ROLES
|
||||
});
|
||||
|
||||
if (permissionCheck.error) {
|
||||
return permissionCheck.error;
|
||||
}
|
||||
|
||||
await db
|
||||
.delete(invitationsTable)
|
||||
.where(eq(invitationsTable.id, invitationId));
|
||||
|
||||
return createApiResponse({ message: "Invitation deleted successfully" });
|
||||
} catch (error) {
|
||||
return ApiError.ServerError(error);
|
||||
}
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
import { eq, and } from "drizzle-orm";
|
||||
import { NextRequest } from "next/server";
|
||||
import { auth } from "@clerk/nextjs/server";
|
||||
import { db } from "~/db";
|
||||
import { invitationsTable, userRolesTable } from "~/db/schema";
|
||||
import { ApiError, createApiResponse } from "~/lib/api-utils";
|
||||
|
||||
export async function POST(req: NextRequest, { params }: { params: { token: string } }) {
|
||||
const { userId } = await auth();
|
||||
const { token } = params;
|
||||
|
||||
if (!userId) {
|
||||
return ApiError.Unauthorized();
|
||||
}
|
||||
|
||||
try {
|
||||
// Find the invitation
|
||||
const [invitation] = await db
|
||||
.select()
|
||||
.from(invitationsTable)
|
||||
.where(
|
||||
and(
|
||||
eq(invitationsTable.token, token),
|
||||
eq(invitationsTable.accepted, false)
|
||||
)
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
if (!invitation) {
|
||||
return ApiError.NotFound("Invitation");
|
||||
}
|
||||
|
||||
// Check if invitation has expired
|
||||
if (new Date() > invitation.expiresAt) {
|
||||
return ApiError.BadRequest("Invitation has expired");
|
||||
}
|
||||
|
||||
// Assign role and mark invitation as accepted in a transaction
|
||||
await db.transaction(async (tx) => {
|
||||
// Assign role
|
||||
await tx
|
||||
.insert(userRolesTable)
|
||||
.values({
|
||||
userId: userId,
|
||||
roleId: invitation.roleId,
|
||||
studyId: invitation.studyId,
|
||||
});
|
||||
|
||||
// Mark invitation as accepted
|
||||
await tx
|
||||
.update(invitationsTable)
|
||||
.set({
|
||||
accepted: true,
|
||||
acceptedByUserId: userId,
|
||||
})
|
||||
.where(eq(invitationsTable.id, invitation.id));
|
||||
});
|
||||
|
||||
return createApiResponse({ message: "Invitation accepted successfully" });
|
||||
} catch (error) {
|
||||
return ApiError.ServerError(error);
|
||||
}
|
||||
}
|
||||
@@ -1,122 +0,0 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth } from "@clerk/nextjs/server";
|
||||
import { db } from "~/db";
|
||||
import { invitationsTable, studyTable, rolesTable } from "~/db/schema";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { randomBytes } from "crypto";
|
||||
import { sendInvitationEmail } from "~/lib/email";
|
||||
import { PERMISSIONS, checkPermissions } from "~/lib/permissions-server";
|
||||
import { ApiError, createApiResponse } from "~/lib/api-utils";
|
||||
|
||||
// Helper to generate a secure random token
|
||||
function generateToken(): string {
|
||||
return randomBytes(32).toString('hex');
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
const url = new URL(request.url);
|
||||
const studyId = url.searchParams.get("studyId");
|
||||
|
||||
if (!studyId) {
|
||||
return ApiError.BadRequest("Study ID is required");
|
||||
}
|
||||
|
||||
const permissionCheck = await checkPermissions({
|
||||
studyId: parseInt(studyId),
|
||||
permission: PERMISSIONS.MANAGE_ROLES
|
||||
});
|
||||
|
||||
if (permissionCheck.error) {
|
||||
return permissionCheck.error;
|
||||
}
|
||||
|
||||
// Get all invitations for the study, including role names
|
||||
const invitations = await db
|
||||
.select({
|
||||
id: invitationsTable.id,
|
||||
email: invitationsTable.email,
|
||||
accepted: invitationsTable.accepted,
|
||||
expiresAt: invitationsTable.expiresAt,
|
||||
createdAt: invitationsTable.createdAt,
|
||||
roleName: rolesTable.name,
|
||||
})
|
||||
.from(invitationsTable)
|
||||
.innerJoin(rolesTable, eq(invitationsTable.roleId, rolesTable.id))
|
||||
.where(eq(invitationsTable.studyId, parseInt(studyId)));
|
||||
|
||||
return createApiResponse(invitations);
|
||||
} catch (error) {
|
||||
return ApiError.ServerError(error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const { email, studyId, roleId } = await request.json();
|
||||
|
||||
const permissionCheck = await checkPermissions({
|
||||
studyId,
|
||||
permission: PERMISSIONS.MANAGE_ROLES
|
||||
});
|
||||
|
||||
if (permissionCheck.error) {
|
||||
return permissionCheck.error;
|
||||
}
|
||||
|
||||
const { userId } = permissionCheck;
|
||||
|
||||
// Get study details
|
||||
const study = await db
|
||||
.select()
|
||||
.from(studyTable)
|
||||
.where(eq(studyTable.id, studyId))
|
||||
.limit(1);
|
||||
|
||||
if (!study[0]) {
|
||||
return ApiError.NotFound("Study");
|
||||
}
|
||||
|
||||
// Verify the role exists
|
||||
const role = await db
|
||||
.select()
|
||||
.from(rolesTable)
|
||||
.where(eq(rolesTable.id, roleId))
|
||||
.limit(1);
|
||||
|
||||
if (!role[0]) {
|
||||
return ApiError.BadRequest("Invalid role");
|
||||
}
|
||||
|
||||
// Generate invitation token
|
||||
const token = generateToken();
|
||||
const expiresAt = new Date();
|
||||
expiresAt.setDate(expiresAt.getDate() + 7); // 7 days expiration
|
||||
|
||||
// Create invitation
|
||||
const [invitation] = await db
|
||||
.insert(invitationsTable)
|
||||
.values({
|
||||
email,
|
||||
studyId,
|
||||
roleId,
|
||||
token,
|
||||
invitedById: userId,
|
||||
expiresAt,
|
||||
})
|
||||
.returning();
|
||||
|
||||
// Send invitation email
|
||||
await sendInvitationEmail({
|
||||
to: email,
|
||||
inviterName: "A researcher", // TODO: Get inviter name
|
||||
studyTitle: study[0].title,
|
||||
role: role[0].name,
|
||||
token,
|
||||
});
|
||||
|
||||
return createApiResponse(invitation);
|
||||
} catch (error) {
|
||||
return ApiError.ServerError(error);
|
||||
}
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
import { eq } from "drizzle-orm";
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth } from "@clerk/nextjs/server";
|
||||
import { db } from "~/db";
|
||||
import { participantsTable } from "~/db/schema";
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const { userId } = await auth();
|
||||
|
||||
if (!userId) {
|
||||
return new NextResponse("Unauthorized", { status: 401 });
|
||||
}
|
||||
|
||||
const url = new URL(request.url);
|
||||
const studyId = url.searchParams.get("studyId");
|
||||
|
||||
if (!studyId) {
|
||||
return new NextResponse("Study ID is required", { status: 400 });
|
||||
}
|
||||
|
||||
const participantList = await db
|
||||
.select()
|
||||
.from(participantsTable)
|
||||
.where(eq(participantsTable.studyId, parseInt(studyId)));
|
||||
|
||||
return NextResponse.json(participantList);
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const { userId } = await auth();
|
||||
|
||||
if (!userId) {
|
||||
return new NextResponse("Unauthorized", { status: 401 });
|
||||
}
|
||||
|
||||
const { name, studyId } = await request.json();
|
||||
|
||||
try {
|
||||
const participant = await db
|
||||
.insert(participantsTable)
|
||||
.values({
|
||||
name,
|
||||
studyId,
|
||||
})
|
||||
.returning();
|
||||
|
||||
return NextResponse.json(participant[0]);
|
||||
} catch (error) {
|
||||
console.error("Error adding participant:", error);
|
||||
return new NextResponse("Internal Server Error", { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth } from "@clerk/nextjs/server";
|
||||
import { ApiError, createApiResponse } from "~/lib/api-utils";
|
||||
import { db } from "~/db";
|
||||
import { userRolesTable, rolePermissionsTable, permissionsTable } from "~/db/schema";
|
||||
import { eq, and } from "drizzle-orm";
|
||||
|
||||
export async function GET() {
|
||||
const { userId } = await auth();
|
||||
|
||||
if (!userId) {
|
||||
return ApiError.Unauthorized();
|
||||
}
|
||||
|
||||
try {
|
||||
const permissions = await db
|
||||
.selectDistinct({
|
||||
code: permissionsTable.code,
|
||||
})
|
||||
.from(userRolesTable)
|
||||
.innerJoin(rolePermissionsTable, eq(rolePermissionsTable.roleId, userRolesTable.roleId))
|
||||
.innerJoin(permissionsTable, eq(permissionsTable.id, rolePermissionsTable.permissionId))
|
||||
.where(eq(userRolesTable.userId, userId));
|
||||
|
||||
return createApiResponse(permissions.map(p => p.code));
|
||||
} catch (error) {
|
||||
return ApiError.ServerError(error);
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth } from "@clerk/nextjs/server";
|
||||
import { db } from "~/db";
|
||||
import { rolesTable } from "~/db/schema";
|
||||
|
||||
export async function GET() {
|
||||
const { userId } = await auth();
|
||||
|
||||
if (!userId) {
|
||||
return new NextResponse("Unauthorized", { status: 401 });
|
||||
}
|
||||
|
||||
try {
|
||||
const roles = await db
|
||||
.select({
|
||||
id: rolesTable.id,
|
||||
name: rolesTable.name,
|
||||
description: rolesTable.description,
|
||||
})
|
||||
.from(rolesTable);
|
||||
|
||||
return NextResponse.json(roles);
|
||||
} catch (error) {
|
||||
console.error("Error fetching roles:", error);
|
||||
return new NextResponse("Internal Server Error", { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,136 +0,0 @@
|
||||
import { eq } from "drizzle-orm";
|
||||
import { db } from "~/db";
|
||||
import { participantsTable } from "~/db/schema";
|
||||
import { PERMISSIONS, checkPermissions } from "~/lib/permissions-server";
|
||||
import { ApiError, createApiResponse } from "~/lib/api-utils";
|
||||
import { auth } from "@clerk/nextjs/server";
|
||||
|
||||
export async function GET(
|
||||
request: Request,
|
||||
context: { params: { id: string } }
|
||||
) {
|
||||
const { userId } = await auth();
|
||||
const { id } = await Promise.resolve(context.params);
|
||||
|
||||
if (!userId) {
|
||||
return ApiError.Unauthorized();
|
||||
}
|
||||
|
||||
try {
|
||||
const studyId = parseInt(id);
|
||||
|
||||
if (isNaN(studyId)) {
|
||||
return ApiError.BadRequest("Invalid study ID");
|
||||
}
|
||||
|
||||
const permissionCheck = await checkPermissions({
|
||||
studyId,
|
||||
permission: PERMISSIONS.VIEW_PARTICIPANT_NAMES,
|
||||
});
|
||||
|
||||
const participants = await db
|
||||
.select()
|
||||
.from(participantsTable)
|
||||
.where(eq(participantsTable.studyId, studyId));
|
||||
|
||||
if (permissionCheck.error) {
|
||||
const anonymizedParticipants = participants.map((participant, index) => ({
|
||||
...participant,
|
||||
name: `Participant ${String.fromCharCode(65 + index)}`,
|
||||
}));
|
||||
return createApiResponse(anonymizedParticipants);
|
||||
}
|
||||
|
||||
return createApiResponse(participants);
|
||||
} catch (error) {
|
||||
return ApiError.ServerError(error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(
|
||||
request: Request,
|
||||
context: { params: { id: string } }
|
||||
) {
|
||||
const { userId } = await auth();
|
||||
const { id } = await Promise.resolve(context.params);
|
||||
|
||||
if (!userId) {
|
||||
return ApiError.Unauthorized();
|
||||
}
|
||||
|
||||
try {
|
||||
const studyId = parseInt(id);
|
||||
const { name } = await request.json();
|
||||
|
||||
if (isNaN(studyId)) {
|
||||
return ApiError.BadRequest("Invalid study ID");
|
||||
}
|
||||
|
||||
if (!name || typeof name !== "string") {
|
||||
return ApiError.BadRequest("Name is required");
|
||||
}
|
||||
|
||||
const permissionCheck = await checkPermissions({
|
||||
studyId,
|
||||
permission: PERMISSIONS.CREATE_PARTICIPANT,
|
||||
});
|
||||
|
||||
if (permissionCheck.error) {
|
||||
return permissionCheck.error;
|
||||
}
|
||||
|
||||
const participant = await db
|
||||
.insert(participantsTable)
|
||||
.values({
|
||||
name,
|
||||
studyId,
|
||||
})
|
||||
.returning();
|
||||
|
||||
return createApiResponse(participant[0]);
|
||||
} catch (error) {
|
||||
return ApiError.ServerError(error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(
|
||||
request: Request,
|
||||
context: { params: { id: string } }
|
||||
) {
|
||||
const { userId } = await auth();
|
||||
const { id } = await Promise.resolve(context.params);
|
||||
|
||||
if (!userId) {
|
||||
return ApiError.Unauthorized();
|
||||
}
|
||||
|
||||
try {
|
||||
const studyId = parseInt(id);
|
||||
const { participantId } = await request.json();
|
||||
|
||||
if (isNaN(studyId)) {
|
||||
return ApiError.BadRequest("Invalid study ID");
|
||||
}
|
||||
|
||||
if (!participantId || typeof participantId !== "number") {
|
||||
return ApiError.BadRequest("Participant ID is required");
|
||||
}
|
||||
|
||||
const permissionCheck = await checkPermissions({
|
||||
studyId,
|
||||
permission: PERMISSIONS.DELETE_PARTICIPANT,
|
||||
});
|
||||
|
||||
if (permissionCheck.error) {
|
||||
return permissionCheck.error;
|
||||
}
|
||||
|
||||
await db
|
||||
.delete(participantsTable)
|
||||
.where(eq(participantsTable.id, participantId));
|
||||
|
||||
return createApiResponse({ success: true });
|
||||
} catch (error) {
|
||||
return ApiError.ServerError(error);
|
||||
}
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
import { eq, and } from "drizzle-orm";
|
||||
import { db } from "~/db";
|
||||
import { studyTable, userRolesTable, rolePermissionsTable, permissionsTable } from "~/db/schema";
|
||||
import { PERMISSIONS, checkPermissions } from "~/lib/permissions-server";
|
||||
import { ApiError, createApiResponse } from "~/lib/api-utils";
|
||||
|
||||
export async function GET(request: Request, { params }: { params: { id: string } }) {
|
||||
try {
|
||||
const id = await Promise.resolve(params.id);
|
||||
const studyId = parseInt(id);
|
||||
|
||||
if (isNaN(studyId)) {
|
||||
return ApiError.BadRequest("Invalid study ID");
|
||||
}
|
||||
|
||||
const permissionCheck = await checkPermissions({
|
||||
studyId,
|
||||
permission: PERMISSIONS.VIEW_STUDY
|
||||
});
|
||||
|
||||
if (permissionCheck.error) {
|
||||
return permissionCheck.error;
|
||||
}
|
||||
|
||||
// Get study with permissions
|
||||
const studyWithPermissions = await db
|
||||
.selectDistinct({
|
||||
id: studyTable.id,
|
||||
title: studyTable.title,
|
||||
description: studyTable.description,
|
||||
createdAt: studyTable.createdAt,
|
||||
updatedAt: studyTable.updatedAt,
|
||||
userId: studyTable.userId,
|
||||
permissionCode: permissionsTable.code,
|
||||
})
|
||||
.from(studyTable)
|
||||
.leftJoin(userRolesTable, eq(userRolesTable.studyId, studyTable.id))
|
||||
.leftJoin(rolePermissionsTable, eq(rolePermissionsTable.roleId, userRolesTable.roleId))
|
||||
.leftJoin(permissionsTable, eq(permissionsTable.id, rolePermissionsTable.permissionId))
|
||||
.where(eq(studyTable.id, studyId));
|
||||
|
||||
if (!studyWithPermissions.length) {
|
||||
return ApiError.NotFound("Study");
|
||||
}
|
||||
|
||||
// Group permissions
|
||||
const study = {
|
||||
...studyWithPermissions[0],
|
||||
permissions: studyWithPermissions
|
||||
.map(s => s.permissionCode)
|
||||
.filter((code): code is string => code !== null)
|
||||
};
|
||||
|
||||
return createApiResponse(study);
|
||||
} catch (error) {
|
||||
return ApiError.ServerError(error);
|
||||
}
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
import { eq } from "drizzle-orm";
|
||||
import { sql } from "drizzle-orm";
|
||||
import { db } from "~/db";
|
||||
import { participantsTable } from "~/db/schema";
|
||||
import { PERMISSIONS, checkPermissions } from "~/lib/permissions-server";
|
||||
import { ApiError, createApiResponse } from "~/lib/api-utils";
|
||||
import { auth } from "@clerk/nextjs/server";
|
||||
|
||||
export async function GET(
|
||||
request: Request,
|
||||
context: { params: { id: string } }
|
||||
) {
|
||||
const { userId } = await auth();
|
||||
const { id } = await Promise.resolve(context.params);
|
||||
|
||||
if (!userId) {
|
||||
return ApiError.Unauthorized();
|
||||
}
|
||||
|
||||
try {
|
||||
const studyId = parseInt(id);
|
||||
|
||||
if (isNaN(studyId)) {
|
||||
return ApiError.BadRequest("Invalid study ID");
|
||||
}
|
||||
|
||||
const permissionCheck = await checkPermissions({
|
||||
studyId,
|
||||
permission: PERMISSIONS.VIEW_STUDY,
|
||||
});
|
||||
|
||||
if (permissionCheck.error) {
|
||||
return permissionCheck.error;
|
||||
}
|
||||
|
||||
// Get participant count using SQL count
|
||||
const [{ count }] = await db
|
||||
.select({
|
||||
count: sql<number>`count(*)::int`,
|
||||
})
|
||||
.from(participantsTable)
|
||||
.where(eq(participantsTable.studyId, studyId));
|
||||
|
||||
// TODO: Add actual trial and form counts when those tables are added
|
||||
const stats = {
|
||||
participantCount: count,
|
||||
completedTrialsCount: 0,
|
||||
pendingFormsCount: 0,
|
||||
};
|
||||
|
||||
return createApiResponse(stats);
|
||||
} catch (error) {
|
||||
return ApiError.ServerError(error);
|
||||
}
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
import { eq, and } from "drizzle-orm";
|
||||
import { db } from "~/db";
|
||||
import { userRolesTable } from "~/db/schema";
|
||||
import { PERMISSIONS, checkPermissions } from "~/lib/permissions-server";
|
||||
import { ApiError, createApiResponse } from "~/lib/api-utils";
|
||||
|
||||
export async function PUT(
|
||||
request: Request,
|
||||
context: { params: { id: string; userId: string } }
|
||||
) {
|
||||
try {
|
||||
const { id, userId } = await Promise.resolve(context.params);
|
||||
const studyId = parseInt(id);
|
||||
|
||||
if (isNaN(studyId)) {
|
||||
return ApiError.BadRequest("Invalid study ID");
|
||||
}
|
||||
|
||||
const permissionCheck = await checkPermissions({
|
||||
studyId,
|
||||
permission: PERMISSIONS.MANAGE_ROLES
|
||||
});
|
||||
|
||||
if (permissionCheck.error) {
|
||||
return permissionCheck.error;
|
||||
}
|
||||
|
||||
const { roleId } = await request.json();
|
||||
|
||||
if (!roleId || typeof roleId !== "number") {
|
||||
return ApiError.BadRequest("Role ID is required");
|
||||
}
|
||||
|
||||
// Update user's role in the study
|
||||
await db.transaction(async (tx) => {
|
||||
// Delete existing roles
|
||||
await tx
|
||||
.delete(userRolesTable)
|
||||
.where(
|
||||
and(
|
||||
eq(userRolesTable.userId, userId),
|
||||
eq(userRolesTable.studyId, studyId)
|
||||
)
|
||||
);
|
||||
|
||||
// Assign new role
|
||||
await tx
|
||||
.insert(userRolesTable)
|
||||
.values({
|
||||
userId,
|
||||
roleId,
|
||||
studyId,
|
||||
});
|
||||
});
|
||||
|
||||
return createApiResponse({ message: "Role updated successfully" });
|
||||
} catch (error) {
|
||||
return ApiError.ServerError(error);
|
||||
}
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
import { eq, and } from "drizzle-orm";
|
||||
import { db } from "~/db";
|
||||
import { userRolesTable, usersTable, rolesTable } from "~/db/schema";
|
||||
import { PERMISSIONS, checkPermissions } from "~/lib/permissions-server";
|
||||
import { ApiError, createApiResponse } from "~/lib/api-utils";
|
||||
|
||||
export async function GET(
|
||||
request: Request,
|
||||
context: { params: { id: string } }
|
||||
) {
|
||||
try {
|
||||
const { id } = await Promise.resolve(context.params);
|
||||
const studyId = parseInt(id);
|
||||
|
||||
if (isNaN(studyId)) {
|
||||
return ApiError.BadRequest("Invalid study ID");
|
||||
}
|
||||
|
||||
const permissionCheck = await checkPermissions({
|
||||
studyId,
|
||||
permission: PERMISSIONS.VIEW_STUDY
|
||||
});
|
||||
|
||||
if (permissionCheck.error) {
|
||||
return permissionCheck.error;
|
||||
}
|
||||
|
||||
// Get all users in the study with their roles
|
||||
const studyUsers = await db
|
||||
.select({
|
||||
id: usersTable.id,
|
||||
email: usersTable.email,
|
||||
name: usersTable.name,
|
||||
imageUrl: usersTable.imageUrl,
|
||||
roleId: rolesTable.id,
|
||||
roleName: rolesTable.name,
|
||||
})
|
||||
.from(userRolesTable)
|
||||
.innerJoin(usersTable, eq(usersTable.id, userRolesTable.userId))
|
||||
.innerJoin(rolesTable, eq(rolesTable.id, userRolesTable.roleId))
|
||||
.where(eq(userRolesTable.studyId, studyId));
|
||||
|
||||
// Group roles by user
|
||||
const users = studyUsers.reduce((acc, curr) => {
|
||||
const existingUser = acc.find(u => u.id === curr.id);
|
||||
if (!existingUser) {
|
||||
acc.push({
|
||||
id: curr.id,
|
||||
email: curr.email,
|
||||
name: curr.name,
|
||||
imageUrl: curr.imageUrl,
|
||||
roles: [{
|
||||
id: curr.roleId,
|
||||
name: curr.roleName,
|
||||
}]
|
||||
});
|
||||
} else if (curr.roleName && !existingUser.roles.some(r => r.id === curr.roleId)) {
|
||||
existingUser.roles.push({
|
||||
id: curr.roleId,
|
||||
name: curr.roleName,
|
||||
});
|
||||
}
|
||||
return acc;
|
||||
}, [] as Array<{
|
||||
id: string;
|
||||
email: string;
|
||||
name: string | null;
|
||||
imageUrl: string | null;
|
||||
roles: Array<{ id: number; name: string }>;
|
||||
}>);
|
||||
|
||||
return createApiResponse(users);
|
||||
} catch (error) {
|
||||
return ApiError.ServerError(error);
|
||||
}
|
||||
}
|
||||
@@ -1,146 +0,0 @@
|
||||
import { eq, and, or } from "drizzle-orm";
|
||||
import { db } from "~/db";
|
||||
import { studyTable, userRolesTable, rolePermissionsTable, permissionsTable, rolesTable } from "~/db/schema";
|
||||
import { PERMISSIONS, checkPermissions } from "~/lib/permissions-server";
|
||||
import { ApiError, createApiResponse, getEnvironment } from "~/lib/api-utils";
|
||||
import { auth } from "@clerk/nextjs/server";
|
||||
|
||||
export async function GET() {
|
||||
const { userId } = await auth();
|
||||
|
||||
if (!userId) {
|
||||
return ApiError.Unauthorized();
|
||||
}
|
||||
|
||||
try {
|
||||
const currentEnvironment = getEnvironment();
|
||||
|
||||
// Get all studies where user has any role
|
||||
const studiesWithPermissions = await db
|
||||
.selectDistinct({
|
||||
id: studyTable.id,
|
||||
title: studyTable.title,
|
||||
description: studyTable.description,
|
||||
createdAt: studyTable.createdAt,
|
||||
updatedAt: studyTable.updatedAt,
|
||||
userId: studyTable.userId,
|
||||
permissionCode: permissionsTable.code,
|
||||
roleName: rolesTable.name,
|
||||
})
|
||||
.from(studyTable)
|
||||
.innerJoin(
|
||||
userRolesTable,
|
||||
and(
|
||||
eq(userRolesTable.studyId, studyTable.id),
|
||||
eq(userRolesTable.userId, userId)
|
||||
)
|
||||
)
|
||||
.innerJoin(rolesTable, eq(rolesTable.id, userRolesTable.roleId))
|
||||
.leftJoin(rolePermissionsTable, eq(rolePermissionsTable.roleId, userRolesTable.roleId))
|
||||
.leftJoin(permissionsTable, eq(permissionsTable.id, rolePermissionsTable.permissionId))
|
||||
.where(eq(studyTable.environment, currentEnvironment));
|
||||
|
||||
// Group permissions and roles by study
|
||||
const studies = studiesWithPermissions.reduce((acc, curr) => {
|
||||
const existingStudy = acc.find(s => s.id === curr.id);
|
||||
if (!existingStudy) {
|
||||
acc.push({
|
||||
id: curr.id,
|
||||
title: curr.title,
|
||||
description: curr.description,
|
||||
createdAt: curr.createdAt,
|
||||
updatedAt: curr.updatedAt,
|
||||
userId: curr.userId,
|
||||
permissions: curr.permissionCode ? [curr.permissionCode] : [],
|
||||
roles: curr.roleName ? [curr.roleName] : []
|
||||
});
|
||||
} else {
|
||||
if (curr.permissionCode && !existingStudy.permissions.includes(curr.permissionCode)) {
|
||||
existingStudy.permissions.push(curr.permissionCode);
|
||||
}
|
||||
if (curr.roleName && !existingStudy.roles.includes(curr.roleName)) {
|
||||
existingStudy.roles.push(curr.roleName);
|
||||
}
|
||||
}
|
||||
return acc;
|
||||
}, [] as Array<{
|
||||
id: number;
|
||||
title: string;
|
||||
description: string | null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date | null;
|
||||
userId: string;
|
||||
permissions: string[];
|
||||
roles: string[];
|
||||
}>);
|
||||
|
||||
return createApiResponse(studies);
|
||||
} catch (error) {
|
||||
return ApiError.ServerError(error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const { userId } = await auth();
|
||||
|
||||
if (!userId) {
|
||||
return ApiError.Unauthorized();
|
||||
}
|
||||
|
||||
try {
|
||||
const { title, description } = await request.json();
|
||||
const currentEnvironment = getEnvironment();
|
||||
|
||||
// Create study and assign admin role in a transaction
|
||||
const result = await db.transaction(async (tx) => {
|
||||
// Create the study
|
||||
const [study] = await tx
|
||||
.insert(studyTable)
|
||||
.values({
|
||||
title,
|
||||
description,
|
||||
userId: userId,
|
||||
environment: currentEnvironment,
|
||||
})
|
||||
.returning();
|
||||
|
||||
// Look up the ADMIN role
|
||||
const [adminRole] = await tx
|
||||
.select()
|
||||
.from(rolesTable)
|
||||
.where(eq(rolesTable.name, 'admin'))
|
||||
.limit(1);
|
||||
|
||||
if (!adminRole) {
|
||||
throw new Error('Admin role not found');
|
||||
}
|
||||
|
||||
// Assign admin role
|
||||
await tx
|
||||
.insert(userRolesTable)
|
||||
.values({
|
||||
userId: userId,
|
||||
roleId: adminRole.id,
|
||||
studyId: study.id,
|
||||
});
|
||||
|
||||
// Get all permissions for this role
|
||||
const permissions = await tx
|
||||
.select({
|
||||
permissionCode: permissionsTable.code
|
||||
})
|
||||
.from(rolePermissionsTable)
|
||||
.innerJoin(permissionsTable, eq(permissionsTable.id, rolePermissionsTable.permissionId))
|
||||
.where(eq(rolePermissionsTable.roleId, adminRole.id));
|
||||
|
||||
return {
|
||||
...study,
|
||||
permissions: permissions.map(p => p.permissionCode)
|
||||
};
|
||||
});
|
||||
|
||||
return createApiResponse(result);
|
||||
} catch (error) {
|
||||
return ApiError.ServerError(error);
|
||||
}
|
||||
}
|
||||
34
src/app/api/trpc/[trpc]/route.ts
Normal file
34
src/app/api/trpc/[trpc]/route.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { fetchRequestHandler } from "@trpc/server/adapters/fetch";
|
||||
import { type NextRequest } from "next/server";
|
||||
|
||||
import { env } from "~/env";
|
||||
import { appRouter } from "~/server/api/root";
|
||||
import { createTRPCContext } from "~/server/api/trpc";
|
||||
|
||||
/**
|
||||
* This wraps the `createTRPCContext` helper and provides the required context for the tRPC API when
|
||||
* handling a HTTP request (e.g. when you make requests from Client Components).
|
||||
*/
|
||||
const createContext = async (req: NextRequest) => {
|
||||
return createTRPCContext({
|
||||
headers: req.headers,
|
||||
});
|
||||
};
|
||||
|
||||
const handler = (req: NextRequest) =>
|
||||
fetchRequestHandler({
|
||||
endpoint: "/api/trpc",
|
||||
req,
|
||||
router: appRouter,
|
||||
createContext: () => createContext(req),
|
||||
onError:
|
||||
env.NODE_ENV === "development"
|
||||
? ({ path, error }) => {
|
||||
console.error(
|
||||
`❌ tRPC failed on ${path ?? "<no-path>"}: ${error.message}`
|
||||
);
|
||||
}
|
||||
: undefined,
|
||||
});
|
||||
|
||||
export { handler as GET, handler as POST };
|
||||
42
src/app/api/upload/route.ts
Normal file
42
src/app/api/upload/route.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { getServerAuthSession } from "~/server/auth";
|
||||
import { uploadToS3 } from "~/server/storage/s3";
|
||||
import { nanoid } from "nanoid";
|
||||
|
||||
export async function POST(req: Request) {
|
||||
try {
|
||||
const session = await getServerAuthSession();
|
||||
if (!session) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
// Get the form data
|
||||
const formData = await req.formData();
|
||||
const file = formData.get("file") as File;
|
||||
|
||||
if (!file) {
|
||||
return NextResponse.json(
|
||||
{ error: "No file provided" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Generate a unique key for the file
|
||||
const key = `${session.user.id}/${nanoid()}.${file.type.split("/")[1]}`;
|
||||
|
||||
// Convert file to buffer and upload
|
||||
const arrayBuffer = await file.arrayBuffer();
|
||||
const buffer = Buffer.from(arrayBuffer);
|
||||
const url = await uploadToS3(buffer, key, file.type);
|
||||
|
||||
console.log("File uploaded successfully:", key);
|
||||
|
||||
return NextResponse.json({ url });
|
||||
} catch (error) {
|
||||
console.error("Error handling upload:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Internal server error" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
import { Webhook } from 'svix';
|
||||
import { headers } from 'next/headers';
|
||||
import { WebhookEvent } from '@clerk/nextjs/server';
|
||||
import { db } from '~/db';
|
||||
import { usersTable } from '~/db/schema';
|
||||
import { eq } from 'drizzle-orm';
|
||||
|
||||
export async function POST(req: Request) {
|
||||
// Get the headers
|
||||
const headerPayload = headers();
|
||||
const svix_id = headerPayload.get("svix-id");
|
||||
const svix_timestamp = headerPayload.get("svix-timestamp");
|
||||
const svix_signature = headerPayload.get("svix-signature");
|
||||
|
||||
// If there are no headers, error out
|
||||
if (!svix_id || !svix_timestamp || !svix_signature) {
|
||||
return new Response('Error occured -- no svix headers', {
|
||||
status: 400
|
||||
});
|
||||
}
|
||||
|
||||
// Get the body
|
||||
const payload = await req.json();
|
||||
const body = JSON.stringify(payload);
|
||||
|
||||
// Create a new Svix instance with your webhook secret
|
||||
const wh = new Webhook(process.env.CLERK_WEBHOOK_SECRET || '');
|
||||
|
||||
let evt: WebhookEvent;
|
||||
|
||||
// Verify the payload with the headers
|
||||
try {
|
||||
evt = wh.verify(body, {
|
||||
"svix-id": svix_id,
|
||||
"svix-timestamp": svix_timestamp,
|
||||
"svix-signature": svix_signature,
|
||||
}) as WebhookEvent;
|
||||
} catch (err) {
|
||||
console.error('Error verifying webhook:', err);
|
||||
return new Response('Error occured', {
|
||||
status: 400
|
||||
});
|
||||
}
|
||||
|
||||
// Handle the webhook
|
||||
const eventType = evt.type;
|
||||
console.log(`Webhook received: ${eventType}`);
|
||||
|
||||
if (eventType === 'user.created' || eventType === 'user.updated') {
|
||||
const { id, email_addresses, first_name, last_name, image_url } = evt.data;
|
||||
const primaryEmail = email_addresses?.[0]?.email_address;
|
||||
|
||||
// Create or update user in our database
|
||||
await db.insert(usersTable).values({
|
||||
id,
|
||||
email: primaryEmail,
|
||||
name: [first_name, last_name].filter(Boolean).join(' ') || null,
|
||||
imageUrl: image_url,
|
||||
}).onConflictDoUpdate({
|
||||
target: usersTable.id,
|
||||
set: {
|
||||
email: primaryEmail,
|
||||
name: [first_name, last_name].filter(Boolean).join(' ') || null,
|
||||
imageUrl: image_url,
|
||||
updatedAt: new Date(),
|
||||
}
|
||||
});
|
||||
|
||||
console.log(`${eventType === 'user.created' ? 'Created' : 'Updated'} user in database: ${id}`);
|
||||
}
|
||||
|
||||
return new Response('', { status: 200 });
|
||||
}
|
||||
68
src/app/auth/signin/page.tsx
Normal file
68
src/app/auth/signin/page.tsx
Normal file
@@ -0,0 +1,68 @@
|
||||
import { type Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { SignInForm } from "~/app/_components/auth/sign-in-form";
|
||||
import { buttonVariants } from "~/components/ui/button";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Sign In",
|
||||
description: "Sign in to your account",
|
||||
};
|
||||
|
||||
export default function SignInPage() {
|
||||
return (
|
||||
<div className="container relative h-screen flex-col items-center justify-center grid lg:max-w-none lg:grid-cols-2 lg:px-0">
|
||||
<div className="relative hidden h-full flex-col bg-muted p-10 text-white lg:flex dark:border-r">
|
||||
<div className="absolute inset-0 bg-zinc-900" />
|
||||
<div className="relative z-20 flex items-center text-lg font-medium">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
className="mr-2 h-6 w-6"
|
||||
>
|
||||
<path d="M15 6v12a3 3 0 1 0 3-3H6a3 3 0 1 0 3 3V6a3 3 0 1 0-3 3h12a3 3 0 1 0-3-3" />
|
||||
</svg>
|
||||
HRI Studio
|
||||
</div>
|
||||
<div className="relative z-20 mt-auto">
|
||||
<blockquote className="space-y-2">
|
||||
<p className="text-lg">
|
||||
“HRI Studio has revolutionized how we conduct human-robot interaction studies.”
|
||||
</p>
|
||||
<footer className="text-sm">Sofia Dewar</footer>
|
||||
</blockquote>
|
||||
</div>
|
||||
</div>
|
||||
<div className="lg:p-8">
|
||||
<div className="mx-auto flex w-full flex-col justify-center space-y-6 sm:w-[350px]">
|
||||
<div className="flex flex-col space-y-2 text-center">
|
||||
<h1 className="text-2xl font-semibold tracking-tight">
|
||||
Welcome back
|
||||
</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Enter your email to sign in to your account
|
||||
</p>
|
||||
</div>
|
||||
<SignInForm />
|
||||
<p className="px-8 text-center text-sm text-muted-foreground">
|
||||
<Link
|
||||
href="/auth/signup"
|
||||
className={cn(
|
||||
buttonVariants({ variant: "ghost" }),
|
||||
"hover:bg-transparent hover:underline",
|
||||
"px-0"
|
||||
)}
|
||||
>
|
||||
Don't have an account? Sign Up
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
68
src/app/auth/signup/page.tsx
Normal file
68
src/app/auth/signup/page.tsx
Normal file
@@ -0,0 +1,68 @@
|
||||
import { type Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { SignUpForm } from "~/app/_components/auth/sign-up-form";
|
||||
import { buttonVariants } from "~/components/ui/button";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Sign Up",
|
||||
description: "Create a new account",
|
||||
};
|
||||
|
||||
export default function SignUpPage() {
|
||||
return (
|
||||
<div className="container relative h-screen flex-col items-center justify-center grid lg:max-w-none lg:grid-cols-2 lg:px-0">
|
||||
<div className="relative hidden h-full flex-col bg-muted p-10 text-white lg:flex dark:border-r">
|
||||
<div className="absolute inset-0 bg-zinc-900" />
|
||||
<div className="relative z-20 flex items-center text-lg font-medium">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
className="mr-2 h-6 w-6"
|
||||
>
|
||||
<path d="M15 6v12a3 3 0 1 0 3-3H6a3 3 0 1 0 3 3V6a3 3 0 1 0-3 3h12a3 3 0 1 0-3-3" />
|
||||
</svg>
|
||||
HRI Studio
|
||||
</div>
|
||||
<div className="relative z-20 mt-auto">
|
||||
<blockquote className="space-y-2">
|
||||
<p className="text-lg">
|
||||
“HRI Studio has revolutionized how we conduct human-robot interaction studies.”
|
||||
</p>
|
||||
<footer className="text-sm">Sofia Dewar</footer>
|
||||
</blockquote>
|
||||
</div>
|
||||
</div>
|
||||
<div className="lg:p-8">
|
||||
<div className="mx-auto flex w-full flex-col justify-center space-y-6 sm:w-[350px]">
|
||||
<div className="flex flex-col space-y-2 text-center">
|
||||
<h1 className="text-2xl font-semibold tracking-tight">
|
||||
Create an account
|
||||
</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Enter your email below to create your account
|
||||
</p>
|
||||
</div>
|
||||
<SignUpForm />
|
||||
<p className="px-8 text-center text-sm text-muted-foreground">
|
||||
<Link
|
||||
href="/auth/signin"
|
||||
className={cn(
|
||||
buttonVariants({ variant: "ghost" }),
|
||||
"hover:bg-transparent hover:underline",
|
||||
"px-0"
|
||||
)}
|
||||
>
|
||||
Already have an account? Sign In
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
280
src/app/dashboard/account/page.tsx
Normal file
280
src/app/dashboard/account/page.tsx
Normal file
@@ -0,0 +1,280 @@
|
||||
"use client"
|
||||
|
||||
import { useSession } from "next-auth/react"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { z } from "zod"
|
||||
import { ImageIcon, Loader2 } from "lucide-react"
|
||||
import Image from "next/image"
|
||||
import { useState, useEffect } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
|
||||
import { Button } from "~/components/ui/button"
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "~/components/ui/card"
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "~/components/ui/form"
|
||||
import { Input } from "~/components/ui/input"
|
||||
import { PageContent } from "~/components/layout/page-content"
|
||||
import { PageHeader } from "~/components/layout/page-header"
|
||||
import { api } from "~/trpc/react"
|
||||
import { toast } from "sonner"
|
||||
import { uploadFile } from "~/lib/upload"
|
||||
import { ImageCropModal } from "~/components/ui/image-crop-modal"
|
||||
|
||||
const accountFormSchema = z.object({
|
||||
firstName: z.string().min(1, "First name is required"),
|
||||
lastName: z.string().min(1, "Last name is required"),
|
||||
email: z.string().email("Invalid email address").optional(),
|
||||
image: z.string().optional(),
|
||||
})
|
||||
|
||||
type AccountFormValues = z.infer<typeof accountFormSchema>
|
||||
|
||||
export default function AccountPage() {
|
||||
const { data: session, update: updateSession } = useSession()
|
||||
const [cropFile, setCropFile] = useState<File | null>(null)
|
||||
const [isUploading, setIsUploading] = useState(false)
|
||||
const [previewImage, setPreviewImage] = useState<string | null>(null)
|
||||
const router = useRouter()
|
||||
|
||||
// Debug full session object
|
||||
useEffect(() => {
|
||||
console.log("[Debug] Full session object:", JSON.stringify(session, null, 2));
|
||||
}, [session]);
|
||||
|
||||
const form = useForm<AccountFormValues>({
|
||||
resolver: zodResolver(accountFormSchema),
|
||||
defaultValues: {
|
||||
firstName: session?.user?.name?.split(" ")[0] ?? "",
|
||||
lastName: session?.user?.name?.split(" ")[1] ?? "",
|
||||
email: session?.user?.email ?? "",
|
||||
image: session?.user?.image ?? undefined,
|
||||
}
|
||||
});
|
||||
|
||||
const updateUser = api.user.update.useMutation();
|
||||
|
||||
const onSubmit = async (data: AccountFormValues) => {
|
||||
try {
|
||||
console.log("[1] Starting update with form data:", data);
|
||||
|
||||
// 1. Update database
|
||||
const result = await updateUser.mutateAsync({
|
||||
firstName: data.firstName,
|
||||
lastName: data.lastName,
|
||||
image: data.image ?? null,
|
||||
});
|
||||
console.log("[2] Database updated:", result);
|
||||
|
||||
// 2. Show success message
|
||||
toast.success("Profile updated");
|
||||
console.log("[3] Showing success toast");
|
||||
|
||||
// 3. Force a hard reload of the page
|
||||
console.log("[4] Forcing page reload");
|
||||
window.location.reload();
|
||||
|
||||
} catch (error) {
|
||||
console.error("[X] Update failed:", error);
|
||||
toast.error("Failed to update profile");
|
||||
}
|
||||
};
|
||||
|
||||
const handleCrop = async (blob: Blob) => {
|
||||
try {
|
||||
setIsUploading(true);
|
||||
|
||||
const file = new File([blob], cropFile?.name ?? "avatar.jpg", {
|
||||
type: cropFile?.type ?? "image/jpeg",
|
||||
});
|
||||
|
||||
const imageUrl = await uploadFile(file);
|
||||
|
||||
setPreviewImage(imageUrl);
|
||||
form.setValue("image", imageUrl);
|
||||
|
||||
} catch (error) {
|
||||
console.error("Error uploading file:", error);
|
||||
toast.error("Error uploading image");
|
||||
setPreviewImage(null);
|
||||
form.setValue("image", undefined);
|
||||
} finally {
|
||||
setIsUploading(false);
|
||||
setCropFile(null);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
title="Account Settings"
|
||||
description="Manage your profile information"
|
||||
/>
|
||||
<PageContent>
|
||||
<div className="grid gap-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Profile</CardTitle>
|
||||
<CardDescription>
|
||||
Update your profile picture and information
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
|
||||
<div className="flex flex-col gap-8 sm:flex-row">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="image"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex flex-col items-start justify-start">
|
||||
<FormLabel className="group flex size-32 cursor-pointer items-center justify-center overflow-hidden rounded-full border bg-muted transition-colors hover:bg-muted/80">
|
||||
{previewImage ? (
|
||||
<div className="relative size-full overflow-hidden rounded-full">
|
||||
<div className="absolute inset-0 z-10 flex items-center justify-center bg-black/60 opacity-0 transition-opacity group-hover:opacity-100">
|
||||
<p className="text-xs font-medium text-white">Change Image</p>
|
||||
</div>
|
||||
<Image
|
||||
src={previewImage}
|
||||
alt="Avatar"
|
||||
fill
|
||||
sizes="128px"
|
||||
className="object-cover"
|
||||
priority
|
||||
onError={(e) => {
|
||||
console.error("Error loading image:", previewImage);
|
||||
e.currentTarget.style.display = "none";
|
||||
setPreviewImage(null);
|
||||
form.setValue("image", undefined);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<ImageIcon className="size-8 text-muted-foreground transition-colors group-hover:text-muted-foreground/80" />
|
||||
)}
|
||||
<FormControl>
|
||||
<Input
|
||||
type="file"
|
||||
accept="image/*"
|
||||
className="hidden"
|
||||
onChange={(e) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file) {
|
||||
setCropFile(file);
|
||||
}
|
||||
}}
|
||||
disabled={isUploading}
|
||||
/>
|
||||
</FormControl>
|
||||
</FormLabel>
|
||||
<FormDescription>
|
||||
Click to upload a new profile picture
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<div className="flex-1 space-y-4">
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="firstName"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>First Name</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
placeholder="Enter your first name"
|
||||
{...field}
|
||||
disabled={updateUser.isPending}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="lastName"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Last Name</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
placeholder="Enter your last name"
|
||||
{...field}
|
||||
disabled={updateUser.isPending}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="email"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Email</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="email"
|
||||
placeholder="Enter your email"
|
||||
{...field}
|
||||
disabled
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
Email cannot be changed
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-end">
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={updateUser.isPending || isUploading}
|
||||
>
|
||||
{(updateUser.isPending || isUploading) && (
|
||||
<Loader2 className="mr-2 size-4 animate-spin" />
|
||||
)}
|
||||
Save Changes
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</PageContent>
|
||||
{cropFile && (
|
||||
<ImageCropModal
|
||||
file={cropFile}
|
||||
aspect={1}
|
||||
onCrop={handleCrop}
|
||||
onCancel={() => setCropFile(null)}
|
||||
className="sm:max-w-md"
|
||||
cropBoxClassName="rounded-full border-2 border-primary shadow-2xl"
|
||||
overlayClassName="bg-background/80 backdrop-blur-sm"
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -1,26 +1,54 @@
|
||||
import { Sidebar } from "~/components/sidebar";
|
||||
import { Breadcrumb } from "~/components/breadcrumb";
|
||||
import { ActiveStudyProvider } from "~/context/active-study";
|
||||
import { StudyProvider } from "~/context/StudyContext";
|
||||
"use client"
|
||||
|
||||
import { useEffect } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useSession } from "next-auth/react"
|
||||
|
||||
import { AppSidebar } from "~/components/navigation/app-sidebar"
|
||||
import { Header } from "~/components/navigation/header"
|
||||
import { SidebarProvider } from "~/components/ui/sidebar"
|
||||
import { StudyProvider } from "~/components/providers/study-provider"
|
||||
import { PageTransition } from "~/components/layout/page-transition"
|
||||
|
||||
export default function DashboardLayout({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
const { data: session, status } = useSession()
|
||||
const router = useRouter()
|
||||
|
||||
useEffect(() => {
|
||||
if (status === "unauthenticated") {
|
||||
router.replace("/login")
|
||||
}
|
||||
}, [status, router])
|
||||
|
||||
// Show nothing while loading
|
||||
if (status === "loading") {
|
||||
return null
|
||||
}
|
||||
|
||||
// Show nothing if not authenticated (will redirect)
|
||||
if (!session) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<ActiveStudyProvider>
|
||||
<SidebarProvider>
|
||||
<StudyProvider>
|
||||
<div className="flex h-screen">
|
||||
<Sidebar />
|
||||
<div className="flex-1 flex flex-col min-h-0">
|
||||
<main className="flex-1 overflow-y-auto p-6">
|
||||
<Breadcrumb />
|
||||
{children}
|
||||
<div className="flex h-full min-h-screen w-full">
|
||||
<AppSidebar />
|
||||
<div className="flex w-0 flex-1 flex-col">
|
||||
<Header />
|
||||
<main className="flex-1 overflow-auto p-4">
|
||||
<PageTransition>
|
||||
{children}
|
||||
</PageTransition>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
</StudyProvider>
|
||||
</ActiveStudyProvider>
|
||||
);
|
||||
}
|
||||
</SidebarProvider>
|
||||
)
|
||||
}
|
||||
@@ -1,159 +1,68 @@
|
||||
'use client';
|
||||
import { Beaker, Plus, Users } from "lucide-react"
|
||||
import Link from "next/link"
|
||||
import { Button } from "~/components/ui/button"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "~/components/ui/card"
|
||||
import { PageContent } from "~/components/layout/page-content"
|
||||
import { PageHeader } from "~/components/layout/page-header"
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "~/components/ui/card";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { BookOpen, Settings2 } from "lucide-react";
|
||||
import { useToast } from "~/hooks/use-toast";
|
||||
import { getApiUrl } from "~/lib/fetch-utils";
|
||||
import { Skeleton } from "~/components/ui/skeleton";
|
||||
import { useActiveStudy } from "~/context/active-study";
|
||||
|
||||
interface DashboardStats {
|
||||
studyCount: number;
|
||||
activeInvitationCount: number;
|
||||
}
|
||||
|
||||
export default function Dashboard() {
|
||||
const [stats, setStats] = useState<DashboardStats>({
|
||||
studyCount: 0,
|
||||
activeInvitationCount: 0,
|
||||
});
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const router = useRouter();
|
||||
const { toast } = useToast();
|
||||
const { studies, setActiveStudy } = useActiveStudy();
|
||||
|
||||
const fetchStats = useCallback(async () => {
|
||||
try {
|
||||
const response = await fetch(getApiUrl('/api/studies'));
|
||||
if (!response.ok) throw new Error("Failed to fetch studies");
|
||||
const { data } = await response.json();
|
||||
setStats({
|
||||
studyCount: data.length,
|
||||
activeInvitationCount: 0
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error fetching stats:", error);
|
||||
toast({
|
||||
title: "Error",
|
||||
description: "Failed to load dashboard statistics",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [toast]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchStats();
|
||||
}, [fetchStats]);
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<Skeleton className="h-8 w-[200px] mb-2" />
|
||||
<Skeleton className="h-4 w-[300px]" />
|
||||
</div>
|
||||
<Skeleton className="h-10 w-[140px]" />
|
||||
export default function DashboardPage() {
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
title="Dashboard"
|
||||
description="Welcome to your research platform."
|
||||
/>
|
||||
<PageContent>
|
||||
<div className="grid gap-4 md:grid-cols-3">
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">Total Studies</CardTitle>
|
||||
<Beaker className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">0</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Active research studies
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">Total Participants</CardTitle>
|
||||
<Users className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">0</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Across all studies
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">Quick Actions</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Button asChild variant="outline" className="w-full">
|
||||
<Link href="/dashboard/studies/new">
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Create New Study
|
||||
</Link>
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 grid-cols-1 md:grid-cols-3">
|
||||
{[1, 2].map((i) => (
|
||||
<Card key={i}>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<Skeleton className="h-4 w-[100px]" />
|
||||
<Skeleton className="h-4 w-4" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Skeleton className="h-7 w-[50px] mb-1" />
|
||||
<Skeleton className="h-3 w-[120px]" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<Skeleton className="h-5 w-[120px] mb-2" />
|
||||
<Skeleton className="h-4 w-[200px]" />
|
||||
</CardHeader>
|
||||
<CardContent className="flex gap-4">
|
||||
<Skeleton className="h-10 w-[140px]" />
|
||||
<Skeleton className="h-10 w-[120px]" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold tracking-tight">Dashboard</h2>
|
||||
<p className="text-muted-foreground">
|
||||
Welcome back to your research dashboard
|
||||
</p>
|
||||
</div>
|
||||
<Button onClick={() => router.push('/dashboard/studies/new')}>
|
||||
Create New Study
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 grid-cols-1 md:grid-cols-3">
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">
|
||||
Total Studies
|
||||
</CardTitle>
|
||||
<BookOpen className="h-4 w-4 text-muted-foreground" />
|
||||
<CardTitle>Recent Activity</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">{stats.studyCount}</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Active research studies
|
||||
<p className="text-sm text-muted-foreground">
|
||||
No recent activity to show.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">
|
||||
Pending Invitations
|
||||
</CardTitle>
|
||||
<Settings2 className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">{stats.activeInvitationCount}</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Awaiting responses
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Quick Actions</CardTitle>
|
||||
<CardDescription>Common tasks and actions</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex gap-4">
|
||||
<Button onClick={() => router.push('/dashboard/studies/new')}>
|
||||
Create New Study
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => router.push('/dashboard/settings')}
|
||||
>
|
||||
<Settings2 className="w-4 h-4 mr-2" />
|
||||
Settings
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
</PageContent>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -1,239 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { PlusIcon, Trash2Icon } from "lucide-react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
CardDescription,
|
||||
CardFooter
|
||||
} from "~/components/ui/card";
|
||||
import { Input } from "~/components/ui/input";
|
||||
import { Label } from "~/components/ui/label";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue
|
||||
} from "~/components/ui/select";
|
||||
import { usePermissions } from "~/hooks/usePermissions";
|
||||
import { getApiUrl } from "~/lib/fetch-utils";
|
||||
|
||||
interface Study {
|
||||
id: number;
|
||||
title: string;
|
||||
}
|
||||
|
||||
interface Participant {
|
||||
id: number;
|
||||
name: string;
|
||||
studyId: number;
|
||||
}
|
||||
|
||||
export default function Participants() {
|
||||
const [studies, setStudies] = useState<Study[]>([]);
|
||||
const [participants, setParticipants] = useState<Participant[]>([]);
|
||||
const [selectedStudyId, setSelectedStudyId] = useState<number | null>(null);
|
||||
const [participantName, setParticipantName] = useState("");
|
||||
const [loading, setLoading] = useState(true);
|
||||
const { hasPermission } = usePermissions();
|
||||
|
||||
useEffect(() => {
|
||||
fetchStudies();
|
||||
}, []);
|
||||
|
||||
const fetchStudies = async () => {
|
||||
try {
|
||||
const response = await fetch(getApiUrl('/api/studies'));
|
||||
const data = await response.json();
|
||||
setStudies(data);
|
||||
} catch (error) {
|
||||
console.error('Error fetching studies:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const fetchParticipants = async (studyId: number) => {
|
||||
try {
|
||||
console.log(`Fetching participants for studyId: ${studyId}`);
|
||||
const response = await fetch(getApiUrl(`/api/participants?studyId=${studyId}`));
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
setParticipants(data);
|
||||
} catch (error) {
|
||||
console.error('Error fetching participants:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleStudyChange = (studyId: string) => {
|
||||
const id = parseInt(studyId); // Convert the string to a number
|
||||
setSelectedStudyId(id);
|
||||
fetchParticipants(id);
|
||||
};
|
||||
|
||||
const addParticipant = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!selectedStudyId) return;
|
||||
|
||||
try {
|
||||
const response = await fetch(getApiUrl('/api/participants'), {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
name: participantName,
|
||||
studyId: selectedStudyId,
|
||||
}),
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const newParticipant = await response.json();
|
||||
setParticipants([...participants, newParticipant]);
|
||||
setParticipantName("");
|
||||
} else {
|
||||
console.error('Error adding participant:', response.statusText);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error adding participant:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const deleteParticipant = async (id: number) => {
|
||||
try {
|
||||
const response = await fetch(getApiUrl('/api/participants/${id}'), {
|
||||
method: 'DELETE',
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
setParticipants(participants.filter(participant => participant.id !== id));
|
||||
} else {
|
||||
console.error('Error deleting participant:', response.statusText);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error deleting participant:', error);
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return <div>Loading...</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="max-w-4xl mx-auto">
|
||||
<div className="flex justify-between items-center mb-8">
|
||||
<h1 className="text-3xl font-bold">Participants</h1>
|
||||
</div>
|
||||
|
||||
<Card className="mb-8">
|
||||
<CardHeader>
|
||||
<CardTitle>Study Selection</CardTitle>
|
||||
<CardDescription>
|
||||
Select a study to manage its participants
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="study">Select Study</Label>
|
||||
<Select onValueChange={handleStudyChange}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select a study" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{studies.map((study) => (
|
||||
<SelectItem key={study.id} value={study.id.toString()}>
|
||||
{study.title}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="mb-8">
|
||||
<CardHeader>
|
||||
<CardTitle>Add New Participant</CardTitle>
|
||||
<CardDescription>
|
||||
Add a new participant to the selected study
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={addParticipant} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="name">Participant Name</Label>
|
||||
<Input
|
||||
type="text"
|
||||
id="name"
|
||||
value={participantName}
|
||||
onChange={(e) => setParticipantName(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<Button type="submit" disabled={!selectedStudyId}>
|
||||
<PlusIcon className="w-4 h-4 mr-2" />
|
||||
Add Participant
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="grid gap-4">
|
||||
{participants.map((participant) => (
|
||||
<Card key={participant.id}>
|
||||
<CardHeader>
|
||||
<div className="flex justify-between items-start">
|
||||
<div>
|
||||
<CardTitle>{participant.name}</CardTitle>
|
||||
<CardDescription className="mt-1.5">
|
||||
Participant ID: {participant.id}
|
||||
</CardDescription>
|
||||
</div>
|
||||
{hasPermission('DELETE_PARTICIPANT') && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="text-destructive"
|
||||
onClick={() => deleteParticipant(participant.id)}
|
||||
>
|
||||
<Trash2Icon className="w-4 h-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardFooter className="text-sm text-muted-foreground">
|
||||
Study ID: {participant.studyId}
|
||||
</CardFooter>
|
||||
</Card>
|
||||
))}
|
||||
{participants.length === 0 && selectedStudyId && (
|
||||
<Card>
|
||||
<CardContent className="py-8">
|
||||
<p className="text-center text-muted-foreground">
|
||||
No participants found for this study. Add one above to get started.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
{!selectedStudyId && (
|
||||
<Card>
|
||||
<CardContent className="py-8">
|
||||
<p className="text-center text-muted-foreground">
|
||||
Please select a study to view its participants.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useParams } from "next/navigation";
|
||||
import { useEffect } from "react";
|
||||
import { useActiveStudy } from "~/context/active-study";
|
||||
import { Skeleton } from "~/components/ui/skeleton";
|
||||
|
||||
export default function StudyLayout({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const { id } = useParams();
|
||||
const { studies, activeStudy, setActiveStudy, isLoading } = useActiveStudy();
|
||||
|
||||
useEffect(() => {
|
||||
if (studies.length > 0 && id) {
|
||||
const study = studies.find(s => s.id === parseInt(id as string));
|
||||
if (study && (!activeStudy || activeStudy.id !== study.id)) {
|
||||
setActiveStudy(study);
|
||||
}
|
||||
}
|
||||
}, [id, studies, activeStudy, setActiveStudy]);
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="h-6">
|
||||
<Skeleton className="h-4 w-[250px]" />
|
||||
</div>
|
||||
<Skeleton className="h-[400px]" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return children;
|
||||
}
|
||||
@@ -1,182 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { useParams } from "next/navigation";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "~/components/ui/card";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { useToast } from "~/hooks/use-toast";
|
||||
import { Plus, Users, FileText, BarChart, PlayCircle } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useActiveStudy } from "~/context/active-study";
|
||||
import { getApiUrl } from "~/lib/fetch-utils";
|
||||
import { Skeleton } from "~/components/ui/skeleton";
|
||||
|
||||
interface StudyStats {
|
||||
participantCount: number;
|
||||
formCount: number;
|
||||
trialCount: number;
|
||||
}
|
||||
|
||||
export default function StudyDashboard() {
|
||||
const [stats, setStats] = useState<StudyStats>({
|
||||
participantCount: 0,
|
||||
formCount: 0,
|
||||
trialCount: 0,
|
||||
});
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const { id } = useParams();
|
||||
const { toast } = useToast();
|
||||
const { activeStudy } = useActiveStudy();
|
||||
|
||||
const fetchStats = useCallback(async () => {
|
||||
try {
|
||||
const response = await fetch(getApiUrl(`/api/studies/${id}/stats`));
|
||||
if (!response.ok) throw new Error("Failed to fetch stats");
|
||||
const { data } = await response.json();
|
||||
setStats({
|
||||
participantCount: data?.participantCount ?? 0,
|
||||
formCount: data?.formCount ?? 0,
|
||||
trialCount: data?.trialCount ?? 0
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error fetching stats:", error);
|
||||
toast({
|
||||
title: "Error",
|
||||
description: "Failed to load study statistics",
|
||||
variant: "destructive",
|
||||
});
|
||||
// Set default values on error
|
||||
setStats({
|
||||
participantCount: 0,
|
||||
formCount: 0,
|
||||
trialCount: 0
|
||||
});
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [toast, id]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchStats();
|
||||
}, [fetchStats]);
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<Skeleton className="h-8 w-[200px] mb-2" />
|
||||
<Skeleton className="h-4 w-[300px]" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 grid-cols-1 md:grid-cols-3">
|
||||
{[1, 2, 3].map((i) => (
|
||||
<Card key={i}>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<Skeleton className="h-4 w-[100px]" />
|
||||
<Skeleton className="h-4 w-4" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Skeleton className="h-7 w-[50px] mb-1" />
|
||||
<Skeleton className="h-3 w-[120px]" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<Skeleton className="h-5 w-[120px] mb-2" />
|
||||
<Skeleton className="h-4 w-[200px]" />
|
||||
</CardHeader>
|
||||
<CardContent className="flex gap-4">
|
||||
<Skeleton className="h-10 w-[140px]" />
|
||||
<Skeleton className="h-10 w-[120px]" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold tracking-tight">{activeStudy?.title}</h2>
|
||||
<p className="text-muted-foreground">
|
||||
Overview of your study's progress and statistics
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 grid-cols-1 md:grid-cols-3">
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">
|
||||
Participants
|
||||
</CardTitle>
|
||||
<Users className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">{stats.participantCount}</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Total enrolled participants
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">
|
||||
Forms
|
||||
</CardTitle>
|
||||
<FileText className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">{stats.formCount}</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Active study forms
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">
|
||||
Trials
|
||||
</CardTitle>
|
||||
<BarChart className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">{stats.trialCount}</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Completed trials
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Quick Actions</CardTitle>
|
||||
<CardDescription>Common tasks and actions for this study</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex gap-4">
|
||||
<Button asChild>
|
||||
<Link href={`/dashboard/studies/${id}/participants/new`}>
|
||||
<Plus className="w-4 h-4 mr-2" />
|
||||
Add Participant
|
||||
</Link>
|
||||
</Button>
|
||||
<Button variant="outline" asChild>
|
||||
<Link href={`/dashboard/studies/${id}/trials/new`}>
|
||||
<PlayCircle className="w-4 h-4 mr-2" />
|
||||
Start Trial
|
||||
</Link>
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,112 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useParams, useRouter } from "next/navigation";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "~/components/ui/card";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { Input } from "~/components/ui/input";
|
||||
import { Label } from "~/components/ui/label";
|
||||
import { useToast } from "~/hooks/use-toast";
|
||||
import { ArrowLeft } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useActiveStudy } from "~/context/active-study";
|
||||
import { hasPermission } from "~/lib/permissions-client";
|
||||
import { PERMISSIONS } from "~/lib/permissions";
|
||||
import { getApiUrl } from "~/lib/fetch-utils";
|
||||
|
||||
export default function NewParticipant() {
|
||||
const [name, setName] = useState("");
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const { id } = useParams();
|
||||
const router = useRouter();
|
||||
const { toast } = useToast();
|
||||
const { activeStudy } = useActiveStudy();
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeStudy || !hasPermission(activeStudy.permissions, PERMISSIONS.CREATE_PARTICIPANT)) {
|
||||
router.push(`/dashboard/studies/${id}`);
|
||||
}
|
||||
}, [activeStudy, id, router]);
|
||||
|
||||
if (!activeStudy || !hasPermission(activeStudy.permissions, PERMISSIONS.CREATE_PARTICIPANT)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setIsSubmitting(true);
|
||||
|
||||
try {
|
||||
const response = await fetch(getApiUrl(`/api/studies/${id}/participants`), {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ name }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to create participant");
|
||||
}
|
||||
|
||||
toast({
|
||||
title: "Success",
|
||||
description: "Participant created successfully",
|
||||
});
|
||||
|
||||
router.push(`/dashboard/studies/${id}/participants`);
|
||||
} catch (error) {
|
||||
console.error("Error creating participant:", error);
|
||||
toast({
|
||||
title: "Error",
|
||||
description: "Failed to create participant",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="gap-2"
|
||||
asChild
|
||||
>
|
||||
<Link href={`/dashboard/studies/${id}/participants`}>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
Back to Participants
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Add New Participant</CardTitle>
|
||||
<CardDescription>
|
||||
Create a new participant for {activeStudy?.title}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="name">Participant Name</Label>
|
||||
<Input
|
||||
id="name"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="Enter participant name"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<Button type="submit" disabled={isSubmitting}>
|
||||
{isSubmitting ? "Creating..." : "Create Participant"}
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,345 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { useParams } from "next/navigation";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "~/components/ui/card";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { useToast } from "~/hooks/use-toast";
|
||||
import { Plus, Trash2 } from "lucide-react";
|
||||
import { useActiveStudy } from "~/context/active-study";
|
||||
import { hasPermission } from "~/lib/permissions-client";
|
||||
import { PERMISSIONS } from "~/lib/permissions";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from "~/components/ui/alert-dialog";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "~/components/ui/dialog";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "~/components/ui/table";
|
||||
import { getApiUrl } from "~/lib/fetch-utils";
|
||||
import { Skeleton } from "~/components/ui/skeleton";
|
||||
import { Input } from "~/components/ui/input";
|
||||
import { Label } from "~/components/ui/label";
|
||||
|
||||
interface Participant {
|
||||
id: number;
|
||||
name: string;
|
||||
studyId: number;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export default function ParticipantsList() {
|
||||
const [participants, setParticipants] = useState<Participant[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [isAddingParticipant, setIsAddingParticipant] = useState(false);
|
||||
const [newParticipantName, setNewParticipantName] = useState("");
|
||||
const { id } = useParams();
|
||||
const { toast } = useToast();
|
||||
const { activeStudy } = useActiveStudy();
|
||||
|
||||
const canCreateParticipant = activeStudy && hasPermission(activeStudy.permissions, PERMISSIONS.CREATE_PARTICIPANT);
|
||||
const canDeleteParticipant = activeStudy && hasPermission(activeStudy.permissions, PERMISSIONS.DELETE_PARTICIPANT);
|
||||
const canViewNames = activeStudy && hasPermission(activeStudy.permissions, PERMISSIONS.VIEW_PARTICIPANT_NAMES);
|
||||
|
||||
const fetchParticipants = useCallback(async () => {
|
||||
try {
|
||||
const response = await fetch(getApiUrl(`/api/studies/${id}/participants`));
|
||||
if (!response.ok) throw new Error("Failed to fetch participants");
|
||||
const data = await response.json();
|
||||
setParticipants(data.data || []);
|
||||
} catch (error) {
|
||||
console.error("Error fetching participants:", error);
|
||||
toast({
|
||||
title: "Error",
|
||||
description: "Failed to load participants",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [id, toast]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchParticipants();
|
||||
}, [fetchParticipants]);
|
||||
|
||||
const handleDelete = async (participantId: number) => {
|
||||
try {
|
||||
const response = await fetch(getApiUrl(`/api/studies/${id}/participants`), {
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ participantId }),
|
||||
});
|
||||
|
||||
if (!response.ok) throw new Error("Failed to delete participant");
|
||||
|
||||
setParticipants(participants.filter(p => p.id !== participantId));
|
||||
toast({
|
||||
title: "Success",
|
||||
description: "Participant deleted successfully",
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error deleting participant:", error);
|
||||
toast({
|
||||
title: "Error",
|
||||
description: "Failed to delete participant",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleAddParticipant = async () => {
|
||||
if (!newParticipantName.trim()) return;
|
||||
|
||||
setIsAddingParticipant(true);
|
||||
try {
|
||||
const response = await fetch(getApiUrl(`/api/studies/${id}/participants`), {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ name: newParticipantName }),
|
||||
});
|
||||
|
||||
if (!response.ok) throw new Error("Failed to add participant");
|
||||
|
||||
const data = await response.json();
|
||||
setParticipants([...participants, data.data]);
|
||||
setNewParticipantName("");
|
||||
toast({
|
||||
title: "Success",
|
||||
description: "Participant added successfully",
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error adding participant:", error);
|
||||
toast({
|
||||
title: "Error",
|
||||
description: "Failed to add participant",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsAddingParticipant(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<Skeleton className="h-8 w-[200px] mb-2" />
|
||||
<Skeleton className="h-4 w-[300px]" />
|
||||
</div>
|
||||
<Skeleton className="h-10 w-[140px]" />
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<Skeleton className="h-5 w-[150px] mb-2" />
|
||||
<Skeleton className="h-4 w-[250px]" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead><Skeleton className="h-4 w-[120px]" /></TableHead>
|
||||
<TableHead><Skeleton className="h-4 w-[100px]" /></TableHead>
|
||||
<TableHead className="w-[100px]"><Skeleton className="h-4 w-[60px]" /></TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{[1, 2, 3].map((i) => (
|
||||
<TableRow key={i}>
|
||||
<TableCell><Skeleton className="h-4 w-[150px]" /></TableCell>
|
||||
<TableCell><Skeleton className="h-4 w-[100px]" /></TableCell>
|
||||
<TableCell><Skeleton className="h-8 w-8" /></TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold tracking-tight">Participants</h2>
|
||||
<p className="text-muted-foreground">
|
||||
Manage study participants and their data
|
||||
</p>
|
||||
</div>
|
||||
{canCreateParticipant && (
|
||||
<Dialog>
|
||||
<DialogTrigger asChild>
|
||||
<Button>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Add Participant
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Add Participant</DialogTitle>
|
||||
<DialogDescription>
|
||||
Add a new participant to {activeStudy?.title}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4 py-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="name">Participant Name</Label>
|
||||
<Input
|
||||
id="name"
|
||||
placeholder="Enter participant name"
|
||||
value={newParticipantName}
|
||||
onChange={(e) => setNewParticipantName(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
onClick={handleAddParticipant}
|
||||
disabled={isAddingParticipant || !newParticipantName.trim()}
|
||||
>
|
||||
{isAddingParticipant ? "Adding..." : "Add Participant"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Study Participants</CardTitle>
|
||||
<CardDescription>
|
||||
All participants enrolled in {activeStudy?.title}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{participants.length > 0 ? (
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Name</TableHead>
|
||||
<TableHead>Added</TableHead>
|
||||
{canDeleteParticipant && <TableHead className="w-[100px]">Actions</TableHead>}
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{participants.map((participant) => (
|
||||
<TableRow key={participant.id}>
|
||||
<TableCell>
|
||||
{canViewNames ? participant.name : `Participant ${participant.id}`}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{new Date(participant.createdAt).toLocaleDateString()}
|
||||
</TableCell>
|
||||
{canDeleteParticipant && (
|
||||
<TableCell>
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger asChild>
|
||||
<Button variant="ghost" size="icon">
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete Participant</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Are you sure you want to delete this participant? This action cannot be undone.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={() => handleDelete(participant.id)}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
Delete
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</TableCell>
|
||||
)}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
) : (
|
||||
<div className="py-8 text-center text-muted-foreground">
|
||||
No participants added yet
|
||||
{canCreateParticipant && (
|
||||
<>
|
||||
.{" "}
|
||||
<Dialog>
|
||||
<DialogTrigger asChild>
|
||||
<Button variant="link" className="px-2 py-0">
|
||||
Add your first participant
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Add Participant</DialogTitle>
|
||||
<DialogDescription>
|
||||
Add a new participant to {activeStudy?.title}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4 py-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="name-empty">Participant Name</Label>
|
||||
<Input
|
||||
id="name-empty"
|
||||
placeholder="Enter participant name"
|
||||
value={newParticipantName}
|
||||
onChange={(e) => setNewParticipantName(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
onClick={handleAddParticipant}
|
||||
disabled={isAddingParticipant || !newParticipantName.trim()}
|
||||
>
|
||||
{isAddingParticipant ? "Adding..." : "Add Participant"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,144 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from "react";
|
||||
import { useParams, useRouter } from "next/navigation";
|
||||
import { SettingsTab } from "~/components/studies/settings-tab";
|
||||
import { UsersTab } from "~/components/studies/users-tab";
|
||||
import { useEffect } from "react";
|
||||
import { PERMISSIONS } from "~/lib/permissions-client";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { Settings2Icon, UsersIcon } from "lucide-react";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { getApiUrl } from "~/lib/fetch-utils";
|
||||
import { Card, CardContent } from "~/components/ui/card";
|
||||
import { Skeleton } from "~/components/ui/skeleton";
|
||||
|
||||
interface Study {
|
||||
id: number;
|
||||
title: string;
|
||||
description: string | null;
|
||||
permissions: string[];
|
||||
}
|
||||
|
||||
export default function StudySettings() {
|
||||
const [study, setStudy] = useState<Study | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [activeTab, setActiveTab] = useState<'settings' | 'users'>('settings');
|
||||
const { id } = useParams();
|
||||
const router = useRouter();
|
||||
|
||||
useEffect(() => {
|
||||
const fetchStudy = async () => {
|
||||
try {
|
||||
const response = await fetch(getApiUrl(`/api/studies/${id}`));
|
||||
if (!response.ok) {
|
||||
if (response.status === 403) {
|
||||
router.push('/dashboard/studies');
|
||||
return;
|
||||
}
|
||||
throw new Error("Failed to fetch study");
|
||||
}
|
||||
const data = await response.json();
|
||||
|
||||
// Check if user has any required permissions
|
||||
const requiredPermissions = [PERMISSIONS.EDIT_STUDY, PERMISSIONS.MANAGE_ROLES];
|
||||
const hasAccess = data.data.permissions.some(p => requiredPermissions.includes(p));
|
||||
|
||||
if (!hasAccess) {
|
||||
router.push('/dashboard/studies');
|
||||
return;
|
||||
}
|
||||
|
||||
setStudy(data.data);
|
||||
} catch (error) {
|
||||
console.error("Error fetching study:", error);
|
||||
setError(error instanceof Error ? error.message : "Failed to load study");
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchStudy();
|
||||
}, [id, router]);
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<Skeleton className="h-8 w-[150px] mb-2" />
|
||||
<Skeleton className="h-4 w-[250px]" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-6">
|
||||
<div className="w-48 flex flex-col gap-2">
|
||||
<Skeleton className="h-10 w-full" />
|
||||
<Skeleton className="h-10 w-full" />
|
||||
</div>
|
||||
|
||||
<div className="flex-1">
|
||||
<Card>
|
||||
<CardContent className="py-6">
|
||||
<div className="space-y-4">
|
||||
<Skeleton className="h-4 w-[200px]" />
|
||||
<Skeleton className="h-10 w-full" />
|
||||
<Skeleton className="h-10 w-full" />
|
||||
<Skeleton className="h-10 w-2/3" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error || !study) {
|
||||
return <div>Error: {error}</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold tracking-tight">Settings</h2>
|
||||
<p className="text-muted-foreground">
|
||||
Manage study settings and team members
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-6">
|
||||
<div className="w-48 flex flex-col gap-2">
|
||||
<Button
|
||||
variant={activeTab === 'settings' ? 'secondary' : 'ghost'}
|
||||
className="justify-start"
|
||||
onClick={() => setActiveTab('settings')}
|
||||
>
|
||||
<Settings2Icon className="mr-2 h-4 w-4" />
|
||||
Settings
|
||||
</Button>
|
||||
<Button
|
||||
variant={activeTab === 'users' ? 'secondary' : 'ghost'}
|
||||
className="justify-start"
|
||||
onClick={() => setActiveTab('users')}
|
||||
>
|
||||
<UsersIcon className="mr-2 h-4 w-4" />
|
||||
Users
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex-1">
|
||||
<div className={cn(activeTab === 'settings' ? 'block' : 'hidden')}>
|
||||
<SettingsTab study={study} />
|
||||
</div>
|
||||
<div className={cn(activeTab === 'users' ? 'block' : 'hidden')}>
|
||||
<UsersTab studyId={study.id} permissions={study.permissions} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,137 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "~/components/ui/card";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { Input } from "~/components/ui/input";
|
||||
import { Label } from "~/components/ui/label";
|
||||
import { Textarea } from "~/components/ui/textarea";
|
||||
import { useToast } from "~/hooks/use-toast";
|
||||
import { ArrowLeft, Settings2Icon } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useActiveStudy } from "~/context/active-study";
|
||||
import { getApiUrl } from "~/lib/fetch-utils";
|
||||
|
||||
export default function NewStudy() {
|
||||
const [title, setTitle] = useState("");
|
||||
const [description, setDescription] = useState("");
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const router = useRouter();
|
||||
const { toast } = useToast();
|
||||
const { refreshStudies } = useActiveStudy();
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setIsSubmitting(true);
|
||||
|
||||
try {
|
||||
const response = await fetch(getApiUrl('/api/studies'), {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ title, description }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to create study");
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
toast({
|
||||
title: "Success",
|
||||
description: "Study created successfully",
|
||||
});
|
||||
|
||||
// Refresh studies list and redirect to the new study
|
||||
await refreshStudies();
|
||||
router.push(`/dashboard/studies/${data.data.id}`);
|
||||
} catch (error) {
|
||||
console.error("Error creating study:", error);
|
||||
toast({
|
||||
title: "Error",
|
||||
description: "Failed to create study",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold tracking-tight">Create New Study</h2>
|
||||
<p className="text-muted-foreground">
|
||||
Set up a new research study and configure its settings
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="gap-2"
|
||||
asChild
|
||||
>
|
||||
<Link href="/dashboard">
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
Back to Dashboard
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-6">
|
||||
<div className="w-48 flex flex-col gap-2">
|
||||
<Button
|
||||
variant="secondary"
|
||||
className="justify-start"
|
||||
>
|
||||
<Settings2Icon className="mr-2 h-4 w-4" />
|
||||
Basic Settings
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex-1">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Study Details</CardTitle>
|
||||
<CardDescription>
|
||||
Configure the basic settings for your new study
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="title">Study Title</Label>
|
||||
<Input
|
||||
id="title"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
placeholder="Enter study title"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="description">Description</Label>
|
||||
<Textarea
|
||||
id="description"
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
placeholder="Enter study description"
|
||||
rows={4}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex justify-end">
|
||||
<Button type="submit" disabled={isSubmitting}>
|
||||
{isSubmitting ? "Creating..." : "Create Study"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,237 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { PlusIcon, Trash2Icon, Settings2, ArrowRight } from "lucide-react";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "~/components/ui/card";
|
||||
import { useToast } from "~/hooks/use-toast";
|
||||
import { PERMISSIONS, hasPermission } from "~/lib/permissions-client";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
AlertDialogFooter
|
||||
} from "~/components/ui/alert-dialog";
|
||||
import { getApiUrl } from "~/lib/fetch-utils";
|
||||
import { Skeleton } from "~/components/ui/skeleton";
|
||||
import { useActiveStudy } from "~/context/active-study";
|
||||
|
||||
interface Study {
|
||||
id: number;
|
||||
title: string;
|
||||
description: string | null;
|
||||
userId: string;
|
||||
environment: string;
|
||||
createdAt: Date;
|
||||
updatedAt: Date | null;
|
||||
permissions: string[];
|
||||
roles: string[];
|
||||
}
|
||||
|
||||
function formatRoleName(role: string): string {
|
||||
return role
|
||||
.split('_')
|
||||
.map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
|
||||
.join(' ');
|
||||
}
|
||||
|
||||
export default function Studies() {
|
||||
const [studies, setStudies] = useState<Study[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const router = useRouter();
|
||||
const { toast } = useToast();
|
||||
const { setActiveStudy } = useActiveStudy();
|
||||
|
||||
const fetchStudies = useCallback(async () => {
|
||||
try {
|
||||
const response = await fetch(getApiUrl("/api/studies"));
|
||||
if (!response.ok) throw new Error("Failed to fetch studies");
|
||||
const { data } = await response.json();
|
||||
setStudies(data.map((study: any) => ({
|
||||
...study,
|
||||
createdAt: new Date(study.createdAt),
|
||||
updatedAt: study.updatedAt ? new Date(study.updatedAt) : null
|
||||
})));
|
||||
} catch (error) {
|
||||
console.error("Error fetching studies:", error);
|
||||
toast({
|
||||
title: "Error",
|
||||
description: "Failed to load studies",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [toast]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchStudies();
|
||||
}, [fetchStudies]);
|
||||
|
||||
const handleDelete = async (id: number) => {
|
||||
try {
|
||||
const response = await fetch(getApiUrl(`/api/studies/${id}`), {
|
||||
method: "DELETE",
|
||||
});
|
||||
|
||||
if (!response.ok) throw new Error("Failed to delete study");
|
||||
|
||||
setStudies(studies.filter(study => study.id !== id));
|
||||
toast({
|
||||
title: "Success",
|
||||
description: "Study deleted successfully",
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error deleting study:", error);
|
||||
toast({
|
||||
title: "Error",
|
||||
description: "Failed to delete study",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleEnterStudy = (study: Study) => {
|
||||
setActiveStudy(study);
|
||||
router.push(`/dashboard/studies/${study.id}`);
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<Skeleton className="h-8 w-[150px] mb-2" />
|
||||
<Skeleton className="h-4 w-[300px]" />
|
||||
</div>
|
||||
<Skeleton className="h-10 w-[140px]" />
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4">
|
||||
{[1, 2, 3].map((i) => (
|
||||
<Card key={i}>
|
||||
<CardContent className="p-6">
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-5 w-[200px] mb-1" />
|
||||
<Skeleton className="h-4 w-[300px] mb-1" />
|
||||
<Skeleton className="h-4 w-[150px]" />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Skeleton className="h-9 w-[100px]" />
|
||||
<Skeleton className="h-9 w-9" />
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold tracking-tight">Studies</h2>
|
||||
<p className="text-muted-foreground">
|
||||
Manage your research studies and experiments
|
||||
</p>
|
||||
</div>
|
||||
{hasPermission(studies[0]?.permissions || [], PERMISSIONS.CREATE_STUDY) && (
|
||||
<Button onClick={() => router.push('/dashboard/studies/new')}>
|
||||
<PlusIcon className="w-4 h-4 mr-2" />
|
||||
Create New Study
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4">
|
||||
{studies.length > 0 ? (
|
||||
studies.map((study) => (
|
||||
<Card key={study.id}>
|
||||
<CardContent className="p-6">
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="space-y-1">
|
||||
<h3 className="font-semibold leading-none tracking-tight">
|
||||
{study.title}
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{study.description || "No description provided."}
|
||||
</p>
|
||||
<p className="text-sm">
|
||||
<span className="text-muted-foreground">Your Roles: </span>
|
||||
<span className="text-foreground">
|
||||
{study.roles?.map(formatRoleName).join(", ")}
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleEnterStudy(study)}
|
||||
>
|
||||
Enter Study
|
||||
<ArrowRight className="ml-2 h-4 w-4" />
|
||||
</Button>
|
||||
{(hasPermission(study.permissions, PERMISSIONS.EDIT_STUDY) ||
|
||||
hasPermission(study.permissions, PERMISSIONS.MANAGE_ROLES)) && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => router.push(`/dashboard/studies/${study.id}/settings`)}
|
||||
>
|
||||
<Settings2 className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
{hasPermission(study.permissions, PERMISSIONS.DELETE_STUDY) && (
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger asChild>
|
||||
<Button variant="ghost" size="sm">
|
||||
<Trash2Icon className="h-4 w-4" />
|
||||
</Button>
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete Study</AlertDialogTitle>
|
||||
</AlertDialogHeader>
|
||||
<p>
|
||||
Are you sure you want to delete this study? This action cannot be undone.
|
||||
</p>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={() => handleDelete(study.id)}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
Delete
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))
|
||||
) : (
|
||||
<Card>
|
||||
<CardContent className="py-8">
|
||||
<p className="text-center text-muted-foreground">
|
||||
No studies found{hasPermission(studies[0]?.permissions || [], PERMISSIONS.CREATE_STUDY) ? ". Create your first study above" : ""}.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,127 +1,21 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
body {
|
||||
font-family: Arial, Helvetica, sans-serif;
|
||||
}
|
||||
|
||||
@layer base {
|
||||
:root {
|
||||
--background: 210 50% 98%;
|
||||
--foreground: 215 25% 27%;
|
||||
--card: 210 50% 98%;
|
||||
--card-foreground: 215 25% 27%;
|
||||
--popover: 210 50% 98%;
|
||||
--popover-foreground: 215 25% 27%;
|
||||
--primary: 215 60% 40%;
|
||||
--primary-foreground: 210 50% 98%;
|
||||
--secondary: 210 55% 92%;
|
||||
--secondary-foreground: 215 25% 27%;
|
||||
--muted: 210 55% 92%;
|
||||
--muted-foreground: 215 20% 50%;
|
||||
--accent: 210 55% 92%;
|
||||
--accent-foreground: 215 25% 27%;
|
||||
--destructive: 0 84% 60%;
|
||||
--destructive-foreground: 210 50% 98%;
|
||||
--border: 214 32% 91%;
|
||||
--input: 214 32% 91%;
|
||||
--ring: 215 60% 40%;
|
||||
--radius: 0.5rem;
|
||||
|
||||
/* Update gradient variables */
|
||||
--gradient-start: 210 50% 96%;
|
||||
--gradient-end: 210 50% 98%;
|
||||
|
||||
/* Updated sidebar variables for a clean, light look */
|
||||
--sidebar-background: 210 50% 98%;
|
||||
--sidebar-foreground: 215 25% 27%;
|
||||
--sidebar-muted: 215 20% 50%;
|
||||
--sidebar-hover: 210 50% 94%;
|
||||
--sidebar-border: 214 32% 91%;
|
||||
--sidebar-separator: 214 32% 91%;
|
||||
--sidebar-active: 210 50% 92%;
|
||||
|
||||
--card-level-1: 210 50% 95%;
|
||||
--card-level-2: 210 50% 90%;
|
||||
--card-level-3: 210 50% 85%;
|
||||
.auth-gradient {
|
||||
@apply relative bg-background;
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: 220 20% 15%;
|
||||
--foreground: 220 20% 90%;
|
||||
--card: 220 20% 15%;
|
||||
--card-foreground: 220 20% 90%;
|
||||
--popover: 220 20% 15%;
|
||||
--popover-foreground: 220 20% 90%;
|
||||
--primary: 220 60% 50%;
|
||||
--primary-foreground: 220 20% 90%;
|
||||
--secondary: 220 30% 20%;
|
||||
--secondary-foreground: 220 20% 90%;
|
||||
--muted: 220 30% 20%;
|
||||
--muted-foreground: 220 20% 70%;
|
||||
--accent: 220 30% 20%;
|
||||
--accent-foreground: 220 20% 90%;
|
||||
--destructive: 0 62% 40%;
|
||||
--destructive-foreground: 220 20% 90%;
|
||||
--border: 220 30% 20%;
|
||||
--input: 220 30% 20%;
|
||||
--ring: 220 60% 50%;
|
||||
|
||||
/* Update gradient variables for dark mode */
|
||||
--gradient-start: 220 20% 12%;
|
||||
--gradient-end: 220 20% 15%;
|
||||
|
||||
/* Updated sidebar variables for dark mode */
|
||||
--sidebar-background-top: 220 20% 15%;
|
||||
--sidebar-background-bottom: 220 20% 15%;
|
||||
--sidebar-foreground: 220 20% 90%;
|
||||
--sidebar-muted: 220 20% 60%;
|
||||
--sidebar-hover: 220 20% 20%;
|
||||
--sidebar-border: 220 20% 25%;
|
||||
--sidebar-separator: 220 20% 22%;
|
||||
|
||||
--card-level-1: 220 20% 12%;
|
||||
--card-level-2: 220 20% 10%;
|
||||
--card-level-3: 220 20% 8%;
|
||||
.auth-gradient::before {
|
||||
@apply absolute inset-0 -z-10 bg-[radial-gradient(circle_at_top,_var(--tw-gradient-stops))] from-primary/20 via-background to-background content-[''];
|
||||
}
|
||||
|
||||
/* Add these utility classes */
|
||||
.card-level-1 {
|
||||
background-color: hsl(var(--card-level-1));
|
||||
.auth-gradient::after {
|
||||
@apply absolute inset-0 -z-10 bg-[url('/grid.svg')] bg-center opacity-10 content-[''];
|
||||
}
|
||||
|
||||
.card-level-2 {
|
||||
background-color: hsl(var(--card-level-2));
|
||||
.auth-card {
|
||||
@apply relative overflow-hidden border border-border/50 bg-card/95 backdrop-blur supports-[backdrop-filter]:bg-card/50;
|
||||
}
|
||||
|
||||
.card-level-3 {
|
||||
background-color: hsl(var(--card-level-3));
|
||||
.auth-input {
|
||||
@apply h-10 bg-background/50 backdrop-blur supports-[backdrop-filter]:bg-background/30;
|
||||
}
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border;
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
}
|
||||
|
||||
/* Sidebar specific styles */
|
||||
.sidebar-separator {
|
||||
@apply my-3 border-t border-[hsl(var(--sidebar-separator))] opacity-60;
|
||||
}
|
||||
|
||||
.sidebar-dropdown-content {
|
||||
@apply bg-[hsl(var(--sidebar-background))] border-[hsl(var(--sidebar-border))];
|
||||
}
|
||||
|
||||
.sidebar-button {
|
||||
@apply hover:bg-[hsl(var(--sidebar-hover))] text-[hsl(var(--sidebar-foreground))];
|
||||
}
|
||||
|
||||
.sidebar-button[data-active="true"] {
|
||||
@apply bg-[hsl(var(--sidebar-active))] font-medium;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
import { ImageResponse } from "next/og";
|
||||
|
||||
export const runtime = "edge";
|
||||
export const contentType = "image/svg+xml";
|
||||
export const size = {
|
||||
width: 32,
|
||||
height: 32,
|
||||
};
|
||||
|
||||
export default function Icon() {
|
||||
return new ImageResponse(
|
||||
(
|
||||
<div
|
||||
style={{
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
background: "transparent",
|
||||
}}
|
||||
>
|
||||
<svg
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
<path d="M12 8V4H8" />
|
||||
<rect width="16" height="12" x="4" y="8" rx="2" />
|
||||
<path d="M2 14h2" />
|
||||
<path d="M20 14h2" />
|
||||
<path d="M15 13v2" />
|
||||
<path d="M9 13v2" />
|
||||
</svg>
|
||||
</div>
|
||||
),
|
||||
{
|
||||
...size,
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -1,143 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "~/components/ui/card";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { useUser } from "@clerk/nextjs";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { Logo } from "~/components/logo";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from "~/components/ui/alert-dialog";
|
||||
|
||||
interface InvitationAcceptContentProps {
|
||||
token: string;
|
||||
}
|
||||
|
||||
export function InvitationAcceptContent({ token }: InvitationAcceptContentProps) {
|
||||
const { isLoaded, isSignedIn } = useUser();
|
||||
const router = useRouter();
|
||||
const [isAccepting, setIsAccepting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const handleAcceptInvitation = async () => {
|
||||
setIsAccepting(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/invitations/accept/${token}`, {
|
||||
method: "POST",
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
throw new Error(errorText || "Failed to accept invitation");
|
||||
}
|
||||
|
||||
router.push("/dashboard");
|
||||
} catch (error) {
|
||||
setError(error instanceof Error ? error.message : "Failed to accept invitation");
|
||||
setIsAccepting(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (!isLoaded) {
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-screen">
|
||||
<Loader2 className="h-8 w-8 animate-spin" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center min-h-screen bg-gray-50/50">
|
||||
<div className="w-full max-w-md px-4 py-8">
|
||||
<div className="flex flex-col items-center mb-8">
|
||||
<div className="mb-6">
|
||||
<Logo className="h-10" />
|
||||
</div>
|
||||
<p className="text-gray-500 text-center">
|
||||
A platform for managing human-robot interaction studies
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Card className="shadow-lg">
|
||||
<CardHeader>
|
||||
<CardTitle>Research Study Invitation</CardTitle>
|
||||
<CardDescription>
|
||||
You've been invited to collaborate on a research study.
|
||||
{!isSignedIn && " Please sign in or create an account to continue."}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{error && (
|
||||
<div className="mb-4 p-4 text-sm text-red-800 bg-red-100 rounded-lg">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isSignedIn ? (
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger asChild>
|
||||
<Button className="w-full" disabled={isAccepting}>
|
||||
Accept Invitation
|
||||
</Button>
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Accept Research Study Invitation</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Are you sure you want to accept this invitation? You will be added as a collaborator to the research study.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={handleAcceptInvitation}
|
||||
disabled={isAccepting}
|
||||
>
|
||||
{isAccepting ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
Accepting...
|
||||
</>
|
||||
) : (
|
||||
"Accept"
|
||||
)}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
) : (
|
||||
<div className="flex flex-col gap-3">
|
||||
<Button
|
||||
variant="default"
|
||||
className="w-full"
|
||||
onClick={() => router.push(`/sign-in?redirect_url=${encodeURIComponent(`/invite/accept/${token}`)}`)}
|
||||
>
|
||||
Sign In
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full"
|
||||
onClick={() => router.push(`/sign-up?redirect_url=${encodeURIComponent(`/invite/accept/${token}`)}`)}
|
||||
>
|
||||
Create Account
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
import { Suspense } from "react";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { InvitationAcceptContent } from "./invitation-accept-content";
|
||||
|
||||
interface InvitationAcceptPageProps {
|
||||
params: { token: string };
|
||||
}
|
||||
|
||||
export default async function InvitationAcceptPage({ params }: InvitationAcceptPageProps) {
|
||||
const token = await Promise.resolve(params.token);
|
||||
|
||||
return (
|
||||
<Suspense
|
||||
fallback={
|
||||
<div className="flex items-center justify-center min-h-screen">
|
||||
<Loader2 className="h-8 w-8 animate-spin" />
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<InvitationAcceptContent token={token} />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
@@ -1,23 +1,47 @@
|
||||
import { ClerkProvider } from "@clerk/nextjs";
|
||||
import { Inter } from 'next/font/google';
|
||||
import { Toaster } from "~/components/ui/toaster";
|
||||
import "~/app/globals.css";
|
||||
import "~/styles/globals.css";
|
||||
|
||||
const inter = Inter({ subsets: ['latin'] });
|
||||
import { Inter } from "next/font/google";
|
||||
import { GeistSans } from 'geist/font/sans';
|
||||
import { headers } from "next/headers";
|
||||
|
||||
import { TRPCReactProvider } from "~/trpc/react";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { Providers } from "~/components/providers";
|
||||
import DatabaseCheck from "~/components/db-check";
|
||||
|
||||
const inter = Inter({
|
||||
subsets: ["latin"],
|
||||
variable: "--font-sans",
|
||||
});
|
||||
|
||||
|
||||
export const metadata = {
|
||||
title: "HRIStudio",
|
||||
description: "A platform for managing human research studies and participant interactions.",
|
||||
icons: [{ rel: "icon", url: "/favicon.ico" }],
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
return (
|
||||
<ClerkProvider>
|
||||
<html lang="en">
|
||||
<body className={inter.className}>
|
||||
{children}
|
||||
<Toaster />
|
||||
</body>
|
||||
</html>
|
||||
</ClerkProvider>
|
||||
<html lang="en" className="h-full">
|
||||
<body className={cn(
|
||||
"min-h-screen bg-background font-sans antialiased",
|
||||
inter.variable
|
||||
)}>
|
||||
<TRPCReactProvider {...{ headers: headers() }}>
|
||||
<Providers>
|
||||
<DatabaseCheck>
|
||||
<div className="relative h-full">
|
||||
{children}
|
||||
</div>
|
||||
</DatabaseCheck>
|
||||
</Providers>
|
||||
</TRPCReactProvider>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
103
src/app/login/login-form.tsx
Normal file
103
src/app/login/login-form.tsx
Normal file
@@ -0,0 +1,103 @@
|
||||
'use client';
|
||||
|
||||
import { signIn } from "next-auth/react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { Input } from "~/components/ui/input";
|
||||
import { Label } from "~/components/ui/label";
|
||||
import Link from "next/link";
|
||||
import { Loader2 } from "lucide-react";
|
||||
|
||||
export function LoginForm({ error }: { error: boolean }) {
|
||||
const router = useRouter();
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
async function onSubmit(e: React.FormEvent<HTMLFormElement>) {
|
||||
e.preventDefault();
|
||||
setIsLoading(true);
|
||||
|
||||
const formData = new FormData(e.currentTarget);
|
||||
const response = await signIn("credentials", {
|
||||
email: formData.get("email"),
|
||||
password: formData.get("password"),
|
||||
redirect: false,
|
||||
});
|
||||
|
||||
setIsLoading(false);
|
||||
|
||||
if (!response?.error) {
|
||||
router.push("/dashboard");
|
||||
router.refresh();
|
||||
} else {
|
||||
router.push("/login?error=CredentialsSignin");
|
||||
router.refresh();
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={onSubmit} className="animate-in fade-in-50 slide-in-from-bottom-4">
|
||||
{error && (
|
||||
<div className="mb-4 rounded border border-destructive/50 bg-destructive/10 p-3 text-sm text-destructive">
|
||||
<p>Invalid email or password</p>
|
||||
</div>
|
||||
)}
|
||||
<div className="grid gap-4">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="email">Email</Label>
|
||||
<Input
|
||||
id="email"
|
||||
name="email"
|
||||
placeholder="name@example.com"
|
||||
type="email"
|
||||
autoCapitalize="none"
|
||||
autoComplete="email"
|
||||
autoCorrect="off"
|
||||
className="auth-input"
|
||||
disabled={isLoading}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label htmlFor="password">Password</Label>
|
||||
<Link
|
||||
href="/forgot-password"
|
||||
className="text-sm text-muted-foreground transition-colors hover:text-primary"
|
||||
>
|
||||
Forgot password?
|
||||
</Link>
|
||||
</div>
|
||||
<Input
|
||||
id="password"
|
||||
name="password"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
className="auth-input"
|
||||
disabled={isLoading}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<Button className="w-full" type="submit" disabled={isLoading}>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
Signing in...
|
||||
</>
|
||||
) : (
|
||||
"Sign In"
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="mt-4 text-center text-sm text-muted-foreground">
|
||||
Don't have an account?{" "}
|
||||
<Link
|
||||
href="/register"
|
||||
className="font-medium text-primary underline-offset-4 transition-colors hover:underline"
|
||||
>
|
||||
Sign up
|
||||
</Link>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
80
src/app/login/page.tsx
Normal file
80
src/app/login/page.tsx
Normal file
@@ -0,0 +1,80 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { redirect } from "next/navigation";
|
||||
import { getServerAuthSession } from "~/server/auth";
|
||||
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardTitle,
|
||||
} from "~/components/ui/card";
|
||||
import { LoginForm } from "./login-form";
|
||||
import { Logo } from "~/components/logo";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Login | HRIStudio",
|
||||
description: "Login to your account",
|
||||
};
|
||||
|
||||
export default async function LoginPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<Record<string, string | string[] | undefined>>
|
||||
}) {
|
||||
const session = await getServerAuthSession();
|
||||
if (session) {
|
||||
redirect("/dashboard");
|
||||
}
|
||||
|
||||
const params = await searchParams;
|
||||
const error = params?.error ? String(params.error) : null;
|
||||
const showError = error === "CredentialsSignin";
|
||||
|
||||
return (
|
||||
<div className="auth-gradient relative flex min-h-screen items-center justify-center px-4">
|
||||
<Logo
|
||||
className="absolute left-4 top-4 text-lg transition-colors hover:text-primary md:left-8 md:top-8"
|
||||
iconClassName="text-primary"
|
||||
/>
|
||||
<div className="w-full max-w-[800px] px-4 py-8">
|
||||
<Card className="auth-card shadow-xl transition-shadow hover:shadow-lg">
|
||||
<CardContent className="grid p-0 md:grid-cols-2">
|
||||
<div className="p-6 md:p-8">
|
||||
<div className="mb-6 space-y-2">
|
||||
<CardTitle className="text-2xl font-bold tracking-tight">
|
||||
Welcome back
|
||||
</CardTitle>
|
||||
<CardDescription className="text-base">
|
||||
Sign in to your account to continue
|
||||
</CardDescription>
|
||||
</div>
|
||||
<LoginForm error={showError} />
|
||||
</div>
|
||||
<div className="relative hidden h-full md:block">
|
||||
<div className="absolute inset-0 bg-gradient-to-br from-primary/30 via-primary/20 to-secondary/10 rounded-r-lg" />
|
||||
<div className="absolute inset-0 flex items-center justify-center">
|
||||
<Logo
|
||||
className="pointer-events-none"
|
||||
iconClassName="h-32 w-32 mr-0 text-primary/40"
|
||||
textClassName="sr-only"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<p className="mt-6 text-center text-sm text-muted-foreground">
|
||||
By signing in, you agree to our{" "}
|
||||
<Link href="/terms" className="underline underline-offset-4 hover:text-primary">
|
||||
Terms of Service
|
||||
</Link>{" "}
|
||||
and{" "}
|
||||
<Link href="/privacy" className="underline underline-offset-4 hover:text-primary">
|
||||
Privacy Policy
|
||||
</Link>
|
||||
.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,31 +1,36 @@
|
||||
'use client';
|
||||
|
||||
import { SignedIn, SignedOut, SignInButton, SignUpButton, UserButton } from "@clerk/nextjs";
|
||||
import { getServerAuthSession } from "~/server/auth";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import Image from "next/image";
|
||||
import Link from "next/link";
|
||||
import { BotIcon } from "lucide-react";
|
||||
import { Logo } from "~/components/logo";
|
||||
|
||||
export default function Home() {
|
||||
export default async function Home() {
|
||||
const session = await getServerAuthSession();
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-background">
|
||||
{/* Navigation Bar */}
|
||||
<nav className="border-b bg-card/50 backdrop-blur supports-[backdrop-filter]:bg-card/50">
|
||||
<div className="container mx-auto px-4 h-16 flex items-center justify-between">
|
||||
<Logo />
|
||||
<div className="flex items-center space-x-2">
|
||||
<Logo />
|
||||
</div>
|
||||
<div className="flex items-center space-x-4">
|
||||
<SignedOut>
|
||||
<SignInButton mode="modal">
|
||||
<Button variant="ghost">Sign In</Button>
|
||||
</SignInButton>
|
||||
<SignUpButton mode="modal">
|
||||
<Button>Sign Up</Button>
|
||||
</SignUpButton>
|
||||
</SignedOut>
|
||||
<SignedIn>
|
||||
<UserButton afterSignOutUrl="/" />
|
||||
</SignedIn>
|
||||
{!session && (
|
||||
<>
|
||||
<Button variant="ghost" asChild>
|
||||
<Link href="/login">Sign In</Link>
|
||||
</Button>
|
||||
<Button asChild>
|
||||
<Link href="/register">Sign Up</Link>
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
{session && (
|
||||
<Button asChild>
|
||||
<Link href="/dashboard">Dashboard</Link>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
@@ -40,20 +45,15 @@ export default function Home() {
|
||||
A comprehensive platform for designing, executing, and analyzing Wizard-of-Oz experiments in human-robot interaction studies.
|
||||
</p>
|
||||
<div className="mt-8 flex flex-col sm:flex-row gap-4">
|
||||
<SignedOut>
|
||||
<SignUpButton mode="modal">
|
||||
<Button size="lg" className="w-full sm:w-auto">
|
||||
Get Started
|
||||
</Button>
|
||||
</SignUpButton>
|
||||
</SignedOut>
|
||||
<SignedIn>
|
||||
{!session ? (
|
||||
<Button size="lg" className="w-full sm:w-auto" asChild>
|
||||
<Link href="/dashboard">
|
||||
Go to Dashboard
|
||||
</Link>
|
||||
<Link href="/register">Get Started</Link>
|
||||
</Button>
|
||||
</SignedIn>
|
||||
) : (
|
||||
<Button size="lg" className="w-full sm:w-auto" asChild>
|
||||
<Link href="/dashboard">Go to Dashboard</Link>
|
||||
</Button>
|
||||
)}
|
||||
<Button size="lg" variant="outline" className="w-full sm:w-auto" asChild>
|
||||
<Link href="https://github.com/soconnor0919/hristudio" target="_blank">
|
||||
View on GitHub
|
||||
@@ -61,14 +61,11 @@ export default function Home() {
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="relative">
|
||||
<Image
|
||||
src="/hristudio_laptop.png"
|
||||
alt="HRIStudio Interface"
|
||||
width={800}
|
||||
height={600}
|
||||
priority
|
||||
/>
|
||||
<div className="relative aspect-video">
|
||||
<div className="absolute inset-0 bg-gradient-to-br from-primary/20 to-secondary/20 rounded-lg" />
|
||||
<div className="absolute inset-0 flex items-center justify-center">
|
||||
<BotIcon className="h-32 w-32 text-primary/40" />
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -97,4 +94,4 @@ export default function Home() {
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
142
src/app/register/page.tsx
Normal file
142
src/app/register/page.tsx
Normal file
@@ -0,0 +1,142 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { redirect } from "next/navigation";
|
||||
import { getServerAuthSession } from "~/server/auth";
|
||||
|
||||
import { Button } from "~/components/ui/button";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardTitle
|
||||
} from "~/components/ui/card";
|
||||
import { Input } from "~/components/ui/input";
|
||||
import { Label } from "~/components/ui/label";
|
||||
import { Logo } from "~/components/logo";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Register | HRIStudio",
|
||||
description: "Create a new account",
|
||||
};
|
||||
|
||||
export default async function RegisterPage() {
|
||||
const session = await getServerAuthSession();
|
||||
|
||||
if (session) {
|
||||
redirect("/dashboard");
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="auth-gradient relative flex min-h-screen items-center justify-center px-4">
|
||||
<Logo
|
||||
className="absolute left-4 top-4 text-lg transition-colors hover:text-primary md:left-8 md:top-8"
|
||||
iconClassName="text-primary"
|
||||
/>
|
||||
<div className="w-full max-w-[800px] px-4 py-8">
|
||||
<Card className="auth-card shadow-xl transition-shadow hover:shadow-lg">
|
||||
<CardContent className="grid p-0 md:grid-cols-2">
|
||||
<div className="p-6 md:p-8">
|
||||
<div className="mb-6 space-y-2">
|
||||
<CardTitle className="text-2xl font-bold tracking-tight">
|
||||
Create an account
|
||||
</CardTitle>
|
||||
<CardDescription className="text-base">
|
||||
Enter your details to get started
|
||||
</CardDescription>
|
||||
</div>
|
||||
<form action="/api/auth/register" method="POST" className="animate-in fade-in-50 slide-in-from-bottom-4">
|
||||
<div className="grid gap-4">
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="firstName">First Name</Label>
|
||||
<Input
|
||||
id="firstName"
|
||||
name="firstName"
|
||||
placeholder="John"
|
||||
autoComplete="given-name"
|
||||
className="auth-input"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="lastName">Last Name</Label>
|
||||
<Input
|
||||
id="lastName"
|
||||
name="lastName"
|
||||
placeholder="Doe"
|
||||
autoComplete="family-name"
|
||||
className="auth-input"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="email">Email</Label>
|
||||
<Input
|
||||
id="email"
|
||||
name="email"
|
||||
placeholder="name@example.com"
|
||||
type="email"
|
||||
autoCapitalize="none"
|
||||
autoComplete="email"
|
||||
autoCorrect="off"
|
||||
className="auth-input"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="password">Password</Label>
|
||||
<Input
|
||||
id="password"
|
||||
name="password"
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
className="auth-input"
|
||||
required
|
||||
/>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Must be at least 8 characters long
|
||||
</p>
|
||||
</div>
|
||||
<Button className="w-full" type="submit">
|
||||
Create account
|
||||
</Button>
|
||||
</div>
|
||||
<div className="mt-4 text-center text-sm text-muted-foreground">
|
||||
Already have an account?{" "}
|
||||
<Link
|
||||
href="/login"
|
||||
className="font-medium text-primary underline-offset-4 transition-colors hover:underline"
|
||||
>
|
||||
Sign in
|
||||
</Link>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<div className="relative hidden h-full md:block">
|
||||
<div className="absolute inset-0 bg-gradient-to-br from-primary/30 via-primary/20 to-secondary/10 rounded-r-lg" />
|
||||
<div className="absolute inset-0 flex items-center justify-center">
|
||||
<Logo
|
||||
className="pointer-events-none"
|
||||
iconClassName="h-32 w-32 mr-0 text-primary/40"
|
||||
textClassName="sr-only"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<p className="mt-6 text-center text-sm text-muted-foreground">
|
||||
By creating an account, you agree to our{" "}
|
||||
<Link href="/terms" className="underline underline-offset-4 hover:text-primary">
|
||||
Terms of Service
|
||||
</Link>{" "}
|
||||
and{" "}
|
||||
<Link href="/privacy" className="underline underline-offset-4 hover:text-primary">
|
||||
Privacy Policy
|
||||
</Link>
|
||||
.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import React from "react";
|
||||
import { SignIn } from "@clerk/nextjs";
|
||||
|
||||
export default function SignInPage() {
|
||||
return (
|
||||
<div className="container flex items-center justify-center min-h-screen py-10">
|
||||
<SignIn />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import React from "react";
|
||||
import { SignUp } from "@clerk/nextjs";
|
||||
|
||||
export default function SignUpPage() {
|
||||
return (
|
||||
<div className="container flex items-center justify-center min-h-screen py-10">
|
||||
<SignUp />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
15
src/app/studies/[id]/page.tsx
Normal file
15
src/app/studies/[id]/page.tsx
Normal file
@@ -0,0 +1,15 @@
|
||||
export default async function StudyPage({ params }: { params: { id: string } }) {
|
||||
const study = await db.query.studies.findFirst({
|
||||
where: (studies, { eq }) => eq(studies.id, params.id),
|
||||
with: { experiments: true }
|
||||
})
|
||||
|
||||
return (
|
||||
<div className="max-w-6xl mx-auto p-6">
|
||||
<StudyHeader study={study} />
|
||||
<Suspense fallback={<ExperimentListSkeleton />}>
|
||||
<ExperimentList studyId={params.id} />
|
||||
</Suspense>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
22
src/auth.ts
Normal file
22
src/auth.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { Auth } from "@auth/core"
|
||||
import Credentials from "@auth/core/providers/credentials"
|
||||
|
||||
export const authOptions: AuthConfig = {
|
||||
providers: [
|
||||
Credentials({
|
||||
credentials: {
|
||||
email: { label: "Email", type: "email" },
|
||||
password: { label: "Password", type: "password" }
|
||||
},
|
||||
async authorize(credentials) {
|
||||
// Drizzle ORM user lookup
|
||||
const user = await db.query.users.findFirst({
|
||||
where: (users, { eq }) => eq(users.email, credentials.email)
|
||||
})
|
||||
return verifyPassword(credentials.password, user?.password) ? user : null
|
||||
}
|
||||
})
|
||||
],
|
||||
session: { strategy: "jwt" },
|
||||
adapter: DrizzleAdapter(db)
|
||||
}
|
||||
149
src/components/auth/study-switcher.tsx
Normal file
149
src/components/auth/study-switcher.tsx
Normal file
@@ -0,0 +1,149 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { Notebook, ChevronsUpDown, Plus } from "lucide-react"
|
||||
import { useSession } from "next-auth/react"
|
||||
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "~/components/ui/dropdown-menu"
|
||||
import {
|
||||
SidebarMenu,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
useSidebar,
|
||||
} from "~/components/ui/sidebar"
|
||||
import { useStudy } from "~/components/providers/study-provider"
|
||||
import { Button } from "~/components/ui/button"
|
||||
import { cn } from "~/lib/utils"
|
||||
|
||||
export function StudySwitcher() {
|
||||
const { status } = useSession()
|
||||
|
||||
// Show nothing while loading to prevent flash
|
||||
if (status === "loading") {
|
||||
return null
|
||||
}
|
||||
|
||||
return <StudySwitcherContent />
|
||||
}
|
||||
|
||||
function StudySwitcherContent() {
|
||||
const { isMobile } = useSidebar()
|
||||
const router = useRouter()
|
||||
const { studies, activeStudy, setActiveStudy, isLoading } = useStudy()
|
||||
|
||||
const handleCreateStudy = () => {
|
||||
router.push("/dashboard/studies/new")
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton
|
||||
size="lg"
|
||||
className="animate-pulse"
|
||||
>
|
||||
<div className="flex aspect-square size-8 items-center justify-center rounded-lg bg-sidebar-accent/10">
|
||||
<Notebook className="size-4 text-muted-foreground/50" />
|
||||
</div>
|
||||
<div className="grid flex-1 gap-1">
|
||||
<div className="h-4 w-24 rounded bg-sidebar-accent/10" />
|
||||
<div className="h-3 w-16 rounded bg-sidebar-accent/10" />
|
||||
</div>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenu>
|
||||
)
|
||||
}
|
||||
|
||||
if (!studies || studies.length === 0) {
|
||||
return (
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton
|
||||
size="lg"
|
||||
onClick={handleCreateStudy}
|
||||
className="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground"
|
||||
>
|
||||
<div className="flex aspect-square size-8 items-center justify-center rounded-lg bg-sidebar-primary text-sidebar-primary-foreground">
|
||||
<Plus className="size-4" />
|
||||
</div>
|
||||
<div className="grid flex-1 text-left text-sm leading-tight">
|
||||
<span className="truncate font-semibold">Create Study</span>
|
||||
<span className="truncate text-xs">Get started</span>
|
||||
</div>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenu>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<SidebarMenuButton
|
||||
size="lg"
|
||||
className="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground"
|
||||
>
|
||||
<div className="flex aspect-square size-8 items-center justify-center rounded-lg bg-sidebar-primary text-sidebar-primary-foreground">
|
||||
<Notebook className="size-4" />
|
||||
</div>
|
||||
<div className="grid flex-1 text-left text-sm leading-tight">
|
||||
<span className="truncate font-semibold">
|
||||
{activeStudy?.title ?? "Select Study"}
|
||||
</span>
|
||||
<span className="truncate text-xs">{activeStudy?.role ?? ""}</span>
|
||||
</div>
|
||||
<ChevronsUpDown className="ml-auto size-4" />
|
||||
</SidebarMenuButton>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent
|
||||
className="w-[--radix-dropdown-menu-trigger-width] min-w-56 rounded-lg"
|
||||
align="start"
|
||||
side={isMobile ? "bottom" : "right"}
|
||||
sideOffset={4}
|
||||
>
|
||||
<DropdownMenuLabel className="text-xs text-muted-foreground">
|
||||
Studies
|
||||
</DropdownMenuLabel>
|
||||
{studies.map((study) => (
|
||||
<DropdownMenuItem
|
||||
key={study.id}
|
||||
onClick={() => setActiveStudy(study)}
|
||||
className="gap-2 p-2"
|
||||
>
|
||||
<div className="flex size-6 items-center justify-center rounded-sm border">
|
||||
<Notebook className="size-4 shrink-0" />
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<p>{study.title}</p>
|
||||
<p className="text-xs text-muted-foreground">{study.role}</p>
|
||||
</div>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
onClick={handleCreateStudy}
|
||||
className="gap-2 p-2"
|
||||
>
|
||||
<div className="flex size-6 items-center justify-center rounded-md">
|
||||
<Plus className="size-4 text-muted-foreground" />
|
||||
</div>
|
||||
<div className="font-medium text-muted-foreground">Create new study</div>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenu>
|
||||
)
|
||||
}
|
||||
35
src/components/auth/user-avatar.tsx
Normal file
35
src/components/auth/user-avatar.tsx
Normal file
@@ -0,0 +1,35 @@
|
||||
"use client";
|
||||
|
||||
import { User } from "next-auth";
|
||||
import { Avatar, AvatarFallback } from "~/components/ui/avatar";
|
||||
import Image from "next/image";
|
||||
|
||||
interface UserAvatarProps {
|
||||
user: Pick<User, "name" | "image">;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function UserAvatar({ user, className }: UserAvatarProps) {
|
||||
return (
|
||||
<Avatar className={className}>
|
||||
{user.image ? (
|
||||
<div className="relative size-full">
|
||||
<Image
|
||||
alt={user.name ?? "Avatar"}
|
||||
src={user.image}
|
||||
fill
|
||||
sizes="32px"
|
||||
className="rounded-full object-cover"
|
||||
onError={(e) => {
|
||||
console.error("Error loading avatar image:", user.image);
|
||||
e.currentTarget.style.display = "none";
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
<AvatarFallback>
|
||||
{user.name?.charAt(0).toUpperCase() ?? "?"}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
);
|
||||
}
|
||||
@@ -1,116 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { ChevronRight } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { useActiveStudy } from "~/context/active-study";
|
||||
|
||||
interface BreadcrumbItem {
|
||||
label: string;
|
||||
href?: string;
|
||||
}
|
||||
|
||||
export function Breadcrumb() {
|
||||
const pathname = usePathname();
|
||||
const { activeStudy } = useActiveStudy();
|
||||
|
||||
const getBreadcrumbs = (): BreadcrumbItem[] => {
|
||||
const items: BreadcrumbItem[] = [{ label: 'Dashboard', href: '/dashboard' }];
|
||||
const path = pathname.split('/').filter(Boolean);
|
||||
|
||||
// Handle root dashboard
|
||||
if (path.length === 1 && path[0] === 'dashboard') {
|
||||
return items;
|
||||
}
|
||||
|
||||
// Handle studies list page
|
||||
if (path[1] === 'studies') {
|
||||
items.push({ label: 'Studies', href: '/dashboard/studies' });
|
||||
|
||||
if (path[2] === 'new') {
|
||||
items.push({ label: 'New Study' });
|
||||
return items;
|
||||
}
|
||||
|
||||
if (!activeStudy) {
|
||||
return items;
|
||||
}
|
||||
|
||||
// Handle active study pages
|
||||
items.push({
|
||||
label: activeStudy.title,
|
||||
href: `/dashboard/studies/${activeStudy.id}`
|
||||
});
|
||||
|
||||
// Add section based on URL
|
||||
if (path.length > 3) {
|
||||
const section = path[3];
|
||||
const sectionLabel = section.charAt(0).toUpperCase() + section.slice(1);
|
||||
|
||||
if (section === 'new') {
|
||||
items.push({
|
||||
label: `New ${path[2].slice(0, -1)}`,
|
||||
href: `/dashboard/studies/${activeStudy.id}/${path[2]}/new`
|
||||
});
|
||||
} else {
|
||||
items.push({
|
||||
label: sectionLabel,
|
||||
href: `/dashboard/studies/${activeStudy.id}/${section}`
|
||||
});
|
||||
}
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
// Handle participants page
|
||||
if (path[1] === 'participants') {
|
||||
items.push({ label: 'Participants', href: '/dashboard/participants' });
|
||||
return items;
|
||||
}
|
||||
|
||||
// Handle settings page
|
||||
if (path[1] === 'settings') {
|
||||
items.push({ label: 'Settings', href: '/dashboard/settings' });
|
||||
return items;
|
||||
}
|
||||
|
||||
// Handle profile page
|
||||
if (path[1] === 'profile') {
|
||||
items.push({ label: 'Profile', href: '/dashboard/profile' });
|
||||
return items;
|
||||
}
|
||||
|
||||
return items;
|
||||
};
|
||||
|
||||
const breadcrumbs = getBreadcrumbs();
|
||||
|
||||
// Always show breadcrumbs on dashboard pages
|
||||
if (breadcrumbs.length <= 1 && !pathname.startsWith('/dashboard')) return null;
|
||||
|
||||
return (
|
||||
<div className="flex items-center space-x-2 text-sm text-muted-foreground mb-6">
|
||||
{breadcrumbs.map((item, index) => {
|
||||
const isLast = index === breadcrumbs.length - 1;
|
||||
|
||||
return (
|
||||
<div key={item.label} className="flex items-center">
|
||||
{index > 0 && <ChevronRight className="h-4 w-4 mx-2" />}
|
||||
{item.href && !isLast ? (
|
||||
<Link
|
||||
href={item.href}
|
||||
className="hover:text-foreground transition-colors"
|
||||
>
|
||||
{item.label}
|
||||
</Link>
|
||||
) : (
|
||||
<span className={isLast ? "text-foreground font-medium" : ""}>
|
||||
{item.label}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
60
src/components/db-check.tsx
Normal file
60
src/components/db-check.tsx
Normal file
@@ -0,0 +1,60 @@
|
||||
'use server'
|
||||
|
||||
import { db } from "~/server/db"
|
||||
import { users } from "~/server/db/schema"
|
||||
import { Card } from "~/components/ui/card"
|
||||
import { DatabaseIcon } from "lucide-react"
|
||||
import { Logo } from "~/components/logo"
|
||||
|
||||
async function checkDatabase() {
|
||||
try {
|
||||
// Try a simple query to check database connection
|
||||
await db.select().from(users).limit(1)
|
||||
return true
|
||||
} catch (error) {
|
||||
console.error("Database connection error:", error)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export default async function DatabaseCheck({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode
|
||||
}): Promise<JSX.Element> {
|
||||
const isConnected = await checkDatabase()
|
||||
|
||||
if (isConnected) {
|
||||
return <>{children}</>
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="grid min-h-screen place-items-center bg-background font-sans antialiased">
|
||||
<div className="flex flex-col items-center gap-8">
|
||||
<Logo
|
||||
className="text-2xl"
|
||||
iconClassName="h-8 w-8"
|
||||
/>
|
||||
<Card className="w-[448px] border-destructive p-6">
|
||||
<div className="flex flex-col items-center gap-4 text-center">
|
||||
<DatabaseIcon className="h-12 w-12 text-destructive" />
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-2xl font-bold tracking-tight">
|
||||
Database Connection Error
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Could not connect to the database. Please make sure the database is running and try again.
|
||||
</p>
|
||||
</div>
|
||||
<div className="w-full rounded-lg bg-muted p-4">
|
||||
<p className="mb-2 font-mono text-sm">Start the database with:</p>
|
||||
<code className="block rounded bg-background p-2 text-sm">
|
||||
docker-compose up -d
|
||||
</code>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
20
src/components/experiment-builder.tsx
Normal file
20
src/components/experiment-builder.tsx
Normal file
@@ -0,0 +1,20 @@
|
||||
export function ExperimentBuilder() {
|
||||
return (
|
||||
<DndContext>
|
||||
<SortableContext items={steps}>
|
||||
<div className="space-y-4">
|
||||
{steps.map((step) => (
|
||||
<ExperimentStep
|
||||
key={step.id}
|
||||
step={step}
|
||||
actions={actionsMap[step.id]}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</SortableContext>
|
||||
<DragOverlay>
|
||||
{activeStep && <StepPreview step={activeStep} />}
|
||||
</DragOverlay>
|
||||
</DndContext>
|
||||
)
|
||||
}
|
||||
@@ -1,157 +0,0 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "~/components/ui/dialog";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { Input } from "~/components/ui/input";
|
||||
import { Label } from "~/components/ui/label";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "~/components/ui/select";
|
||||
import { ROLES } from "~/lib/roles";
|
||||
import { UserPlusIcon } from "lucide-react";
|
||||
|
||||
interface Role {
|
||||
id: number;
|
||||
name: string;
|
||||
}
|
||||
|
||||
interface InviteUserDialogProps {
|
||||
studyId: number;
|
||||
onInviteSent?: () => void;
|
||||
}
|
||||
|
||||
export function InviteUserDialog({ studyId, onInviteSent }: InviteUserDialogProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [email, setEmail] = useState("");
|
||||
const [roleId, setRoleId] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [roles, setRoles] = useState<Role[]>([]);
|
||||
const router = useRouter();
|
||||
|
||||
useEffect(() => {
|
||||
// Fetch available roles when dialog opens
|
||||
if (open) {
|
||||
fetchRoles();
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
const fetchRoles = async () => {
|
||||
try {
|
||||
const response = await fetch("/api/roles");
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
setRoles(data.filter((role: Role) =>
|
||||
role.name !== ROLES.ADMIN && role.name !== ROLES.PRINCIPAL_INVESTIGATOR
|
||||
));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error fetching roles:", error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/invitations", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
email,
|
||||
studyId,
|
||||
roleId: parseInt(roleId),
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to send invitation");
|
||||
}
|
||||
|
||||
setOpen(false);
|
||||
setEmail("");
|
||||
setRoleId("");
|
||||
onInviteSent?.();
|
||||
router.refresh();
|
||||
} catch (error) {
|
||||
console.error("Error sending invitation:", error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button>
|
||||
<UserPlusIcon className="w-4 h-4 mr-2" />
|
||||
Invite User
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Invite User</DialogTitle>
|
||||
<DialogDescription>
|
||||
Send an invitation to join your study. The user will receive an email with instructions.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="space-y-4 py-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">Email Address</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
placeholder="researcher@university.edu"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="role">Role</Label>
|
||||
<Select
|
||||
value={roleId}
|
||||
onValueChange={setRoleId}
|
||||
required
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select a role" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{roles.map((role) => (
|
||||
<SelectItem key={role.id} value={role.id.toString()}>
|
||||
{role.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? "Sending..." : "Send Invitation"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
|
||||
25
src/components/layout/page-content.tsx
Normal file
25
src/components/layout/page-content.tsx
Normal file
@@ -0,0 +1,25 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "~/lib/utils"
|
||||
|
||||
interface PageContentProps
|
||||
extends React.HTMLAttributes<HTMLDivElement> {
|
||||
children: React.ReactNode
|
||||
}
|
||||
|
||||
export function PageContent({
|
||||
children,
|
||||
className,
|
||||
...props
|
||||
}: PageContentProps) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"grid gap-6",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
34
src/components/layout/page-header.tsx
Normal file
34
src/components/layout/page-header.tsx
Normal file
@@ -0,0 +1,34 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "~/lib/utils"
|
||||
|
||||
interface PageHeaderProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
title: string
|
||||
description?: string
|
||||
children?: React.ReactNode
|
||||
}
|
||||
|
||||
export function PageHeader({
|
||||
title,
|
||||
description,
|
||||
children,
|
||||
className,
|
||||
...props
|
||||
}: PageHeaderProps) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center justify-between gap-4 pb-6",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div className="grid gap-1">
|
||||
<h1 className="text-2xl font-semibold tracking-tight">{title}</h1>
|
||||
{description && (
|
||||
<p className="text-sm text-muted-foreground">{description}</p>
|
||||
)}
|
||||
</div>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
25
src/components/layout/page-transition.tsx
Normal file
25
src/components/layout/page-transition.tsx
Normal file
@@ -0,0 +1,25 @@
|
||||
"use client"
|
||||
|
||||
import { motion, AnimatePresence } from "framer-motion"
|
||||
import { usePathname } from "next/navigation"
|
||||
|
||||
export function PageTransition({ children }: { children: React.ReactNode }) {
|
||||
const pathname = usePathname()
|
||||
|
||||
return (
|
||||
<AnimatePresence mode="wait">
|
||||
<motion.div
|
||||
key={pathname}
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{
|
||||
duration: 0.15,
|
||||
ease: "easeOut",
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</motion.div>
|
||||
</AnimatePresence>
|
||||
)
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { BotIcon } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { BotIcon } from "lucide-react"
|
||||
import Link from "next/link"
|
||||
import { cn } from "~/lib/utils"
|
||||
|
||||
interface LogoProps {
|
||||
href?: string;
|
||||
className?: string;
|
||||
iconClassName?: string;
|
||||
textClassName?: string;
|
||||
href?: string
|
||||
className?: string
|
||||
iconClassName?: string
|
||||
textClassName?: string
|
||||
}
|
||||
|
||||
export function Logo({
|
||||
@@ -32,5 +32,5 @@ export function Logo({
|
||||
<span className="font-normal">Studio</span>
|
||||
</span>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
)
|
||||
}
|
||||
92
src/components/navigation/app-sidebar.tsx
Normal file
92
src/components/navigation/app-sidebar.tsx
Normal file
@@ -0,0 +1,92 @@
|
||||
"use client"
|
||||
|
||||
import {
|
||||
Beaker,
|
||||
Home,
|
||||
Settings2,
|
||||
User
|
||||
} from "lucide-react"
|
||||
import * as React from "react"
|
||||
import { useSession } from "next-auth/react"
|
||||
|
||||
import { StudySwitcher } from "~/components/auth/study-switcher"
|
||||
import {
|
||||
Sidebar,
|
||||
SidebarContent,
|
||||
SidebarFooter,
|
||||
SidebarHeader,
|
||||
SidebarRail,
|
||||
} from "~/components/ui/sidebar"
|
||||
import { NavMain } from "~/components/navigation/nav-main"
|
||||
import { NavUser } from "~/components/navigation/nav-user"
|
||||
|
||||
const data = {
|
||||
navMain: [
|
||||
{
|
||||
title: "Overview",
|
||||
url: "/dashboard",
|
||||
icon: Home,
|
||||
isActive: true,
|
||||
},
|
||||
{
|
||||
title: "Studies",
|
||||
url: "/dashboard/studies",
|
||||
icon: Beaker,
|
||||
items: [
|
||||
{
|
||||
title: "All Studies",
|
||||
url: "/dashboard/studies",
|
||||
},
|
||||
{
|
||||
title: "Create Study",
|
||||
url: "/dashboard/studies/new",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Settings",
|
||||
url: "/dashboard/settings",
|
||||
icon: Settings2,
|
||||
items: [
|
||||
{
|
||||
title: "Account",
|
||||
url: "/dashboard/account",
|
||||
icon: User,
|
||||
},
|
||||
{
|
||||
title: "Team",
|
||||
url: "/dashboard/settings/team",
|
||||
},
|
||||
{
|
||||
title: "Billing",
|
||||
url: "/dashboard/settings/billing",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
|
||||
const { data: session } = useSession()
|
||||
if (!session) return null
|
||||
|
||||
return (
|
||||
<Sidebar
|
||||
collapsible="icon"
|
||||
variant="floating"
|
||||
className="border-none"
|
||||
{...props}
|
||||
>
|
||||
<SidebarHeader>
|
||||
<StudySwitcher />
|
||||
</SidebarHeader>
|
||||
<SidebarContent>
|
||||
<NavMain items={data.navMain} />
|
||||
</SidebarContent>
|
||||
<SidebarFooter>
|
||||
<NavUser />
|
||||
</SidebarFooter>
|
||||
<SidebarRail />
|
||||
</Sidebar>
|
||||
)
|
||||
}
|
||||
64
src/components/navigation/breadcrumb-nav.tsx
Normal file
64
src/components/navigation/breadcrumb-nav.tsx
Normal file
@@ -0,0 +1,64 @@
|
||||
"use client"
|
||||
|
||||
import { usePathname } from "next/navigation"
|
||||
import Link from "next/link"
|
||||
|
||||
export function BreadcrumbNav() {
|
||||
const pathname = usePathname()
|
||||
|
||||
// Get breadcrumb items based on pathname
|
||||
const getBreadcrumbs = () => {
|
||||
const paths = pathname.split("/").filter(Boolean)
|
||||
const items = []
|
||||
|
||||
if (paths[0] === "dashboard") {
|
||||
items.push({
|
||||
label: "Dashboard",
|
||||
href: "/dashboard",
|
||||
current: paths.length === 1,
|
||||
})
|
||||
}
|
||||
|
||||
if (paths[1] === "studies") {
|
||||
items.push({
|
||||
label: "Studies",
|
||||
href: "/dashboard/studies",
|
||||
current: paths.length === 2,
|
||||
})
|
||||
|
||||
if (paths[2] === "new") {
|
||||
items.push({
|
||||
label: "Create Study",
|
||||
current: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return items
|
||||
}
|
||||
|
||||
const breadcrumbs = getBreadcrumbs()
|
||||
|
||||
return (
|
||||
<nav aria-label="breadcrumb">
|
||||
<ol className="flex items-center gap-2">
|
||||
{breadcrumbs.map((item, index) => (
|
||||
<li key={item.label} className="flex items-center">
|
||||
{index > 0 && (
|
||||
<span role="presentation" aria-hidden="true" className="mx-2 text-muted-foreground">
|
||||
/
|
||||
</span>
|
||||
)}
|
||||
{item.current ? (
|
||||
<span className="font-medium">{item.label}</span>
|
||||
) : (
|
||||
<Link href={item.href} className="text-muted-foreground hover:text-foreground">
|
||||
{item.label}
|
||||
</Link>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</nav>
|
||||
)
|
||||
}
|
||||
25
src/components/navigation/header.tsx
Normal file
25
src/components/navigation/header.tsx
Normal file
@@ -0,0 +1,25 @@
|
||||
"use client"
|
||||
|
||||
import { Separator } from "~/components/ui/separator"
|
||||
import { SidebarTrigger } from "~/components/ui/sidebar"
|
||||
import { BreadcrumbNav } from "./breadcrumb-nav"
|
||||
import { Logo } from "~/components/logo"
|
||||
|
||||
export function Header() {
|
||||
return (
|
||||
<div className="sticky top-0 z-40 w-full">
|
||||
<header className="mx-2 mt-2 flex h-14 items-center justify-between rounded-lg border bg-gradient-to-r from-[hsl(var(--sidebar-gradient-from))] to-[hsl(var(--sidebar-gradient-to))] px-6 shadow-sm md:ml-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<SidebarTrigger className="-ml-2 text-[hsl(var(--sidebar-text))] hover:bg-[hsl(var(--sidebar-text))]/10" />
|
||||
<Separator orientation="vertical" className="h-4 bg-[hsl(var(--sidebar-text))]/10" />
|
||||
<BreadcrumbNav />
|
||||
</div>
|
||||
<Logo
|
||||
href="/dashboard"
|
||||
className="text-[hsl(var(--sidebar-text))]"
|
||||
iconClassName="text-[hsl(var(--sidebar-text-muted))]"
|
||||
/>
|
||||
</header>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
73
src/components/navigation/nav-main.tsx
Normal file
73
src/components/navigation/nav-main.tsx
Normal file
@@ -0,0 +1,73 @@
|
||||
"use client"
|
||||
|
||||
import { ChevronRight, type LucideIcon } from "lucide-react"
|
||||
|
||||
import {
|
||||
Collapsible,
|
||||
CollapsibleContent,
|
||||
CollapsibleTrigger,
|
||||
} from "~/components/ui/collapsible"
|
||||
import {
|
||||
SidebarGroup,
|
||||
SidebarGroupLabel,
|
||||
SidebarMenu,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
SidebarMenuSub,
|
||||
SidebarMenuSubButton,
|
||||
SidebarMenuSubItem,
|
||||
} from "~/components/ui/sidebar"
|
||||
|
||||
export function NavMain({
|
||||
items,
|
||||
}: {
|
||||
items: {
|
||||
title: string
|
||||
url: string
|
||||
icon?: LucideIcon
|
||||
isActive?: boolean
|
||||
items?: {
|
||||
title: string
|
||||
url: string
|
||||
}[]
|
||||
}[]
|
||||
}) {
|
||||
return (
|
||||
<SidebarGroup>
|
||||
<SidebarGroupLabel>Platform</SidebarGroupLabel>
|
||||
<SidebarMenu>
|
||||
{items.map((item) => (
|
||||
<Collapsible
|
||||
key={item.title}
|
||||
asChild
|
||||
defaultOpen={item.isActive}
|
||||
className="group/collapsible"
|
||||
>
|
||||
<SidebarMenuItem>
|
||||
<CollapsibleTrigger asChild>
|
||||
<SidebarMenuButton tooltip={item.title}>
|
||||
{item.icon && <item.icon />}
|
||||
<span>{item.title}</span>
|
||||
<ChevronRight className="ml-auto transition-transform duration-200 group-data-[state=open]/collapsible:rotate-90" />
|
||||
</SidebarMenuButton>
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent>
|
||||
<SidebarMenuSub>
|
||||
{item.items?.map((subItem) => (
|
||||
<SidebarMenuSubItem key={subItem.title}>
|
||||
<SidebarMenuSubButton asChild>
|
||||
<a href={subItem.url}>
|
||||
<span>{subItem.title}</span>
|
||||
</a>
|
||||
</SidebarMenuSubButton>
|
||||
</SidebarMenuSubItem>
|
||||
))}
|
||||
</SidebarMenuSub>
|
||||
</CollapsibleContent>
|
||||
</SidebarMenuItem>
|
||||
</Collapsible>
|
||||
))}
|
||||
</SidebarMenu>
|
||||
</SidebarGroup>
|
||||
)
|
||||
}
|
||||
89
src/components/navigation/nav-projects.tsx
Normal file
89
src/components/navigation/nav-projects.tsx
Normal file
@@ -0,0 +1,89 @@
|
||||
"use client"
|
||||
|
||||
import {
|
||||
Folder,
|
||||
Forward,
|
||||
MoreHorizontal,
|
||||
Trash2,
|
||||
type LucideIcon,
|
||||
} from "lucide-react"
|
||||
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "~/components/ui/dropdown-menu"
|
||||
import {
|
||||
SidebarGroup,
|
||||
SidebarGroupLabel,
|
||||
SidebarMenu,
|
||||
SidebarMenuAction,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
useSidebar,
|
||||
} from "~/components/ui/sidebar"
|
||||
|
||||
export function NavProjects({
|
||||
projects,
|
||||
}: {
|
||||
projects: {
|
||||
name: string
|
||||
url: string
|
||||
icon: LucideIcon
|
||||
}[]
|
||||
}) {
|
||||
const { isMobile } = useSidebar()
|
||||
|
||||
return (
|
||||
<SidebarGroup className="group-data-[collapsible=icon]:hidden">
|
||||
<SidebarGroupLabel>Projects</SidebarGroupLabel>
|
||||
<SidebarMenu>
|
||||
{projects.map((item) => (
|
||||
<SidebarMenuItem key={item.name}>
|
||||
<SidebarMenuButton asChild>
|
||||
<a href={item.url}>
|
||||
<item.icon />
|
||||
<span>{item.name}</span>
|
||||
</a>
|
||||
</SidebarMenuButton>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<SidebarMenuAction showOnHover>
|
||||
<MoreHorizontal />
|
||||
<span className="sr-only">More</span>
|
||||
</SidebarMenuAction>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent
|
||||
className="w-48 rounded-lg"
|
||||
side={isMobile ? "bottom" : "right"}
|
||||
align={isMobile ? "end" : "start"}
|
||||
>
|
||||
<DropdownMenuItem>
|
||||
<Folder className="text-muted-foreground" />
|
||||
<span>View Project</span>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem>
|
||||
<Forward className="text-muted-foreground" />
|
||||
<span>Share Project</span>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem>
|
||||
<Trash2 className="text-muted-foreground" />
|
||||
<span>Delete Project</span>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</SidebarMenuItem>
|
||||
))}
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton className="text-sidebar-foreground/70">
|
||||
<MoreHorizontal className="text-sidebar-foreground/70" />
|
||||
<span>More</span>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenu>
|
||||
</SidebarGroup>
|
||||
)
|
||||
}
|
||||
89
src/components/navigation/nav-studies.tsx
Normal file
89
src/components/navigation/nav-studies.tsx
Normal file
@@ -0,0 +1,89 @@
|
||||
"use client"
|
||||
|
||||
import {
|
||||
Folder,
|
||||
Forward,
|
||||
MoreHorizontal,
|
||||
Trash2,
|
||||
type LucideIcon,
|
||||
} from "lucide-react"
|
||||
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "~/components/ui/dropdown-menu"
|
||||
import {
|
||||
SidebarGroup,
|
||||
SidebarGroupLabel,
|
||||
SidebarMenu,
|
||||
SidebarMenuAction,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
useSidebar,
|
||||
} from "~/components/ui/sidebar"
|
||||
|
||||
export function NavStudies({
|
||||
studies,
|
||||
}: {
|
||||
studies: {
|
||||
name: string
|
||||
url: string
|
||||
icon: LucideIcon
|
||||
}[]
|
||||
}) {
|
||||
const { isMobile } = useSidebar()
|
||||
|
||||
return (
|
||||
<SidebarGroup className="group-data-[collapsible=icon]:hidden">
|
||||
<SidebarGroupLabel>Active Studies</SidebarGroupLabel>
|
||||
<SidebarMenu>
|
||||
{studies.map((study) => (
|
||||
<SidebarMenuItem key={study.name}>
|
||||
<SidebarMenuButton asChild>
|
||||
<a href={study.url}>
|
||||
<study.icon />
|
||||
<span>{study.name}</span>
|
||||
</a>
|
||||
</SidebarMenuButton>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<SidebarMenuAction showOnHover>
|
||||
<MoreHorizontal />
|
||||
<span className="sr-only">More</span>
|
||||
</SidebarMenuAction>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent
|
||||
className="w-48 rounded-lg"
|
||||
side={isMobile ? "bottom" : "right"}
|
||||
align={isMobile ? "end" : "start"}
|
||||
>
|
||||
<DropdownMenuItem>
|
||||
<Folder className="text-muted-foreground" />
|
||||
<span>View Study</span>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem>
|
||||
<Forward className="text-muted-foreground" />
|
||||
<span>Share Study</span>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem>
|
||||
<Trash2 className="text-muted-foreground" />
|
||||
<span>Archive Study</span>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</SidebarMenuItem>
|
||||
))}
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton className="text-sidebar-foreground/70">
|
||||
<MoreHorizontal className="text-sidebar-foreground/70" />
|
||||
<span>View All Studies</span>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenu>
|
||||
</SidebarGroup>
|
||||
)
|
||||
}
|
||||
152
src/components/navigation/nav-user.tsx
Normal file
152
src/components/navigation/nav-user.tsx
Normal file
@@ -0,0 +1,152 @@
|
||||
"use client"
|
||||
|
||||
import { ChevronsUpDown, LogOut, Settings, User } from "lucide-react"
|
||||
import { useSession } from "next-auth/react"
|
||||
import Link from "next/link"
|
||||
import Image from "next/image"
|
||||
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuGroup,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "~/components/ui/dropdown-menu"
|
||||
import {
|
||||
SidebarMenu,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
} from "~/components/ui/sidebar"
|
||||
import { Avatar, AvatarFallback } from "~/components/ui/avatar"
|
||||
|
||||
export function NavUser() {
|
||||
const { data: session, status } = useSession()
|
||||
|
||||
if (status === "loading") {
|
||||
return (
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton
|
||||
size="lg"
|
||||
className="animate-pulse"
|
||||
>
|
||||
<div className="flex aspect-square size-8 items-center justify-center rounded-lg bg-sidebar-accent/10">
|
||||
<User className="size-4 text-muted-foreground/50" />
|
||||
</div>
|
||||
<div className="grid flex-1 gap-1">
|
||||
<div className="h-4 w-24 rounded bg-sidebar-accent/10" />
|
||||
<div className="h-3 w-16 rounded bg-sidebar-accent/10" />
|
||||
</div>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenu>
|
||||
)
|
||||
}
|
||||
|
||||
if (!session?.user) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<SidebarMenuButton
|
||||
size="lg"
|
||||
className="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground"
|
||||
>
|
||||
<Avatar className="size-8 rounded-lg">
|
||||
{session.user.image ? (
|
||||
<div className="relative size-full overflow-hidden rounded-lg">
|
||||
<Image
|
||||
src={session.user.image}
|
||||
alt={session.user.name ?? "User"}
|
||||
fill
|
||||
sizes="32px"
|
||||
className="object-cover"
|
||||
onError={(e) => {
|
||||
console.error("Error loading nav avatar:", session.user.image);
|
||||
e.currentTarget.style.display = "none";
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<AvatarFallback className="rounded-lg bg-sidebar-muted">
|
||||
<User className="size-4" />
|
||||
</AvatarFallback>
|
||||
)}
|
||||
</Avatar>
|
||||
<div className="grid flex-1 text-left text-sm leading-tight">
|
||||
<span className="truncate font-semibold">
|
||||
{session.user.name ?? "User"}
|
||||
</span>
|
||||
<span className="truncate text-xs text-sidebar-muted">
|
||||
{session.user.email}
|
||||
</span>
|
||||
</div>
|
||||
<ChevronsUpDown className="ml-auto size-4" />
|
||||
</SidebarMenuButton>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent
|
||||
className="w-[--radix-dropdown-menu-trigger-width] min-w-56 rounded-lg"
|
||||
align="end"
|
||||
sideOffset={4}
|
||||
>
|
||||
<DropdownMenuLabel className="font-normal">
|
||||
<div className="flex items-center gap-2 px-1 py-1.5">
|
||||
<Avatar className="size-8 rounded-lg">
|
||||
{session.user.image ? (
|
||||
<div className="relative size-full overflow-hidden rounded-lg">
|
||||
<Image
|
||||
src={session.user.image}
|
||||
alt={session.user.name ?? "User"}
|
||||
fill
|
||||
sizes="32px"
|
||||
className="object-cover"
|
||||
onError={(e) => {
|
||||
console.error("Error loading dropdown avatar:", session.user.image);
|
||||
e.currentTarget.style.display = "none";
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<AvatarFallback className="rounded-lg">
|
||||
<User className="size-4" />
|
||||
</AvatarFallback>
|
||||
)}
|
||||
</Avatar>
|
||||
<div className="grid flex-1 text-left text-sm leading-tight">
|
||||
<span className="font-semibold">
|
||||
{session.user.name ?? "User"}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{session.user.email}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuGroup>
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href="/dashboard/account">
|
||||
<Settings className="mr-2 size-4" />
|
||||
Settings
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuGroup>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href="/api/auth/signout">
|
||||
<LogOut className="mr-2 size-4" />
|
||||
Sign out
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenu>
|
||||
)
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
|
||||
interface PageHeaderProps {
|
||||
title: string;
|
||||
description: string;
|
||||
children?: React.ReactNode;
|
||||
}
|
||||
|
||||
export function PageHeader({ title, description, children }: PageHeaderProps) {
|
||||
return (
|
||||
<div className="mb-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold tracking-tight">{title}</h1>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
{description}
|
||||
</p>
|
||||
</div>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
11
src/components/providers.tsx
Normal file
11
src/components/providers.tsx
Normal file
@@ -0,0 +1,11 @@
|
||||
"use client"
|
||||
|
||||
import { SessionProvider } from "next-auth/react"
|
||||
|
||||
export function Providers({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<SessionProvider>
|
||||
{children}
|
||||
</SessionProvider>
|
||||
)
|
||||
}
|
||||
89
src/components/providers/study-provider.tsx
Normal file
89
src/components/providers/study-provider.tsx
Normal file
@@ -0,0 +1,89 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { api } from "~/trpc/react"
|
||||
|
||||
interface Study {
|
||||
id: number
|
||||
title: string
|
||||
description: string | null
|
||||
role: string
|
||||
}
|
||||
|
||||
interface StudyContextType {
|
||||
studies: Study[]
|
||||
activeStudy: Study | null
|
||||
setActiveStudy: (study: Study | null) => void
|
||||
isLoading: boolean
|
||||
}
|
||||
|
||||
const StudyContext = React.createContext<StudyContextType | undefined>(undefined)
|
||||
|
||||
const STORAGE_KEY = "activeStudyId"
|
||||
|
||||
function getStoredStudyId(): number | null {
|
||||
if (typeof window === "undefined") return null
|
||||
const stored = localStorage.getItem(STORAGE_KEY)
|
||||
return stored ? Number(stored) : null
|
||||
}
|
||||
|
||||
export function StudyProvider({ children }: { children: React.ReactNode }) {
|
||||
// Initialize with stored study ID
|
||||
const [activeStudyId, setActiveStudyId] = React.useState<number | null>(() => getStoredStudyId())
|
||||
|
||||
const { data: studies = [], isLoading } = api.study.getMyStudies.useQuery()
|
||||
|
||||
// Find the active study from the studies array
|
||||
const activeStudy = React.useMemo(() => {
|
||||
if (!studies.length || !activeStudyId) return null
|
||||
return studies.find(s => s.id === activeStudyId) ?? studies[0]
|
||||
}, [studies, activeStudyId])
|
||||
|
||||
// Update active study ID when studies load
|
||||
React.useEffect(() => {
|
||||
if (!studies.length) return;
|
||||
|
||||
if (!activeStudyId || !studies.find(s => s.id === activeStudyId)) {
|
||||
// If no active study or it doesn't exist in the list, set the first study
|
||||
const id = studies[0]?.id;
|
||||
if (id) {
|
||||
setActiveStudyId(id);
|
||||
localStorage.setItem(STORAGE_KEY, String(id));
|
||||
}
|
||||
}
|
||||
}, [studies, activeStudyId]);
|
||||
|
||||
const setActiveStudy = React.useCallback((study: Study | null) => {
|
||||
if (study) {
|
||||
setActiveStudyId(study.id)
|
||||
localStorage.setItem(STORAGE_KEY, String(study.id))
|
||||
} else {
|
||||
setActiveStudyId(null)
|
||||
localStorage.removeItem(STORAGE_KEY)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const value = React.useMemo(
|
||||
() => ({
|
||||
studies,
|
||||
activeStudy: activeStudy ?? null,
|
||||
setActiveStudy,
|
||||
isLoading,
|
||||
}),
|
||||
[studies, activeStudy, setActiveStudy, isLoading]
|
||||
)
|
||||
|
||||
return (
|
||||
<StudyContext.Provider value={value}>
|
||||
{children}
|
||||
</StudyContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export function useStudy() {
|
||||
const context = React.useContext(StudyContext)
|
||||
if (context === undefined) {
|
||||
throw new Error("useStudy must be used within a StudyProvider")
|
||||
}
|
||||
return context
|
||||
}
|
||||
@@ -1,254 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { UserButton, useUser } from "@clerk/nextjs"
|
||||
import {
|
||||
BarChartIcon,
|
||||
UsersRoundIcon,
|
||||
LandPlotIcon,
|
||||
FileTextIcon,
|
||||
LayoutDashboard,
|
||||
Menu,
|
||||
Settings,
|
||||
ChevronDown,
|
||||
FolderIcon,
|
||||
PlusIcon
|
||||
} from "lucide-react"
|
||||
import Link from "next/link"
|
||||
import { usePathname, useRouter } from "next/navigation"
|
||||
import { useState } from "react"
|
||||
import { Button } from "~/components/ui/button"
|
||||
import { Sheet, SheetContent, SheetTrigger, SheetTitle } from "~/components/ui/sheet"
|
||||
import { cn } from "~/lib/utils"
|
||||
import { Logo } from "~/components/logo"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "~/components/ui/select"
|
||||
import { Separator } from "~/components/ui/separator"
|
||||
import { useActiveStudy } from "~/context/active-study"
|
||||
|
||||
const getNavItems = (studyId?: number) => [
|
||||
{
|
||||
name: "Dashboard",
|
||||
href: studyId ? `/dashboard/studies/${studyId}` : "/dashboard",
|
||||
icon: LayoutDashboard,
|
||||
exact: true,
|
||||
requiresStudy: false
|
||||
},
|
||||
{
|
||||
name: "Studies",
|
||||
href: "/dashboard/studies",
|
||||
icon: FolderIcon,
|
||||
exact: true,
|
||||
requiresStudy: false,
|
||||
hideWithStudy: true
|
||||
},
|
||||
{
|
||||
name: "Participants",
|
||||
href: `/dashboard/studies/${studyId}/participants`,
|
||||
icon: UsersRoundIcon,
|
||||
requiresStudy: true,
|
||||
baseRoute: "participants"
|
||||
},
|
||||
{
|
||||
name: "Trials",
|
||||
href: `/dashboard/studies/${studyId}/trials`,
|
||||
icon: LandPlotIcon,
|
||||
requiresStudy: true,
|
||||
baseRoute: "trials"
|
||||
},
|
||||
{
|
||||
name: "Forms",
|
||||
href: `/dashboard/studies/${studyId}/forms`,
|
||||
icon: FileTextIcon,
|
||||
requiresStudy: true,
|
||||
baseRoute: "forms"
|
||||
},
|
||||
{
|
||||
name: "Data Analysis",
|
||||
href: `/dashboard/studies/${studyId}/analysis`,
|
||||
icon: BarChartIcon,
|
||||
requiresStudy: true,
|
||||
baseRoute: "analysis"
|
||||
},
|
||||
{
|
||||
name: "Settings",
|
||||
href: `/dashboard/studies/${studyId}/settings`,
|
||||
icon: Settings,
|
||||
requiresStudy: true,
|
||||
baseRoute: "settings"
|
||||
},
|
||||
];
|
||||
|
||||
export function Sidebar() {
|
||||
const pathname = usePathname()
|
||||
const router = useRouter()
|
||||
const [isOpen, setIsOpen] = useState(false)
|
||||
const { user } = useUser()
|
||||
const { activeStudy, setActiveStudy, studies, isLoading } = useActiveStudy()
|
||||
|
||||
const navItems = getNavItems(activeStudy?.id)
|
||||
const visibleNavItems = activeStudy
|
||||
? navItems.filter(item => !item.hideWithStudy)
|
||||
: navItems.filter(item => !item.requiresStudy)
|
||||
|
||||
const isActiveRoute = (item: { href: string, exact?: boolean, baseRoute?: string }) => {
|
||||
if (item.exact) {
|
||||
return pathname === item.href;
|
||||
}
|
||||
if (item.baseRoute && activeStudy) {
|
||||
const pattern = new RegExp(`/dashboard/studies/\\d+/${item.baseRoute}`);
|
||||
return pattern.test(pathname);
|
||||
}
|
||||
return pathname.startsWith(item.href);
|
||||
};
|
||||
|
||||
const handleStudyChange = (value: string) => {
|
||||
if (value === "all") {
|
||||
setActiveStudy(null);
|
||||
router.push("/dashboard");
|
||||
} else {
|
||||
const study = studies.find(s => s.id.toString() === value);
|
||||
if (study) {
|
||||
setActiveStudy(study);
|
||||
router.push(`/dashboard/studies/${study.id}`);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const SidebarContent = () => (
|
||||
<div className="flex h-full flex-col">
|
||||
<div className="p-4">
|
||||
<Select
|
||||
value={activeStudy?.id?.toString() || "all"}
|
||||
onValueChange={handleStudyChange}
|
||||
>
|
||||
<SelectTrigger className="w-full sidebar-button">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="truncate">
|
||||
{activeStudy?.title || "All Studies"}
|
||||
</span>
|
||||
</div>
|
||||
</SelectTrigger>
|
||||
<SelectContent className="sidebar-dropdown-content">
|
||||
<SelectItem value="all" className="sidebar-button">
|
||||
<div className="flex items-center">
|
||||
<FolderIcon className="h-4 w-4 mr-2" />
|
||||
All Studies
|
||||
</div>
|
||||
</SelectItem>
|
||||
<Separator className="sidebar-separator" />
|
||||
{studies.map((study) => (
|
||||
<SelectItem
|
||||
key={study.id}
|
||||
value={study.id.toString()}
|
||||
className="sidebar-button"
|
||||
>
|
||||
{study.title}
|
||||
</SelectItem>
|
||||
))}
|
||||
<Separator className="sidebar-separator" />
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="w-full justify-start sidebar-button"
|
||||
asChild
|
||||
>
|
||||
<Link href="/dashboard/studies/new">
|
||||
<PlusIcon className="h-4 w-4 mr-2" />
|
||||
Create New Study
|
||||
</Link>
|
||||
</Button>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<nav className="flex-1 overflow-y-auto p-4">
|
||||
<ul className="space-y-2">
|
||||
{visibleNavItems.map((item) => {
|
||||
const IconComponent = item.icon;
|
||||
const isActive = isActiveRoute(item);
|
||||
|
||||
return (
|
||||
<li key={item.href}>
|
||||
<Button
|
||||
asChild
|
||||
variant="ghost"
|
||||
className="w-full justify-start sidebar-button"
|
||||
data-active={isActive}
|
||||
>
|
||||
<Link href={item.href} onClick={() => setIsOpen(false)}>
|
||||
<IconComponent className="h-5 w-5 mr-3" />
|
||||
<span>{item.name}</span>
|
||||
</Link>
|
||||
</Button>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</nav>
|
||||
|
||||
<div className="p-4">
|
||||
<div className="border-t border-[hsl(var(--sidebar-separator))]">
|
||||
<div className="flex items-center justify-between pt-4">
|
||||
<div className="flex items-center space-x-4">
|
||||
<div className="w-8 h-8">
|
||||
<UserButton afterSignOutUrl="/" />
|
||||
</div>
|
||||
{user && (
|
||||
<div className="min-w-0">
|
||||
<p className="text-sm font-medium text-[hsl(var(--sidebar-foreground))] truncate">
|
||||
{user.fullName ?? user.username ?? 'User'}
|
||||
</p>
|
||||
<p className="text-xs text-[hsl(var(--sidebar-muted))] truncate">
|
||||
{user.primaryEmailAddress?.emailAddress ?? 'user@example.com'}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="lg:hidden fixed top-0 left-0 right-0 z-50">
|
||||
<div className="flex h-14 items-center justify-between border-b border-[hsl(var(--sidebar-border))]">
|
||||
<Logo
|
||||
href="/dashboard"
|
||||
className="text-[hsl(var(--sidebar-foreground))]"
|
||||
iconClassName="text-[hsl(var(--sidebar-muted))]"
|
||||
/>
|
||||
<Sheet open={isOpen} onOpenChange={setIsOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<Button variant="ghost" className="h-14 w-14 px-0 sidebar-button">
|
||||
<Menu className="h-6 w-6" />
|
||||
</Button>
|
||||
</SheetTrigger>
|
||||
<SheetContent
|
||||
side="left"
|
||||
className="w-full p-0 border-[hsl(var(--sidebar-border))]"
|
||||
>
|
||||
<SheetTitle className="sr-only">Navigation Menu</SheetTitle>
|
||||
<SidebarContent />
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</div>
|
||||
</div>
|
||||
<div className="hidden lg:flex lg:w-64 lg:flex-col lg:border-r lg:border-[hsl(var(--sidebar-border))]">
|
||||
<div className="flex h-14 items-center border-b border-[hsl(var(--sidebar-border))] px-4">
|
||||
<Logo
|
||||
href="/dashboard"
|
||||
className="text-[hsl(var(--sidebar-foreground))]"
|
||||
iconClassName="text-[hsl(var(--sidebar-muted))]"
|
||||
/>
|
||||
</div>
|
||||
<SidebarContent />
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -1,137 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "~/components/ui/card";
|
||||
import { useToast } from "~/hooks/use-toast";
|
||||
import { PERMISSIONS } from "~/lib/permissions-client";
|
||||
import { InviteUserDialog } from "./invite-user-dialog";
|
||||
|
||||
interface Invitation {
|
||||
id: string;
|
||||
email: string;
|
||||
roleName: string;
|
||||
accepted: boolean;
|
||||
expiresAt: string;
|
||||
}
|
||||
|
||||
interface InvitationsTabProps {
|
||||
studyId: number;
|
||||
permissions: string[];
|
||||
}
|
||||
|
||||
export function InvitationsTab({ studyId, permissions }: InvitationsTabProps) {
|
||||
const [invitations, setInvitations] = useState<Invitation[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const { toast } = useToast();
|
||||
|
||||
const hasPermission = (permission: string) => permissions.includes(permission);
|
||||
const canManageRoles = hasPermission(PERMISSIONS.MANAGE_ROLES);
|
||||
|
||||
const fetchInvitations = useCallback(async () => {
|
||||
try {
|
||||
const response = await fetch(`/api/invitations?studyId=${studyId}`);
|
||||
if (!response.ok) throw new Error("Failed to fetch invitations");
|
||||
const data = await response.json();
|
||||
setInvitations(data.data || []);
|
||||
} catch (error) {
|
||||
console.error("Error fetching invitations:", error);
|
||||
toast({
|
||||
title: "Error",
|
||||
description: "Failed to load invitations",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [studyId, toast]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchInvitations();
|
||||
}, [fetchInvitations]);
|
||||
|
||||
|
||||
const handleDeleteInvitation = async (invitationId: string) => {
|
||||
try {
|
||||
const response = await fetch(`/api/invitations/${invitationId}`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to delete invitation");
|
||||
}
|
||||
|
||||
setInvitations(invitations.filter(inv => inv.id !== invitationId));
|
||||
toast({
|
||||
title: "Success",
|
||||
description: "Invitation deleted successfully",
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error deleting invitation:", error);
|
||||
toast({
|
||||
title: "Error",
|
||||
description: "Failed to delete invitation",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="py-8">
|
||||
<p className="text-center text-muted-foreground">Loading invitations...</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<CardTitle>Manage Invitations</CardTitle>
|
||||
<CardDescription>
|
||||
Invite researchers and participants to collaborate on this study
|
||||
</CardDescription>
|
||||
</div>
|
||||
<InviteUserDialog studyId={studyId} onInviteSent={fetchInvitations} />
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{invitations.length > 0 ? (
|
||||
<div className="space-y-4">
|
||||
{invitations.map((invitation) => (
|
||||
<div
|
||||
key={invitation.id}
|
||||
className="flex items-center justify-between p-4 border rounded-lg bg-card"
|
||||
>
|
||||
<div>
|
||||
<p className="font-medium">{invitation.email}</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Role: {invitation.roleName}
|
||||
{invitation.accepted ? " • Accepted" : " • Pending"}
|
||||
</p>
|
||||
</div>
|
||||
{!invitation.accepted && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleDeleteInvitation(invitation.id)}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-muted-foreground">No invitations sent yet.</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,165 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "~/components/ui/dialog";
|
||||
import { Input } from "~/components/ui/input";
|
||||
import { Label } from "~/components/ui/label";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "~/components/ui/select";
|
||||
import { useToast } from "~/hooks/use-toast";
|
||||
|
||||
interface Role {
|
||||
id: number;
|
||||
name: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
interface InviteUserDialogProps {
|
||||
studyId: number;
|
||||
onInviteSent: () => void;
|
||||
}
|
||||
|
||||
export function InviteUserDialog({ studyId, onInviteSent }: InviteUserDialogProps) {
|
||||
const [email, setEmail] = useState("");
|
||||
const [roleId, setRoleId] = useState<string>("");
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [roles, setRoles] = useState<Role[]>([]);
|
||||
const { toast } = useToast();
|
||||
|
||||
const fetchRoles = useCallback(async () => {
|
||||
try {
|
||||
const response = await fetch("/api/roles");
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to fetch roles");
|
||||
}
|
||||
const data = await response.json();
|
||||
// Filter out admin and PI roles
|
||||
setRoles(data.filter((role: Role) =>
|
||||
!['admin', 'principal_investigator'].includes(role.name)
|
||||
));
|
||||
} catch (error) {
|
||||
console.error("Error fetching roles:", error);
|
||||
toast({
|
||||
title: "Error",
|
||||
description: "Failed to load roles",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
}, [toast]);
|
||||
|
||||
// Fetch available roles when dialog opens
|
||||
useEffect(() => {
|
||||
fetchRoles();
|
||||
}, [fetchRoles]);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!email || !roleId) return;
|
||||
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const response = await fetch("/api/invitations", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
email,
|
||||
roleId: parseInt(roleId, 10),
|
||||
studyId,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to send invitation");
|
||||
}
|
||||
|
||||
toast({
|
||||
title: "Success",
|
||||
description: "Invitation sent successfully",
|
||||
});
|
||||
setIsOpen(false);
|
||||
setEmail("");
|
||||
setRoleId("");
|
||||
onInviteSent();
|
||||
} catch (error) {
|
||||
console.error("Error sending invitation:", error);
|
||||
toast({
|
||||
title: "Error",
|
||||
description: "Failed to send invitation",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={setIsOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button>Invite User</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Invite User</DialogTitle>
|
||||
<DialogDescription>
|
||||
Send an invitation to collaborate on this study
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">Email</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
placeholder="Enter email address"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="role">Role</Label>
|
||||
<Select value={roleId} onValueChange={setRoleId} required>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select a role" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{roles.map((role) => (
|
||||
<SelectItem key={role.id} value={role.id.toString()}>
|
||||
{role.name.split('_').map(word =>
|
||||
word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()
|
||||
).join(' ')}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={() => setIsOpen(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={isLoading}>
|
||||
{isLoading ? "Sending..." : "Send Invitation"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1,227 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { PlusIcon, Trash2Icon } from "lucide-react";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "~/components/ui/card";
|
||||
import { Input } from "~/components/ui/input";
|
||||
import { Label } from "~/components/ui/label";
|
||||
import { useToast } from "~/hooks/use-toast";
|
||||
import { PERMISSIONS } from "~/lib/permissions-client";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
AlertDialogFooter
|
||||
} from "~/components/ui/alert-dialog";
|
||||
|
||||
interface Participant {
|
||||
id: number;
|
||||
name: string;
|
||||
studyId: number;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
interface ParticipantsTabProps {
|
||||
studyId: number;
|
||||
permissions: string[];
|
||||
}
|
||||
|
||||
export function ParticipantsTab({ studyId, permissions }: ParticipantsTabProps) {
|
||||
const [participants, setParticipants] = useState<Participant[]>([]);
|
||||
const [name, setName] = useState("");
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const { toast } = useToast();
|
||||
|
||||
const hasPermission = (permission: string) => permissions.includes(permission);
|
||||
const canCreateParticipant = hasPermission(PERMISSIONS.CREATE_PARTICIPANT);
|
||||
const canDeleteParticipant = hasPermission(PERMISSIONS.DELETE_PARTICIPANT);
|
||||
const canViewNames = hasPermission(PERMISSIONS.VIEW_PARTICIPANT_NAMES);
|
||||
|
||||
const fetchParticipants = useCallback(async () => {
|
||||
try {
|
||||
const response = await fetch(`/api/studies/${studyId}/participants`);
|
||||
if (!response.ok) throw new Error("Failed to fetch participants");
|
||||
const data = await response.json();
|
||||
setParticipants(data.data || []);
|
||||
} catch (error) {
|
||||
console.error("Error fetching participants:", error);
|
||||
toast({
|
||||
title: "Error",
|
||||
description: "Failed to load participants",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [toast, studyId]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchParticipants();
|
||||
}, [fetchParticipants]);
|
||||
|
||||
const createParticipant = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
const response = await fetch(`/api/studies/${studyId}/participants`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ name }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to create participant");
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
setParticipants([...participants, data.data]);
|
||||
setName("");
|
||||
toast({
|
||||
title: "Success",
|
||||
description: "Participant created successfully",
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error creating participant:", error);
|
||||
toast({
|
||||
title: "Error",
|
||||
description: "Failed to create participant",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const deleteParticipant = async (participantId: number) => {
|
||||
try {
|
||||
const response = await fetch(`/api/studies/${studyId}/participants`, {
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ participantId }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to delete participant");
|
||||
}
|
||||
|
||||
setParticipants(participants.filter(p => p.id !== participantId));
|
||||
toast({
|
||||
title: "Success",
|
||||
description: "Participant deleted successfully",
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error deleting participant:", error);
|
||||
toast({
|
||||
title: "Error",
|
||||
description: "Failed to delete participant",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="py-8">
|
||||
<p className="text-center text-muted-foreground">Loading participants...</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{canCreateParticipant && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Add New Participant</CardTitle>
|
||||
<CardDescription>Add a new participant to this study</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={createParticipant} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="name">Participant Name</Label>
|
||||
<Input
|
||||
id="name"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="Enter participant name"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<Button type="submit">
|
||||
<PlusIcon className="w-4 h-4 mr-2" />
|
||||
Add Participant
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<div className="grid gap-4">
|
||||
{participants.length > 0 ? (
|
||||
participants.map((participant) => (
|
||||
<Card key={participant.id}>
|
||||
<div className="p-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h3 className="font-semibold">
|
||||
{participant.name}
|
||||
{!canViewNames && <span className="text-sm text-muted-foreground ml-2">(ID: {participant.id})</span>}
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Added {new Date(participant.createdAt).toLocaleDateString()}
|
||||
</p>
|
||||
</div>
|
||||
{canDeleteParticipant && (
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger asChild>
|
||||
<Button variant="outline" size="sm">
|
||||
<Trash2Icon className="w-4 h-4 mr-2" />
|
||||
Delete
|
||||
</Button>
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
This action cannot be undone. This will permanently delete the participant
|
||||
"{participant.name}" and all associated data.
|
||||
</div>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={() => deleteParticipant(participant.id)}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
Delete Participant
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
))
|
||||
) : (
|
||||
<Card>
|
||||
<CardContent className="py-8">
|
||||
<p className="text-center text-muted-foreground">
|
||||
No participants added yet{canCreateParticipant ? ". Add your first participant above" : ""}.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,118 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "~/components/ui/card";
|
||||
import { Input } from "~/components/ui/input";
|
||||
import { Label } from "~/components/ui/label";
|
||||
import { Textarea } from "~/components/ui/textarea";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { useToast } from "~/hooks/use-toast";
|
||||
import { useState } from "react";
|
||||
import { PERMISSIONS } from "~/lib/permissions-client";
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
interface SettingsTabProps {
|
||||
study: {
|
||||
id: number;
|
||||
title: string;
|
||||
description: string | null;
|
||||
permissions: string[];
|
||||
};
|
||||
}
|
||||
|
||||
export function SettingsTab({ study }: SettingsTabProps) {
|
||||
const [title, setTitle] = useState(study.title);
|
||||
const [description, setDescription] = useState(study.description || "");
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const { toast } = useToast();
|
||||
const router = useRouter();
|
||||
|
||||
const hasPermission = (permission: string) => study.permissions.includes(permission);
|
||||
const canEditStudy = hasPermission(PERMISSIONS.EDIT_STUDY);
|
||||
|
||||
const updateStudy = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!canEditStudy) return;
|
||||
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const response = await fetch(`/api/studies/${study.id}`, {
|
||||
method: "PATCH",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ title, description }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
if (response.status === 403) {
|
||||
router.push('/dashboard/studies');
|
||||
return;
|
||||
}
|
||||
throw new Error("Failed to update study");
|
||||
}
|
||||
|
||||
toast({
|
||||
title: "Success",
|
||||
description: "Study updated successfully",
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error updating study:", error);
|
||||
toast({
|
||||
title: "Error",
|
||||
description: error instanceof Error ? error.message : "Failed to update study",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (!canEditStudy) {
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="py-8">
|
||||
<p className="text-center text-muted-foreground">
|
||||
You don't have permission to edit this study.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Study Settings</CardTitle>
|
||||
<CardDescription>Update your study details and configuration</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={updateStudy} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="title">Study Title</Label>
|
||||
<Input
|
||||
id="title"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
placeholder="Enter study title"
|
||||
required
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="description">Description</Label>
|
||||
<Textarea
|
||||
id="description"
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
placeholder="Enter study description"
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</div>
|
||||
<Button type="submit" disabled={isLoading}>
|
||||
{isLoading ? "Saving..." : "Save Changes"}
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -1,342 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
import { UserAvatar } from "~/components/user-avatar";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "~/components/ui/card";
|
||||
import { useToast } from "~/hooks/use-toast";
|
||||
import { PERMISSIONS } from "~/lib/permissions-client";
|
||||
import { InviteUserDialog } from "./invite-user-dialog";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "~/components/ui/select";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "~/components/ui/table";
|
||||
import { Trash2Icon } from "lucide-react";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from "~/components/ui/alert-dialog";
|
||||
|
||||
interface User {
|
||||
id: string;
|
||||
email: string;
|
||||
name: string | null;
|
||||
roles: Array<{ id: number; name: string }>;
|
||||
imageUrl: string;
|
||||
}
|
||||
|
||||
interface Invitation {
|
||||
id: string;
|
||||
email: string;
|
||||
roleName: string;
|
||||
accepted: boolean;
|
||||
expiresAt: string;
|
||||
}
|
||||
|
||||
interface Role {
|
||||
id: number;
|
||||
name: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
interface UsersTabProps {
|
||||
studyId: number;
|
||||
permissions: string[];
|
||||
}
|
||||
|
||||
export function UsersTab({ studyId, permissions }: UsersTabProps) {
|
||||
const [users, setUsers] = useState<User[]>([]);
|
||||
const [invitations, setInvitations] = useState<Invitation[]>([]);
|
||||
const [roles, setRoles] = useState<Role[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const { toast } = useToast();
|
||||
|
||||
const hasPermission = (permission: string) => permissions.includes(permission);
|
||||
const canManageRoles = hasPermission(PERMISSIONS.MANAGE_ROLES);
|
||||
|
||||
const fetchUsers = useCallback(async () => {
|
||||
try {
|
||||
const response = await fetch(`/api/studies/${studyId}/users`);
|
||||
if (!response.ok) throw new Error("Failed to fetch users");
|
||||
const data = await response.json();
|
||||
setUsers(data.data || []);
|
||||
} catch (error) {
|
||||
console.error("Error fetching users:", error);
|
||||
toast({
|
||||
title: "Error",
|
||||
description: "Failed to load users",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
}, [studyId, toast]);
|
||||
|
||||
const fetchInvitations = useCallback(async () => {
|
||||
try {
|
||||
const response = await fetch(`/api/invitations?studyId=${studyId}`);
|
||||
if (response.status === 403) {
|
||||
// Silently handle 403 errors as they're expected for researchers
|
||||
return;
|
||||
}
|
||||
if (!response.ok) throw new Error("Failed to fetch invitations");
|
||||
const data = await response.json();
|
||||
setInvitations(data.data || []);
|
||||
} catch (error) {
|
||||
console.error("Error fetching invitations:", error);
|
||||
toast({
|
||||
title: "Error",
|
||||
description: "Failed to load invitations",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
}, [studyId, toast]);
|
||||
|
||||
const fetchRoles = useCallback(async () => {
|
||||
try {
|
||||
const response = await fetch("/api/roles");
|
||||
if (!response.ok) throw new Error("Failed to fetch roles");
|
||||
const data = await response.json();
|
||||
setRoles(data);
|
||||
} catch (error) {
|
||||
console.error("Error fetching roles:", error);
|
||||
toast({
|
||||
title: "Error",
|
||||
description: "Failed to load roles",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
}, [toast]);
|
||||
|
||||
const fetchData = useCallback(async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const promises = [fetchUsers(), fetchRoles()];
|
||||
if (canManageRoles) {
|
||||
promises.push(fetchInvitations());
|
||||
}
|
||||
await Promise.all(promises);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [fetchUsers, fetchInvitations, fetchRoles, canManageRoles]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchData();
|
||||
}, [fetchData]);
|
||||
|
||||
const handleRoleChange = async (userId: string, newRoleId: string) => {
|
||||
try {
|
||||
const response = await fetch(`/api/studies/${studyId}/users/${userId}/role`, {
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
roleId: parseInt(newRoleId, 10),
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) throw new Error("Failed to update role");
|
||||
|
||||
toast({
|
||||
title: "Success",
|
||||
description: "User role updated successfully",
|
||||
});
|
||||
|
||||
// Refresh users list
|
||||
fetchUsers();
|
||||
} catch (error) {
|
||||
console.error("Error updating role:", error);
|
||||
toast({
|
||||
title: "Error",
|
||||
description: "Failed to update user role",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteInvitation = async (invitationId: string) => {
|
||||
try {
|
||||
const response = await fetch(`/api/invitations/${invitationId}`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
|
||||
if (!response.ok) throw new Error("Failed to delete invitation");
|
||||
|
||||
setInvitations(invitations.filter(inv => inv.id !== invitationId));
|
||||
toast({
|
||||
title: "Success",
|
||||
description: "Invitation deleted successfully",
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error deleting invitation:", error);
|
||||
toast({
|
||||
title: "Error",
|
||||
description: "Failed to delete invitation",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const formatName = (user: User) => {
|
||||
return user.name || user.email;
|
||||
};
|
||||
|
||||
const formatRoleName = (name: string) => {
|
||||
return name
|
||||
.split('_')
|
||||
.map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
|
||||
.join(' ');
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return <div>Loading...</div>;
|
||||
}
|
||||
|
||||
const pendingInvitations = invitations.filter(inv => !inv.accepted);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader className="flex flex-col justify-between">
|
||||
<div className="flex justify-between items-center">
|
||||
<div>
|
||||
<CardTitle>Study Members</CardTitle>
|
||||
<CardDescription>
|
||||
{canManageRoles ? 'Manage users and their roles in this study' : 'View study members'}
|
||||
</CardDescription>
|
||||
</div>
|
||||
{canManageRoles && (
|
||||
<InviteUserDialog
|
||||
studyId={studyId}
|
||||
onInviteSent={() => canManageRoles && fetchInvitations()}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>User</TableHead>
|
||||
<TableHead>Email</TableHead>
|
||||
<TableHead>Role</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{users.map((user) => (
|
||||
<TableRow key={user.id}>
|
||||
<TableCell className="flex items-center gap-2">
|
||||
<UserAvatar
|
||||
user={{
|
||||
name: formatName(user),
|
||||
email: user.email,
|
||||
imageUrl: user.imageUrl,
|
||||
}}
|
||||
/>
|
||||
<span>{formatName(user)}</span>
|
||||
</TableCell>
|
||||
<TableCell>{user.email}</TableCell>
|
||||
<TableCell>
|
||||
<Select
|
||||
value={user.roles[0]?.id.toString()}
|
||||
onValueChange={(value) => handleRoleChange(user.id, value)}
|
||||
disabled={!canManageRoles}
|
||||
>
|
||||
<SelectTrigger className="w-[180px]">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
{canManageRoles && (
|
||||
<SelectContent>
|
||||
{roles.map((role) => (
|
||||
<SelectItem key={role.id} value={role.id.toString()}>
|
||||
{formatRoleName(role.name)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
)}
|
||||
</Select>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{canManageRoles && pendingInvitations.length > 0 && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Pending Invitations</CardTitle>
|
||||
<CardDescription>
|
||||
Outstanding invitations to join the study
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Email</TableHead>
|
||||
<TableHead>Role</TableHead>
|
||||
<TableHead>Expires</TableHead>
|
||||
<TableHead className="w-[100px]">Actions</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{pendingInvitations.map((invitation) => (
|
||||
<TableRow key={invitation.id}>
|
||||
<TableCell>{invitation.email}</TableCell>
|
||||
<TableCell>{formatRoleName(invitation.roleName)}</TableCell>
|
||||
<TableCell>{new Date(invitation.expiresAt).toLocaleDateString()}</TableCell>
|
||||
<TableCell>
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger asChild>
|
||||
<Button variant="ghost" size="icon">
|
||||
<Trash2Icon className="h-4 w-4" />
|
||||
</Button>
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete Invitation</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Are you sure you want to delete this invitation? This action cannot be undone.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={() => handleDeleteInvitation(invitation.id)}
|
||||
>
|
||||
Delete
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,141 +0,0 @@
|
||||
"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"
|
||||
|
||||
const AlertDialog = AlertDialogPrimitive.Root
|
||||
|
||||
const AlertDialogTrigger = AlertDialogPrimitive.Trigger
|
||||
|
||||
const AlertDialogPortal = AlertDialogPrimitive.Portal
|
||||
|
||||
const AlertDialogOverlay = React.forwardRef<
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Overlay>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Overlay>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AlertDialogPrimitive.Overlay
|
||||
className={cn(
|
||||
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
ref={ref}
|
||||
/>
|
||||
))
|
||||
AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName
|
||||
|
||||
const AlertDialogContent = React.forwardRef<
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AlertDialogPortal>
|
||||
<AlertDialogOverlay />
|
||||
<AlertDialogPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 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 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</AlertDialogPortal>
|
||||
))
|
||||
AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName
|
||||
|
||||
const AlertDialogHeader = ({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-col space-y-2 text-center sm:text-left",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
AlertDialogHeader.displayName = "AlertDialogHeader"
|
||||
|
||||
const AlertDialogFooter = ({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
AlertDialogFooter.displayName = "AlertDialogFooter"
|
||||
|
||||
const AlertDialogTitle = React.forwardRef<
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Title>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Title>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AlertDialogPrimitive.Title
|
||||
ref={ref}
|
||||
className={cn("text-lg font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName
|
||||
|
||||
const AlertDialogDescription = React.forwardRef<
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Description>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Description>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AlertDialogPrimitive.Description
|
||||
ref={ref}
|
||||
className={cn("text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
AlertDialogDescription.displayName =
|
||||
AlertDialogPrimitive.Description.displayName
|
||||
|
||||
const AlertDialogAction = React.forwardRef<
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Action>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AlertDialogPrimitive.Action
|
||||
ref={ref}
|
||||
className={cn(buttonVariants(), className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName
|
||||
|
||||
const AlertDialogCancel = React.forwardRef<
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Cancel>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Cancel>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AlertDialogPrimitive.Cancel
|
||||
ref={ref}
|
||||
className={cn(
|
||||
buttonVariants({ variant: "outline" }),
|
||||
"mt-2 sm:mt-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName
|
||||
|
||||
export {
|
||||
AlertDialog,
|
||||
AlertDialogPortal,
|
||||
AlertDialogOverlay,
|
||||
AlertDialogTrigger,
|
||||
AlertDialogContent,
|
||||
AlertDialogHeader,
|
||||
AlertDialogFooter,
|
||||
AlertDialogTitle,
|
||||
AlertDialogDescription,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
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 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground [&>svg~*]:pl-7",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-background text-foreground",
|
||||
destructive:
|
||||
"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
const Alert = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof alertVariants>
|
||||
>(({ className, variant, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
role="alert"
|
||||
className={cn(alertVariants({ variant }), className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
Alert.displayName = "Alert"
|
||||
|
||||
const AlertTitle = React.forwardRef<
|
||||
HTMLParagraphElement,
|
||||
React.HTMLAttributes<HTMLHeadingElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<h5
|
||||
ref={ref}
|
||||
className={cn("mb-1 font-medium leading-none tracking-tight", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
AlertTitle.displayName = "AlertTitle"
|
||||
|
||||
const AlertDescription = React.forwardRef<
|
||||
HTMLParagraphElement,
|
||||
React.HTMLAttributes<HTMLParagraphElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn("text-sm [&_p]:leading-relaxed", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
AlertDescription.displayName = "AlertDescription"
|
||||
|
||||
export { Alert, AlertTitle, AlertDescription }
|
||||
@@ -12,7 +12,7 @@ const Avatar = React.forwardRef<
|
||||
<AvatarPrimitive.Root
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",
|
||||
"relative flex h-10 w-10 shrink-0 overflow-hidden rounded-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
@@ -26,7 +26,7 @@ const AvatarImage = React.forwardRef<
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AvatarPrimitive.Image
|
||||
ref={ref}
|
||||
className={cn("aspect-square h-full w-full", className)}
|
||||
className={cn("aspect-square h-full w-full rounded-lg", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
@@ -39,7 +39,7 @@ const AvatarFallback = React.forwardRef<
|
||||
<AvatarPrimitive.Fallback
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex h-full w-full items-center justify-center rounded-full bg-muted",
|
||||
"flex h-full w-full items-center justify-center rounded-lg bg-muted",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
import * as React from "react"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { cn } from "~/lib/utils"
|
||||
|
||||
const badgeVariants = cva(
|
||||
"inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
"border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80",
|
||||
secondary:
|
||||
"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||
destructive:
|
||||
"border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80",
|
||||
outline: "text-foreground",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
export interface BadgeProps
|
||||
extends React.HTMLAttributes<HTMLDivElement>,
|
||||
VariantProps<typeof badgeVariants> {}
|
||||
|
||||
function Badge({ className, variant, ...props }: BadgeProps) {
|
||||
return (
|
||||
<div className={cn(badgeVariants({ variant }), className)} {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
export { Badge, badgeVariants }
|
||||
@@ -1,7 +1,8 @@
|
||||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { ChevronRight, MoreHorizontal } from "lucide-react"
|
||||
|
||||
import { cn } from "~/lib/utils"
|
||||
import { ChevronRightIcon, DotsHorizontalIcon } from "@radix-ui/react-icons"
|
||||
|
||||
const Breadcrumb = React.forwardRef<
|
||||
HTMLElement,
|
||||
@@ -82,7 +83,7 @@ const BreadcrumbSeparator = ({
|
||||
className={cn("[&>svg]:w-3.5 [&>svg]:h-3.5", className)}
|
||||
{...props}
|
||||
>
|
||||
{children ?? <ChevronRightIcon />}
|
||||
{children ?? <ChevronRight />}
|
||||
</li>
|
||||
)
|
||||
BreadcrumbSeparator.displayName = "BreadcrumbSeparator"
|
||||
@@ -97,7 +98,7 @@ const BreadcrumbEllipsis = ({
|
||||
className={cn("flex h-9 w-9 items-center justify-center", className)}
|
||||
{...props}
|
||||
>
|
||||
<DotsHorizontalIcon className="h-4 w-4" />
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
<span className="sr-only">More</span>
|
||||
</span>
|
||||
)
|
||||
|
||||
@@ -5,26 +5,21 @@ import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { cn } from "~/lib/utils"
|
||||
|
||||
const buttonVariants = cva(
|
||||
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
|
||||
"inline-flex items-center justify-center rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:opacity-50 disabled:pointer-events-none ring-offset-background",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
"bg-primary text-primary-foreground shadow hover:bg-primary/90",
|
||||
destructive:
|
||||
"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",
|
||||
outline:
|
||||
"border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
|
||||
default: "bg-primary text-primary-foreground hover:bg-primary/90",
|
||||
destructive: "bg-destructive text-destructive-foreground hover:bg-destructive/90",
|
||||
outline: "border border-input hover:bg-accent hover:text-accent-foreground",
|
||||
secondary: "bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||
ghost: "hover:bg-accent hover:text-accent-foreground",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
link: "underline-offset-4 hover:underline text-primary",
|
||||
},
|
||||
size: {
|
||||
default: "h-9 px-4 py-2",
|
||||
sm: "h-8 rounded-md px-3 text-xs",
|
||||
lg: "h-10 rounded-md px-8",
|
||||
icon: "h-9 w-9",
|
||||
default: "h-10 py-2 px-4",
|
||||
sm: "h-9 px-3 rounded-md",
|
||||
lg: "h-11 px-8 rounded-md",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
|
||||
@@ -9,7 +9,7 @@ const Card = React.forwardRef<
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"rounded-xl border bg-card text-card-foreground shadow",
|
||||
"rounded-lg border border-[hsl(var(--border))] bg-[hsl(var(--card-level-1))] shadow-sm",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
@@ -30,10 +30,10 @@ const CardHeader = React.forwardRef<
|
||||
CardHeader.displayName = "CardHeader"
|
||||
|
||||
const CardTitle = React.forwardRef<
|
||||
HTMLParagraphElement,
|
||||
React.HTMLAttributes<HTMLHeadingElement>
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<h3
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn("font-semibold leading-none tracking-tight", className)}
|
||||
{...props}
|
||||
@@ -42,10 +42,10 @@ const CardTitle = React.forwardRef<
|
||||
CardTitle.displayName = "CardTitle"
|
||||
|
||||
const CardDescription = React.forwardRef<
|
||||
HTMLParagraphElement,
|
||||
React.HTMLAttributes<HTMLParagraphElement>
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<p
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn("text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
|
||||
11
src/components/ui/collapsible.tsx
Normal file
11
src/components/ui/collapsible.tsx
Normal file
@@ -0,0 +1,11 @@
|
||||
"use client"
|
||||
|
||||
import * as CollapsiblePrimitive from "@radix-ui/react-collapsible"
|
||||
|
||||
const Collapsible = CollapsiblePrimitive.Root
|
||||
|
||||
const CollapsibleTrigger = CollapsiblePrimitive.CollapsibleTrigger
|
||||
|
||||
const CollapsibleContent = CollapsiblePrimitive.CollapsibleContent
|
||||
|
||||
export { Collapsible, CollapsibleTrigger, CollapsibleContent }
|
||||
153
src/components/ui/command.tsx
Normal file
153
src/components/ui/command.tsx
Normal file
@@ -0,0 +1,153 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { type DialogProps } from "@radix-ui/react-dialog"
|
||||
import { Command as CommandPrimitive } from "cmdk"
|
||||
import { Search } from "lucide-react"
|
||||
|
||||
import { cn } from "~/lib/utils"
|
||||
import { Dialog, DialogContent } from "~/components/ui/dialog"
|
||||
|
||||
const Command = React.forwardRef<
|
||||
React.ElementRef<typeof CommandPrimitive>,
|
||||
React.ComponentPropsWithoutRef<typeof CommandPrimitive>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<CommandPrimitive
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
Command.displayName = CommandPrimitive.displayName
|
||||
|
||||
const CommandDialog = ({ children, ...props }: DialogProps) => {
|
||||
return (
|
||||
<Dialog {...props}>
|
||||
<DialogContent className="overflow-hidden p-0">
|
||||
<Command className="[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
|
||||
{children}
|
||||
</Command>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
const CommandInput = React.forwardRef<
|
||||
React.ElementRef<typeof CommandPrimitive.Input>,
|
||||
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Input>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div className="flex items-center border-b px-3" cmdk-input-wrapper="">
|
||||
<Search className="mr-2 h-4 w-4 shrink-0 opacity-50" />
|
||||
<CommandPrimitive.Input
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
))
|
||||
|
||||
CommandInput.displayName = CommandPrimitive.Input.displayName
|
||||
|
||||
const CommandList = React.forwardRef<
|
||||
React.ElementRef<typeof CommandPrimitive.List>,
|
||||
React.ComponentPropsWithoutRef<typeof CommandPrimitive.List>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<CommandPrimitive.List
|
||||
ref={ref}
|
||||
className={cn("max-h-[300px] overflow-y-auto overflow-x-hidden", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
|
||||
CommandList.displayName = CommandPrimitive.List.displayName
|
||||
|
||||
const CommandEmpty = React.forwardRef<
|
||||
React.ElementRef<typeof CommandPrimitive.Empty>,
|
||||
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Empty>
|
||||
>((props, ref) => (
|
||||
<CommandPrimitive.Empty
|
||||
ref={ref}
|
||||
className="py-6 text-center text-sm"
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
|
||||
CommandEmpty.displayName = CommandPrimitive.Empty.displayName
|
||||
|
||||
const CommandGroup = React.forwardRef<
|
||||
React.ElementRef<typeof CommandPrimitive.Group>,
|
||||
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Group>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<CommandPrimitive.Group
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
|
||||
CommandGroup.displayName = CommandPrimitive.Group.displayName
|
||||
|
||||
const CommandSeparator = React.forwardRef<
|
||||
React.ElementRef<typeof CommandPrimitive.Separator>,
|
||||
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Separator>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<CommandPrimitive.Separator
|
||||
ref={ref}
|
||||
className={cn("-mx-1 h-px bg-border", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
CommandSeparator.displayName = CommandPrimitive.Separator.displayName
|
||||
|
||||
const CommandItem = React.forwardRef<
|
||||
React.ElementRef<typeof CommandPrimitive.Item>,
|
||||
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Item>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<CommandPrimitive.Item
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative flex cursor-default gap-2 select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
|
||||
CommandItem.displayName = CommandPrimitive.Item.displayName
|
||||
|
||||
const CommandShortcut = ({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLSpanElement>) => {
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"ml-auto text-xs tracking-widest text-muted-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
CommandShortcut.displayName = "CommandShortcut"
|
||||
|
||||
export {
|
||||
Command,
|
||||
CommandDialog,
|
||||
CommandInput,
|
||||
CommandList,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandItem,
|
||||
CommandShortcut,
|
||||
CommandSeparator,
|
||||
}
|
||||
@@ -2,8 +2,9 @@
|
||||
|
||||
import * as React from "react"
|
||||
import * as DialogPrimitive from "@radix-ui/react-dialog"
|
||||
import { X } from "lucide-react"
|
||||
|
||||
import { cn } from "~/lib/utils"
|
||||
import { Cross2Icon } from "@radix-ui/react-icons"
|
||||
|
||||
const Dialog = DialogPrimitive.Root
|
||||
|
||||
@@ -44,7 +45,7 @@ const DialogContent = React.forwardRef<
|
||||
>
|
||||
{children}
|
||||
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
|
||||
<Cross2Icon className="h-4 w-4" />
|
||||
<X className="h-4 w-4" />
|
||||
<span className="sr-only">Close</span>
|
||||
</DialogPrimitive.Close>
|
||||
</DialogPrimitive.Content>
|
||||
|
||||
201
src/components/ui/dropdown-menu.tsx
Normal file
201
src/components/ui/dropdown-menu.tsx
Normal file
@@ -0,0 +1,201 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"
|
||||
import { Check, ChevronRight, Circle } from "lucide-react"
|
||||
|
||||
import { cn } from "~/lib/utils"
|
||||
|
||||
const DropdownMenu = DropdownMenuPrimitive.Root
|
||||
|
||||
const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger
|
||||
|
||||
const DropdownMenuGroup = DropdownMenuPrimitive.Group
|
||||
|
||||
const DropdownMenuPortal = DropdownMenuPrimitive.Portal
|
||||
|
||||
const DropdownMenuSub = DropdownMenuPrimitive.Sub
|
||||
|
||||
const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup
|
||||
|
||||
const DropdownMenuSubTrigger = React.forwardRef<
|
||||
React.ElementRef<typeof DropdownMenuPrimitive.SubTrigger>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger> & {
|
||||
inset?: boolean
|
||||
}
|
||||
>(({ className, inset, children, ...props }, ref) => (
|
||||
<DropdownMenuPrimitive.SubTrigger
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex cursor-default gap-2 select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
|
||||
inset && "pl-8",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronRight className="ml-auto" />
|
||||
</DropdownMenuPrimitive.SubTrigger>
|
||||
))
|
||||
DropdownMenuSubTrigger.displayName =
|
||||
DropdownMenuPrimitive.SubTrigger.displayName
|
||||
|
||||
const DropdownMenuSubContent = React.forwardRef<
|
||||
React.ElementRef<typeof DropdownMenuPrimitive.SubContent>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DropdownMenuPrimitive.SubContent
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg 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 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
DropdownMenuSubContent.displayName =
|
||||
DropdownMenuPrimitive.SubContent.displayName
|
||||
|
||||
const DropdownMenuContent = React.forwardRef<
|
||||
React.ElementRef<typeof DropdownMenuPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content>
|
||||
>(({ className, sideOffset = 4, ...props }, ref) => (
|
||||
<DropdownMenuPrimitive.Portal>
|
||||
<DropdownMenuPrimitive.Content
|
||||
ref={ref}
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md",
|
||||
"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 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</DropdownMenuPrimitive.Portal>
|
||||
))
|
||||
DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName
|
||||
|
||||
const DropdownMenuItem = React.forwardRef<
|
||||
React.ElementRef<typeof DropdownMenuPrimitive.Item>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {
|
||||
inset?: boolean
|
||||
}
|
||||
>(({ className, inset, ...props }, ref) => (
|
||||
<DropdownMenuPrimitive.Item
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
inset && "pl-8",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName
|
||||
|
||||
const DropdownMenuCheckboxItem = React.forwardRef<
|
||||
React.ElementRef<typeof DropdownMenuPrimitive.CheckboxItem>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.CheckboxItem>
|
||||
>(({ className, children, checked, ...props }, ref) => (
|
||||
<DropdownMenuPrimitive.CheckboxItem
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
|
||||
className
|
||||
)}
|
||||
checked={checked}
|
||||
{...props}
|
||||
>
|
||||
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
|
||||
<DropdownMenuPrimitive.ItemIndicator>
|
||||
<Check className="h-4 w-4" />
|
||||
</DropdownMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.CheckboxItem>
|
||||
))
|
||||
DropdownMenuCheckboxItem.displayName =
|
||||
DropdownMenuPrimitive.CheckboxItem.displayName
|
||||
|
||||
const DropdownMenuRadioItem = React.forwardRef<
|
||||
React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.RadioItem>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<DropdownMenuPrimitive.RadioItem
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
|
||||
<DropdownMenuPrimitive.ItemIndicator>
|
||||
<Circle className="h-2 w-2 fill-current" />
|
||||
</DropdownMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.RadioItem>
|
||||
))
|
||||
DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName
|
||||
|
||||
const DropdownMenuLabel = React.forwardRef<
|
||||
React.ElementRef<typeof DropdownMenuPrimitive.Label>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & {
|
||||
inset?: boolean
|
||||
}
|
||||
>(({ className, inset, ...props }, ref) => (
|
||||
<DropdownMenuPrimitive.Label
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"px-2 py-1.5 text-sm font-semibold",
|
||||
inset && "pl-8",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName
|
||||
|
||||
const DropdownMenuSeparator = React.forwardRef<
|
||||
React.ElementRef<typeof DropdownMenuPrimitive.Separator>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DropdownMenuPrimitive.Separator
|
||||
ref={ref}
|
||||
className={cn("-mx-1 my-1 h-px bg-muted", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName
|
||||
|
||||
const DropdownMenuShortcut = ({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLSpanElement>) => {
|
||||
return (
|
||||
<span
|
||||
className={cn("ml-auto text-xs tracking-widest opacity-60", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
DropdownMenuShortcut.displayName = "DropdownMenuShortcut"
|
||||
|
||||
export {
|
||||
DropdownMenu,
|
||||
DropdownMenuTrigger,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuCheckboxItem,
|
||||
DropdownMenuRadioItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuShortcut,
|
||||
DropdownMenuGroup,
|
||||
DropdownMenuPortal,
|
||||
DropdownMenuSub,
|
||||
DropdownMenuSubContent,
|
||||
DropdownMenuSubTrigger,
|
||||
DropdownMenuRadioGroup,
|
||||
}
|
||||
178
src/components/ui/form.tsx
Normal file
178
src/components/ui/form.tsx
Normal file
@@ -0,0 +1,178 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import type * as LabelPrimitive from "@radix-ui/react-label"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import {
|
||||
Controller,
|
||||
FormProvider,
|
||||
useFormContext,
|
||||
type ControllerProps,
|
||||
type FieldPath,
|
||||
type FieldValues,
|
||||
} from "react-hook-form"
|
||||
|
||||
import { cn } from "~/lib/utils"
|
||||
import { Label } from "~/components/ui/label"
|
||||
|
||||
const Form = FormProvider
|
||||
|
||||
type FormFieldContextValue<
|
||||
TFieldValues extends FieldValues = FieldValues,
|
||||
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
|
||||
> = {
|
||||
name: TName
|
||||
}
|
||||
|
||||
const FormFieldContext = React.createContext<FormFieldContextValue>(
|
||||
{} as FormFieldContextValue
|
||||
)
|
||||
|
||||
const FormField = <
|
||||
TFieldValues extends FieldValues = FieldValues,
|
||||
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
|
||||
>({
|
||||
...props
|
||||
}: ControllerProps<TFieldValues, TName>) => {
|
||||
return (
|
||||
<FormFieldContext.Provider value={{ name: props.name }}>
|
||||
<Controller {...props} />
|
||||
</FormFieldContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
const useFormField = () => {
|
||||
const fieldContext = React.useContext(FormFieldContext)
|
||||
const itemContext = React.useContext(FormItemContext)
|
||||
const { getFieldState, formState } = useFormContext()
|
||||
|
||||
const fieldState = getFieldState(fieldContext.name, formState)
|
||||
|
||||
if (!fieldContext) {
|
||||
throw new Error("useFormField should be used within <FormField>")
|
||||
}
|
||||
|
||||
const { id } = itemContext
|
||||
|
||||
return {
|
||||
id,
|
||||
name: fieldContext.name,
|
||||
formItemId: `${id}-form-item`,
|
||||
formDescriptionId: `${id}-form-item-description`,
|
||||
formMessageId: `${id}-form-item-message`,
|
||||
...fieldState,
|
||||
}
|
||||
}
|
||||
|
||||
type FormItemContextValue = {
|
||||
id: string
|
||||
}
|
||||
|
||||
const FormItemContext = React.createContext<FormItemContextValue>(
|
||||
{} as FormItemContextValue
|
||||
)
|
||||
|
||||
const FormItem = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement>
|
||||
>(({ className, ...props }, ref) => {
|
||||
const id = React.useId()
|
||||
|
||||
return (
|
||||
<FormItemContext.Provider value={{ id }}>
|
||||
<div ref={ref} className={cn("space-y-2", className)} {...props} />
|
||||
</FormItemContext.Provider>
|
||||
)
|
||||
})
|
||||
FormItem.displayName = "FormItem"
|
||||
|
||||
const FormLabel = React.forwardRef<
|
||||
React.ElementRef<typeof LabelPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root>
|
||||
>(({ className, ...props }, ref) => {
|
||||
const { error, formItemId } = useFormField()
|
||||
|
||||
return (
|
||||
<Label
|
||||
ref={ref}
|
||||
className={cn(error && "text-destructive", className)}
|
||||
htmlFor={formItemId}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
FormLabel.displayName = "FormLabel"
|
||||
|
||||
const FormControl = React.forwardRef<
|
||||
React.ElementRef<typeof Slot>,
|
||||
React.ComponentPropsWithoutRef<typeof Slot>
|
||||
>(({ ...props }, ref) => {
|
||||
const { error, formItemId, formDescriptionId, formMessageId } = useFormField()
|
||||
|
||||
return (
|
||||
<Slot
|
||||
ref={ref}
|
||||
id={formItemId}
|
||||
aria-describedby={
|
||||
!error
|
||||
? `${formDescriptionId}`
|
||||
: `${formDescriptionId} ${formMessageId}`
|
||||
}
|
||||
aria-invalid={!!error}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
FormControl.displayName = "FormControl"
|
||||
|
||||
const FormDescription = React.forwardRef<
|
||||
HTMLParagraphElement,
|
||||
React.HTMLAttributes<HTMLParagraphElement>
|
||||
>(({ className, ...props }, ref) => {
|
||||
const { formDescriptionId } = useFormField()
|
||||
|
||||
return (
|
||||
<p
|
||||
ref={ref}
|
||||
id={formDescriptionId}
|
||||
className={cn("text-[0.8rem] text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
FormDescription.displayName = "FormDescription"
|
||||
|
||||
const FormMessage = React.forwardRef<
|
||||
HTMLParagraphElement,
|
||||
React.HTMLAttributes<HTMLParagraphElement>
|
||||
>(({ className, children, ...props }, ref) => {
|
||||
const { error, formMessageId } = useFormField()
|
||||
const body = error ? String(error?.message) : children
|
||||
|
||||
if (!body) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<p
|
||||
ref={ref}
|
||||
id={formMessageId}
|
||||
className={cn("text-[0.8rem] font-medium text-destructive", className)}
|
||||
{...props}
|
||||
>
|
||||
{body}
|
||||
</p>
|
||||
)
|
||||
})
|
||||
FormMessage.displayName = "FormMessage"
|
||||
|
||||
export {
|
||||
useFormField,
|
||||
Form,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormMessage,
|
||||
FormField,
|
||||
}
|
||||
168
src/components/ui/image-crop-modal.tsx
Normal file
168
src/components/ui/image-crop-modal.tsx
Normal file
@@ -0,0 +1,168 @@
|
||||
"use client";
|
||||
|
||||
import { Dialog, DialogContent, DialogTitle } from "./dialog";
|
||||
import { useState, useCallback } from "react";
|
||||
import Cropper, { Area } from "react-easy-crop";
|
||||
import { Button } from "./button";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { Slider } from "./slider";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "./card";
|
||||
import { Loader2 } from "lucide-react";
|
||||
|
||||
interface ImageCropModalProps {
|
||||
file: File;
|
||||
aspect?: number;
|
||||
onCrop: (blob: Blob) => void;
|
||||
onCancel: () => void;
|
||||
className?: string;
|
||||
cropBoxClassName?: string;
|
||||
overlayClassName?: string;
|
||||
}
|
||||
|
||||
export function ImageCropModal({
|
||||
file,
|
||||
aspect = 1,
|
||||
onCrop,
|
||||
onCancel,
|
||||
className,
|
||||
cropBoxClassName,
|
||||
overlayClassName,
|
||||
}: ImageCropModalProps) {
|
||||
const [crop, setCrop] = useState({ x: 0, y: 0 });
|
||||
const [zoom, setZoom] = useState(1.5);
|
||||
const [croppedAreaPixels, setCroppedAreaPixels] = useState<Area | null>(null);
|
||||
const [imageUrl] = useState(() => URL.createObjectURL(file));
|
||||
const [isCropping, setIsCropping] = useState(false);
|
||||
|
||||
const onCropComplete = useCallback((croppedArea: Area, croppedAreaPixels: Area) => {
|
||||
setCroppedAreaPixels(croppedAreaPixels);
|
||||
}, []);
|
||||
|
||||
const handleCrop = async () => {
|
||||
try {
|
||||
setIsCropping(true);
|
||||
if (!croppedAreaPixels) return;
|
||||
|
||||
const canvas = document.createElement("canvas");
|
||||
const image = new Image();
|
||||
image.src = imageUrl;
|
||||
|
||||
await new Promise((resolve) => {
|
||||
image.onload = resolve;
|
||||
});
|
||||
|
||||
const scaleX = image.naturalWidth / image.width;
|
||||
const scaleY = image.naturalHeight / image.height;
|
||||
|
||||
// Set a fixed size for the output
|
||||
const outputSize = 400;
|
||||
canvas.width = outputSize;
|
||||
canvas.height = outputSize;
|
||||
|
||||
const ctx = canvas.getContext("2d");
|
||||
if (!ctx) return;
|
||||
|
||||
ctx.imageSmoothingQuality = "high";
|
||||
ctx.drawImage(
|
||||
image,
|
||||
croppedAreaPixels.x * scaleX,
|
||||
croppedAreaPixels.y * scaleY,
|
||||
croppedAreaPixels.width * scaleX,
|
||||
croppedAreaPixels.height * scaleY,
|
||||
0,
|
||||
0,
|
||||
outputSize,
|
||||
outputSize
|
||||
);
|
||||
|
||||
canvas.toBlob(
|
||||
(blob) => {
|
||||
if (blob) {
|
||||
onCrop(blob);
|
||||
}
|
||||
},
|
||||
"image/jpeg",
|
||||
0.95
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Error cropping image:", error);
|
||||
} finally {
|
||||
setIsCropping(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open onOpenChange={() => onCancel()}>
|
||||
<DialogContent className={cn("max-h-[85vh] gap-0 p-0 sm:max-w-md", className)}>
|
||||
<div className="space-y-4 p-6 pb-4">
|
||||
<DialogTitle className="text-lg font-semibold">
|
||||
Crop Profile Picture
|
||||
</DialogTitle>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Adjust the image and zoom to crop your profile picture
|
||||
</p>
|
||||
</div>
|
||||
<div className="space-y-6 px-6">
|
||||
<div className="relative h-[280px] w-full overflow-hidden rounded-lg">
|
||||
<Cropper
|
||||
image={imageUrl}
|
||||
crop={crop}
|
||||
zoom={zoom}
|
||||
aspect={aspect}
|
||||
onCropChange={setCrop}
|
||||
onCropComplete={onCropComplete}
|
||||
onZoomChange={setZoom}
|
||||
cropShape="round"
|
||||
showGrid={false}
|
||||
objectFit="contain"
|
||||
minZoom={1}
|
||||
maxZoom={3}
|
||||
classes={{
|
||||
containerClassName: "rounded-lg",
|
||||
cropAreaClassName: cn(
|
||||
"!border-2 !border-primary !rounded-full !shadow-2xl",
|
||||
cropBoxClassName
|
||||
),
|
||||
mediaClassName: "object-contain",
|
||||
}}
|
||||
style={{
|
||||
containerStyle: {
|
||||
position: "relative",
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
backgroundColor: "var(--muted)",
|
||||
},
|
||||
cropAreaStyle: {
|
||||
color: "var(--muted-foreground)",
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<h4 className="font-medium leading-none">Zoom</h4>
|
||||
<Slider
|
||||
value={[zoom]}
|
||||
min={1}
|
||||
max={3}
|
||||
step={0.1}
|
||||
onValueChange={([value]) => setZoom(value)}
|
||||
className="py-2"
|
||||
aria-label="Zoom"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2 pb-6">
|
||||
<Button variant="outline" onClick={onCancel}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleCrop} disabled={isCropping}>
|
||||
{isCropping && (
|
||||
<Loader2 className="mr-2 size-4 animate-spin" />
|
||||
)}
|
||||
Save & Apply
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -2,16 +2,13 @@ import * as React from "react"
|
||||
|
||||
import { cn } from "~/lib/utils"
|
||||
|
||||
export interface InputProps
|
||||
extends React.InputHTMLAttributes<HTMLInputElement> {}
|
||||
|
||||
const Input = React.forwardRef<HTMLInputElement, InputProps>(
|
||||
const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>(
|
||||
({ className, type, ...props }, ref) => {
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
className={cn(
|
||||
"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
|
||||
"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
className
|
||||
)}
|
||||
ref={ref}
|
||||
|
||||
33
src/components/ui/popover.tsx
Normal file
33
src/components/ui/popover.tsx
Normal file
@@ -0,0 +1,33 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as PopoverPrimitive from "@radix-ui/react-popover"
|
||||
|
||||
import { cn } from "~/lib/utils"
|
||||
|
||||
const Popover = PopoverPrimitive.Root
|
||||
|
||||
const PopoverTrigger = PopoverPrimitive.Trigger
|
||||
|
||||
const PopoverAnchor = PopoverPrimitive.Anchor
|
||||
|
||||
const PopoverContent = React.forwardRef<
|
||||
React.ElementRef<typeof PopoverPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>
|
||||
>(({ className, align = "center", sideOffset = 4, ...props }, ref) => (
|
||||
<PopoverPrimitive.Portal>
|
||||
<PopoverPrimitive.Content
|
||||
ref={ref}
|
||||
align={align}
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none 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 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</PopoverPrimitive.Portal>
|
||||
))
|
||||
PopoverContent.displayName = PopoverPrimitive.Content.displayName
|
||||
|
||||
export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor }
|
||||
@@ -1,13 +1,8 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import {
|
||||
CaretSortIcon,
|
||||
CheckIcon,
|
||||
ChevronDownIcon,
|
||||
ChevronUpIcon,
|
||||
} from "@radix-ui/react-icons"
|
||||
import * as SelectPrimitive from "@radix-ui/react-select"
|
||||
import { Check, ChevronDown, ChevronUp } from "lucide-react"
|
||||
|
||||
import { cn } from "~/lib/utils"
|
||||
|
||||
@@ -31,7 +26,7 @@ const SelectTrigger = React.forwardRef<
|
||||
>
|
||||
{children}
|
||||
<SelectPrimitive.Icon asChild>
|
||||
<CaretSortIcon className="h-4 w-4 opacity-50" />
|
||||
<ChevronDown className="h-4 w-4 opacity-50" />
|
||||
</SelectPrimitive.Icon>
|
||||
</SelectPrimitive.Trigger>
|
||||
))
|
||||
@@ -49,7 +44,7 @@ const SelectScrollUpButton = React.forwardRef<
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronUpIcon />
|
||||
<ChevronUp className="h-4 w-4" />
|
||||
</SelectPrimitive.ScrollUpButton>
|
||||
))
|
||||
SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName
|
||||
@@ -66,7 +61,7 @@ const SelectScrollDownButton = React.forwardRef<
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronDownIcon />
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
</SelectPrimitive.ScrollDownButton>
|
||||
))
|
||||
SelectScrollDownButton.displayName =
|
||||
@@ -130,7 +125,7 @@ const SelectItem = React.forwardRef<
|
||||
>
|
||||
<span className="absolute right-2 flex h-3.5 w-3.5 items-center justify-center">
|
||||
<SelectPrimitive.ItemIndicator>
|
||||
<CheckIcon className="h-4 w-4" />
|
||||
<Check className="h-4 w-4" />
|
||||
</SelectPrimitive.ItemIndicator>
|
||||
</span>
|
||||
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
import * as React from "react"
|
||||
import * as SheetPrimitive from "@radix-ui/react-dialog"
|
||||
import { Cross2Icon } from "@radix-ui/react-icons"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { X } from "lucide-react"
|
||||
|
||||
import { cn } from "~/lib/utils"
|
||||
|
||||
@@ -65,7 +65,7 @@ const SheetContent = React.forwardRef<
|
||||
{...props}
|
||||
>
|
||||
<SheetPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary">
|
||||
<Cross2Icon className="h-4 w-4" />
|
||||
<X className="h-4 w-4" />
|
||||
<span className="sr-only">Close</span>
|
||||
</SheetPrimitive.Close>
|
||||
{children}
|
||||
|
||||
763
src/components/ui/sidebar.tsx
Normal file
763
src/components/ui/sidebar.tsx
Normal file
@@ -0,0 +1,763 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { type VariantProps, cva } from "class-variance-authority"
|
||||
import { PanelLeft } from "lucide-react"
|
||||
|
||||
import { useIsMobile } from "~/hooks/use-mobile"
|
||||
import { cn } from "~/lib/utils"
|
||||
import { Button } from "~/components/ui/button"
|
||||
import { Input } from "~/components/ui/input"
|
||||
import { Separator } from "~/components/ui/separator"
|
||||
import { Sheet, SheetContent } from "~/components/ui/sheet"
|
||||
import { Skeleton } from "~/components/ui/skeleton"
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from "~/components/ui/tooltip"
|
||||
|
||||
const SIDEBAR_COOKIE_NAME = "sidebar:state"
|
||||
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7
|
||||
const SIDEBAR_WIDTH = "16rem"
|
||||
const SIDEBAR_WIDTH_MOBILE = "18rem"
|
||||
const SIDEBAR_WIDTH_ICON = "3rem"
|
||||
const SIDEBAR_KEYBOARD_SHORTCUT = "b"
|
||||
|
||||
type SidebarContext = {
|
||||
state: "expanded" | "collapsed"
|
||||
open: boolean
|
||||
setOpen: (open: boolean) => void
|
||||
openMobile: boolean
|
||||
setOpenMobile: (open: boolean) => void
|
||||
isMobile: boolean
|
||||
toggleSidebar: () => void
|
||||
}
|
||||
|
||||
const SidebarContext = React.createContext<SidebarContext | null>(null)
|
||||
|
||||
function useSidebar() {
|
||||
const context = React.useContext(SidebarContext)
|
||||
if (!context) {
|
||||
throw new Error("useSidebar must be used within a SidebarProvider.")
|
||||
}
|
||||
|
||||
return context
|
||||
}
|
||||
|
||||
const SidebarProvider = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.ComponentProps<"div"> & {
|
||||
defaultOpen?: boolean
|
||||
open?: boolean
|
||||
onOpenChange?: (open: boolean) => void
|
||||
}
|
||||
>(
|
||||
(
|
||||
{
|
||||
defaultOpen = true,
|
||||
open: openProp,
|
||||
onOpenChange: setOpenProp,
|
||||
className,
|
||||
style,
|
||||
children,
|
||||
...props
|
||||
},
|
||||
ref
|
||||
) => {
|
||||
const isMobile = useIsMobile()
|
||||
const [openMobile, setOpenMobile] = React.useState(false)
|
||||
|
||||
// This is the internal state of the sidebar.
|
||||
// We use openProp and setOpenProp for control from outside the component.
|
||||
const [_open, _setOpen] = React.useState(defaultOpen)
|
||||
const open = openProp ?? _open
|
||||
const setOpen = React.useCallback(
|
||||
(value: boolean | ((value: boolean) => boolean)) => {
|
||||
const openState = typeof value === "function" ? value(open) : value
|
||||
if (setOpenProp) {
|
||||
setOpenProp(openState)
|
||||
} else {
|
||||
_setOpen(openState)
|
||||
}
|
||||
|
||||
// This sets the cookie to keep the sidebar state.
|
||||
document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`
|
||||
},
|
||||
[setOpenProp, open]
|
||||
)
|
||||
|
||||
// Helper to toggle the sidebar.
|
||||
const toggleSidebar = React.useCallback(() => {
|
||||
return isMobile
|
||||
? setOpenMobile((open) => !open)
|
||||
: setOpen((open) => !open)
|
||||
}, [isMobile, setOpen, setOpenMobile])
|
||||
|
||||
// Adds a keyboard shortcut to toggle the sidebar.
|
||||
React.useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (
|
||||
event.key === SIDEBAR_KEYBOARD_SHORTCUT &&
|
||||
(event.metaKey || event.ctrlKey)
|
||||
) {
|
||||
event.preventDefault()
|
||||
toggleSidebar()
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener("keydown", handleKeyDown)
|
||||
return () => window.removeEventListener("keydown", handleKeyDown)
|
||||
}, [toggleSidebar])
|
||||
|
||||
// We add a state so that we can do data-state="expanded" or "collapsed".
|
||||
// This makes it easier to style the sidebar with Tailwind classes.
|
||||
const state = open ? "expanded" : "collapsed"
|
||||
|
||||
const contextValue = React.useMemo<SidebarContext>(
|
||||
() => ({
|
||||
state,
|
||||
open,
|
||||
setOpen,
|
||||
isMobile,
|
||||
openMobile,
|
||||
setOpenMobile,
|
||||
toggleSidebar,
|
||||
}),
|
||||
[state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar]
|
||||
)
|
||||
|
||||
return (
|
||||
<SidebarContext.Provider value={contextValue}>
|
||||
<TooltipProvider delayDuration={0}>
|
||||
<div
|
||||
style={
|
||||
{
|
||||
"--sidebar-width": SIDEBAR_WIDTH,
|
||||
"--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
|
||||
...style,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
className={cn(
|
||||
"group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar",
|
||||
className
|
||||
)}
|
||||
ref={ref}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
</SidebarContext.Provider>
|
||||
)
|
||||
}
|
||||
)
|
||||
SidebarProvider.displayName = "SidebarProvider"
|
||||
|
||||
const Sidebar = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.ComponentProps<"div"> & {
|
||||
side?: "left" | "right"
|
||||
variant?: "sidebar" | "floating" | "inset"
|
||||
collapsible?: "offcanvas" | "icon" | "none"
|
||||
}
|
||||
>(
|
||||
(
|
||||
{
|
||||
side = "left",
|
||||
variant = "sidebar",
|
||||
collapsible = "offcanvas",
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
},
|
||||
ref
|
||||
) => {
|
||||
const { isMobile, state, openMobile, setOpenMobile } = useSidebar()
|
||||
|
||||
if (collapsible === "none") {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground",
|
||||
className
|
||||
)}
|
||||
ref={ref}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (isMobile) {
|
||||
return (
|
||||
<Sheet open={openMobile} onOpenChange={setOpenMobile} {...props}>
|
||||
<SheetContent
|
||||
data-sidebar="sidebar"
|
||||
data-mobile="true"
|
||||
className="w-[--sidebar-width] bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden"
|
||||
style={
|
||||
{
|
||||
"--sidebar-width": SIDEBAR_WIDTH_MOBILE,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
side={side}
|
||||
>
|
||||
<div className="flex h-full w-full flex-col">{children}</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
className="group peer hidden text-sidebar-foreground md:block"
|
||||
data-state={state}
|
||||
data-collapsible={state === "collapsed" ? collapsible : ""}
|
||||
data-variant={variant}
|
||||
data-side={side}
|
||||
>
|
||||
{/* This is what handles the sidebar gap on desktop */}
|
||||
<div
|
||||
className={cn(
|
||||
"relative h-svh w-[--sidebar-width] bg-transparent transition-[width] duration-200 ease-linear",
|
||||
"group-data-[collapsible=offcanvas]:w-0",
|
||||
"group-data-[side=right]:rotate-180",
|
||||
variant === "floating" || variant === "inset"
|
||||
? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4))]"
|
||||
: "group-data-[collapsible=icon]:w-[--sidebar-width-icon]"
|
||||
)}
|
||||
/>
|
||||
<div
|
||||
className={cn(
|
||||
"fixed inset-y-0 z-10 hidden h-svh w-[--sidebar-width] transition-[left,right,width] duration-200 ease-linear md:flex",
|
||||
side === "left"
|
||||
? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]"
|
||||
: "right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",
|
||||
// Adjust the padding for floating and inset variants.
|
||||
variant === "floating" || variant === "inset"
|
||||
? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4)_+2px)]"
|
||||
: "group-data-[collapsible=icon]:w-[--sidebar-width-icon] group-data-[side=left]:border-r group-data-[side=right]:border-l",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div
|
||||
data-sidebar="sidebar"
|
||||
className="flex h-full w-full flex-col bg-sidebar group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow"
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
)
|
||||
Sidebar.displayName = "Sidebar"
|
||||
|
||||
const SidebarTrigger = React.forwardRef<
|
||||
React.ElementRef<typeof Button>,
|
||||
React.ComponentProps<typeof Button>
|
||||
>(({ className, onClick, ...props }, ref) => {
|
||||
const { toggleSidebar } = useSidebar()
|
||||
|
||||
return (
|
||||
<Button
|
||||
ref={ref}
|
||||
data-sidebar="trigger"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className={cn("h-7 w-7", className)}
|
||||
onClick={(event) => {
|
||||
onClick?.(event)
|
||||
toggleSidebar()
|
||||
}}
|
||||
{...props}
|
||||
>
|
||||
<PanelLeft />
|
||||
<span className="sr-only">Toggle Sidebar</span>
|
||||
</Button>
|
||||
)
|
||||
})
|
||||
SidebarTrigger.displayName = "SidebarTrigger"
|
||||
|
||||
const SidebarRail = React.forwardRef<
|
||||
HTMLButtonElement,
|
||||
React.ComponentProps<"button">
|
||||
>(({ className, ...props }, ref) => {
|
||||
const { toggleSidebar } = useSidebar()
|
||||
|
||||
return (
|
||||
<button
|
||||
ref={ref}
|
||||
data-sidebar="rail"
|
||||
aria-label="Toggle Sidebar"
|
||||
tabIndex={-1}
|
||||
onClick={toggleSidebar}
|
||||
title="Toggle Sidebar"
|
||||
className={cn(
|
||||
"absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] hover:after:bg-sidebar-border group-data-[side=left]:-right-4 group-data-[side=right]:left-0 sm:flex",
|
||||
"[[data-side=left]_&]:cursor-w-resize [[data-side=right]_&]:cursor-e-resize",
|
||||
"[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
|
||||
"group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full group-data-[collapsible=offcanvas]:hover:bg-sidebar",
|
||||
"[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
|
||||
"[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
SidebarRail.displayName = "SidebarRail"
|
||||
|
||||
const SidebarInset = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.ComponentProps<"main">
|
||||
>(({ className, ...props }, ref) => {
|
||||
return (
|
||||
<main
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative flex min-h-svh flex-1 flex-col bg-background",
|
||||
"peer-data-[variant=inset]:min-h-[calc(100svh-theme(spacing.4))] md:peer-data-[variant=inset]:m-2 md:peer-data-[state=collapsed]:peer-data-[variant=inset]:ml-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
SidebarInset.displayName = "SidebarInset"
|
||||
|
||||
const SidebarInput = React.forwardRef<
|
||||
React.ElementRef<typeof Input>,
|
||||
React.ComponentProps<typeof Input>
|
||||
>(({ className, ...props }, ref) => {
|
||||
return (
|
||||
<Input
|
||||
ref={ref}
|
||||
data-sidebar="input"
|
||||
className={cn(
|
||||
"h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
SidebarInput.displayName = "SidebarInput"
|
||||
|
||||
const SidebarHeader = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.ComponentProps<"div">
|
||||
>(({ className, ...props }, ref) => {
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
data-sidebar="header"
|
||||
className={cn("flex flex-col gap-2 p-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
SidebarHeader.displayName = "SidebarHeader"
|
||||
|
||||
const SidebarFooter = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.ComponentProps<"div">
|
||||
>(({ className, ...props }, ref) => {
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
data-sidebar="footer"
|
||||
className={cn("flex flex-col gap-2 p-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
SidebarFooter.displayName = "SidebarFooter"
|
||||
|
||||
const SidebarSeparator = React.forwardRef<
|
||||
React.ElementRef<typeof Separator>,
|
||||
React.ComponentProps<typeof Separator>
|
||||
>(({ className, ...props }, ref) => {
|
||||
return (
|
||||
<Separator
|
||||
ref={ref}
|
||||
data-sidebar="separator"
|
||||
className={cn("mx-2 w-auto bg-sidebar-border", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
SidebarSeparator.displayName = "SidebarSeparator"
|
||||
|
||||
const SidebarContent = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.ComponentProps<"div">
|
||||
>(({ className, ...props }, ref) => {
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
data-sidebar="content"
|
||||
className={cn(
|
||||
"flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
SidebarContent.displayName = "SidebarContent"
|
||||
|
||||
const SidebarGroup = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.ComponentProps<"div">
|
||||
>(({ className, ...props }, ref) => {
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
data-sidebar="group"
|
||||
className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
SidebarGroup.displayName = "SidebarGroup"
|
||||
|
||||
const SidebarGroupLabel = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.ComponentProps<"div"> & { asChild?: boolean }
|
||||
>(({ className, asChild = false, ...props }, ref) => {
|
||||
const Comp = asChild ? Slot : "div"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
ref={ref}
|
||||
data-sidebar="group-label"
|
||||
className={cn(
|
||||
"flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium text-sidebar-foreground/70 outline-none ring-sidebar-ring transition-[margin,opa] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
"group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
SidebarGroupLabel.displayName = "SidebarGroupLabel"
|
||||
|
||||
const SidebarGroupAction = React.forwardRef<
|
||||
HTMLButtonElement,
|
||||
React.ComponentProps<"button"> & { asChild?: boolean }
|
||||
>(({ className, asChild = false, ...props }, ref) => {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
ref={ref}
|
||||
data-sidebar="group-action"
|
||||
className={cn(
|
||||
"absolute right-3 top-3.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
// Increases the hit area of the button on mobile.
|
||||
"after:absolute after:-inset-2 after:md:hidden",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
SidebarGroupAction.displayName = "SidebarGroupAction"
|
||||
|
||||
const SidebarGroupContent = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.ComponentProps<"div">
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
data-sidebar="group-content"
|
||||
className={cn("w-full text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
SidebarGroupContent.displayName = "SidebarGroupContent"
|
||||
|
||||
const SidebarMenu = React.forwardRef<
|
||||
HTMLUListElement,
|
||||
React.ComponentProps<"ul">
|
||||
>(({ className, ...props }, ref) => (
|
||||
<ul
|
||||
ref={ref}
|
||||
data-sidebar="menu"
|
||||
className={cn("flex w-full min-w-0 flex-col gap-1", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
SidebarMenu.displayName = "SidebarMenu"
|
||||
|
||||
const SidebarMenuItem = React.forwardRef<
|
||||
HTMLLIElement,
|
||||
React.ComponentProps<"li">
|
||||
>(({ className, ...props }, ref) => (
|
||||
<li
|
||||
ref={ref}
|
||||
data-sidebar="menu-item"
|
||||
className={cn("group/menu-item relative", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
SidebarMenuItem.displayName = "SidebarMenuItem"
|
||||
|
||||
const sidebarMenuButtonVariants = cva(
|
||||
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-none ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-[[data-sidebar=menu-action]]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:!size-8 group-data-[collapsible=icon]:!p-2 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
|
||||
outline:
|
||||
"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]",
|
||||
},
|
||||
size: {
|
||||
default: "h-8 text-sm",
|
||||
sm: "h-7 text-xs",
|
||||
lg: "h-12 text-sm group-data-[collapsible=icon]:!p-0",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
const SidebarMenuButton = React.forwardRef<
|
||||
HTMLButtonElement,
|
||||
React.ComponentProps<"button"> & {
|
||||
asChild?: boolean
|
||||
isActive?: boolean
|
||||
tooltip?: string | React.ComponentProps<typeof TooltipContent>
|
||||
} & VariantProps<typeof sidebarMenuButtonVariants>
|
||||
>(
|
||||
(
|
||||
{
|
||||
asChild = false,
|
||||
isActive = false,
|
||||
variant = "default",
|
||||
size = "default",
|
||||
tooltip,
|
||||
className,
|
||||
...props
|
||||
},
|
||||
ref
|
||||
) => {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
const { isMobile, state } = useSidebar()
|
||||
|
||||
const button = (
|
||||
<Comp
|
||||
ref={ref}
|
||||
data-sidebar="menu-button"
|
||||
data-size={size}
|
||||
data-active={isActive}
|
||||
className={cn(sidebarMenuButtonVariants({ variant, size }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
|
||||
if (!tooltip) {
|
||||
return button
|
||||
}
|
||||
|
||||
if (typeof tooltip === "string") {
|
||||
tooltip = {
|
||||
children: tooltip,
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>{button}</TooltipTrigger>
|
||||
<TooltipContent
|
||||
side="right"
|
||||
align="center"
|
||||
hidden={state !== "collapsed" || isMobile}
|
||||
{...tooltip}
|
||||
/>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
)
|
||||
SidebarMenuButton.displayName = "SidebarMenuButton"
|
||||
|
||||
const SidebarMenuAction = React.forwardRef<
|
||||
HTMLButtonElement,
|
||||
React.ComponentProps<"button"> & {
|
||||
asChild?: boolean
|
||||
showOnHover?: boolean
|
||||
}
|
||||
>(({ className, asChild = false, showOnHover = false, ...props }, ref) => {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
ref={ref}
|
||||
data-sidebar="menu-action"
|
||||
className={cn(
|
||||
"absolute right-1 top-1.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 peer-hover/menu-button:text-sidebar-accent-foreground [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
// Increases the hit area of the button on mobile.
|
||||
"after:absolute after:-inset-2 after:md:hidden",
|
||||
"peer-data-[size=sm]/menu-button:top-1",
|
||||
"peer-data-[size=default]/menu-button:top-1.5",
|
||||
"peer-data-[size=lg]/menu-button:top-2.5",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
showOnHover &&
|
||||
"group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 peer-data-[active=true]/menu-button:text-sidebar-accent-foreground md:opacity-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
SidebarMenuAction.displayName = "SidebarMenuAction"
|
||||
|
||||
const SidebarMenuBadge = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.ComponentProps<"div">
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
data-sidebar="menu-badge"
|
||||
className={cn(
|
||||
"pointer-events-none absolute right-1 flex h-5 min-w-5 select-none items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums text-sidebar-foreground",
|
||||
"peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground",
|
||||
"peer-data-[size=sm]/menu-button:top-1",
|
||||
"peer-data-[size=default]/menu-button:top-1.5",
|
||||
"peer-data-[size=lg]/menu-button:top-2.5",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
SidebarMenuBadge.displayName = "SidebarMenuBadge"
|
||||
|
||||
const SidebarMenuSkeleton = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.ComponentProps<"div"> & {
|
||||
showIcon?: boolean
|
||||
}
|
||||
>(({ className, showIcon = false, ...props }, ref) => {
|
||||
// Random width between 50 to 90%.
|
||||
const width = React.useMemo(() => {
|
||||
return `${Math.floor(Math.random() * 40) + 50}%`
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
data-sidebar="menu-skeleton"
|
||||
className={cn("flex h-8 items-center gap-2 rounded-md px-2", className)}
|
||||
{...props}
|
||||
>
|
||||
{showIcon && (
|
||||
<Skeleton
|
||||
className="size-4 rounded-md"
|
||||
data-sidebar="menu-skeleton-icon"
|
||||
/>
|
||||
)}
|
||||
<Skeleton
|
||||
className="h-4 max-w-[--skeleton-width] flex-1"
|
||||
data-sidebar="menu-skeleton-text"
|
||||
style={
|
||||
{
|
||||
"--skeleton-width": width,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
SidebarMenuSkeleton.displayName = "SidebarMenuSkeleton"
|
||||
|
||||
const SidebarMenuSub = React.forwardRef<
|
||||
HTMLUListElement,
|
||||
React.ComponentProps<"ul">
|
||||
>(({ className, ...props }, ref) => (
|
||||
<ul
|
||||
ref={ref}
|
||||
data-sidebar="menu-sub"
|
||||
className={cn(
|
||||
"mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l border-sidebar-border px-2.5 py-0.5",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
SidebarMenuSub.displayName = "SidebarMenuSub"
|
||||
|
||||
const SidebarMenuSubItem = React.forwardRef<
|
||||
HTMLLIElement,
|
||||
React.ComponentProps<"li">
|
||||
>(({ ...props }, ref) => <li ref={ref} {...props} />)
|
||||
SidebarMenuSubItem.displayName = "SidebarMenuSubItem"
|
||||
|
||||
const SidebarMenuSubButton = React.forwardRef<
|
||||
HTMLAnchorElement,
|
||||
React.ComponentProps<"a"> & {
|
||||
asChild?: boolean
|
||||
size?: "sm" | "md"
|
||||
isActive?: boolean
|
||||
}
|
||||
>(({ asChild = false, size = "md", isActive, className, ...props }, ref) => {
|
||||
const Comp = asChild ? Slot : "a"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
ref={ref}
|
||||
data-sidebar="menu-sub-button"
|
||||
data-size={size}
|
||||
data-active={isActive}
|
||||
className={cn(
|
||||
"flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground outline-none ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground",
|
||||
"data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",
|
||||
size === "sm" && "text-xs",
|
||||
size === "md" && "text-sm",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
SidebarMenuSubButton.displayName = "SidebarMenuSubButton"
|
||||
|
||||
export {
|
||||
Sidebar,
|
||||
SidebarContent,
|
||||
SidebarFooter,
|
||||
SidebarGroup,
|
||||
SidebarGroupAction,
|
||||
SidebarGroupContent,
|
||||
SidebarGroupLabel,
|
||||
SidebarHeader,
|
||||
SidebarInput,
|
||||
SidebarInset,
|
||||
SidebarMenu,
|
||||
SidebarMenuAction,
|
||||
SidebarMenuBadge,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
SidebarMenuSkeleton,
|
||||
SidebarMenuSub,
|
||||
SidebarMenuSubButton,
|
||||
SidebarMenuSubItem,
|
||||
SidebarProvider,
|
||||
SidebarRail,
|
||||
SidebarSeparator,
|
||||
SidebarTrigger,
|
||||
useSidebar,
|
||||
}
|
||||
28
src/components/ui/slider.tsx
Normal file
28
src/components/ui/slider.tsx
Normal file
@@ -0,0 +1,28 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as SliderPrimitive from "@radix-ui/react-slider"
|
||||
|
||||
import { cn } from "~/lib/utils"
|
||||
|
||||
const Slider = React.forwardRef<
|
||||
React.ElementRef<typeof SliderPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof SliderPrimitive.Root>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SliderPrimitive.Root
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative flex w-full touch-none select-none items-center",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<SliderPrimitive.Track className="relative h-1.5 w-full grow overflow-hidden rounded-full bg-primary/20">
|
||||
<SliderPrimitive.Range className="absolute h-full bg-primary" />
|
||||
</SliderPrimitive.Track>
|
||||
<SliderPrimitive.Thumb className="block h-4 w-4 rounded-full border border-primary/50 bg-background shadow transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50" />
|
||||
</SliderPrimitive.Root>
|
||||
))
|
||||
Slider.displayName = SliderPrimitive.Root.displayName
|
||||
|
||||
export { Slider }
|
||||
@@ -2,23 +2,21 @@ import * as React from "react"
|
||||
|
||||
import { cn } from "~/lib/utils"
|
||||
|
||||
export interface TextareaProps
|
||||
extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {}
|
||||
|
||||
const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
|
||||
({ className, ...props }, ref) => {
|
||||
return (
|
||||
<textarea
|
||||
className={cn(
|
||||
"flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
)
|
||||
const Textarea = React.forwardRef<
|
||||
HTMLTextAreaElement,
|
||||
React.ComponentProps<"textarea">
|
||||
>(({ className, ...props }, ref) => {
|
||||
return (
|
||||
<textarea
|
||||
className={cn(
|
||||
"flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-base shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
className
|
||||
)}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
Textarea.displayName = "Textarea"
|
||||
|
||||
export { Textarea }
|
||||
|
||||
@@ -3,8 +3,9 @@
|
||||
import * as React from "react"
|
||||
import * as ToastPrimitives from "@radix-ui/react-toast"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { X } from "lucide-react"
|
||||
|
||||
import { cn } from "~/lib/utils"
|
||||
import { Cross2Icon } from "@radix-ui/react-icons"
|
||||
|
||||
const ToastProvider = ToastPrimitives.Provider
|
||||
|
||||
@@ -82,7 +83,7 @@ const ToastClose = React.forwardRef<
|
||||
toast-close=""
|
||||
{...props}
|
||||
>
|
||||
<Cross2Icon className="h-4 w-4" />
|
||||
<X className="h-4 w-4" />
|
||||
</ToastPrimitives.Close>
|
||||
))
|
||||
ToastClose.displayName = ToastPrimitives.Close.displayName
|
||||
|
||||
32
src/components/ui/tooltip.tsx
Normal file
32
src/components/ui/tooltip.tsx
Normal file
@@ -0,0 +1,32 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as TooltipPrimitive from "@radix-ui/react-tooltip"
|
||||
|
||||
import { cn } from "~/lib/utils"
|
||||
|
||||
const TooltipProvider = TooltipPrimitive.Provider
|
||||
|
||||
const Tooltip = TooltipPrimitive.Root
|
||||
|
||||
const TooltipTrigger = TooltipPrimitive.Trigger
|
||||
|
||||
const TooltipContent = React.forwardRef<
|
||||
React.ElementRef<typeof TooltipPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>
|
||||
>(({ className, sideOffset = 4, ...props }, ref) => (
|
||||
<TooltipPrimitive.Portal>
|
||||
<TooltipPrimitive.Content
|
||||
ref={ref}
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"z-50 overflow-hidden rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</TooltipPrimitive.Portal>
|
||||
))
|
||||
TooltipContent.displayName = TooltipPrimitive.Content.displayName
|
||||
|
||||
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
|
||||
@@ -1,29 +0,0 @@
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "~/components/ui/avatar";
|
||||
|
||||
interface UserAvatarProps {
|
||||
user: {
|
||||
name?: string | null;
|
||||
email: string;
|
||||
imageUrl?: string | null;
|
||||
};
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function UserAvatar({ user, className }: UserAvatarProps) {
|
||||
function getInitials(name: string) {
|
||||
return name
|
||||
.split(' ')
|
||||
.map(part => part[0])
|
||||
.join('')
|
||||
.toUpperCase();
|
||||
}
|
||||
|
||||
const initials = user.name ? getInitials(user.name) : user.email[0].toUpperCase();
|
||||
|
||||
return (
|
||||
<Avatar className={className}>
|
||||
{user.imageUrl && <AvatarImage src={user.imageUrl} alt={user.name || user.email} />}
|
||||
<AvatarFallback>{initials}</AvatarFallback>
|
||||
</Avatar>
|
||||
);
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import React, { createContext, useContext, useState, ReactNode } from 'react';
|
||||
|
||||
interface StudyContextType {
|
||||
selectedStudyId: number | null;
|
||||
setSelectedStudyId: (id: number | null) => void;
|
||||
}
|
||||
|
||||
const StudyContext = createContext<StudyContextType | undefined>(undefined);
|
||||
|
||||
export const StudyProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
|
||||
const [selectedStudyId, setSelectedStudyId] = useState<number | null>(null);
|
||||
|
||||
return (
|
||||
<StudyContext.Provider value={{ selectedStudyId, setSelectedStudyId }}>
|
||||
{children}
|
||||
</StudyContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export const useStudy = () => {
|
||||
const context = useContext(StudyContext);
|
||||
if (!context) {
|
||||
throw new Error('useStudy must be used within a StudyProvider');
|
||||
}
|
||||
return context;
|
||||
};
|
||||
@@ -1,109 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { createContext, useContext, useEffect, useState, useCallback } from 'react';
|
||||
import { usePathname, useRouter } from 'next/navigation';
|
||||
|
||||
interface Study {
|
||||
id: number;
|
||||
title: string;
|
||||
description: string | null;
|
||||
userId: string;
|
||||
environment: string;
|
||||
createdAt: Date;
|
||||
updatedAt: Date | null;
|
||||
permissions: string[];
|
||||
}
|
||||
|
||||
interface ActiveStudyContextType {
|
||||
activeStudy: Study | null;
|
||||
setActiveStudy: (study: Study | null) => void;
|
||||
studies: Study[];
|
||||
isLoading: boolean;
|
||||
error: string | null;
|
||||
refreshStudies: () => Promise<void>;
|
||||
}
|
||||
|
||||
const ActiveStudyContext = createContext<ActiveStudyContextType | undefined>(undefined);
|
||||
|
||||
export function ActiveStudyProvider({ children }: { children: React.ReactNode }) {
|
||||
const [activeStudy, setActiveStudy] = useState<Study | null>(null);
|
||||
const [studies, setStudies] = useState<Study[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const pathname = usePathname();
|
||||
const router = useRouter();
|
||||
|
||||
const fetchStudies = useCallback(async () => {
|
||||
try {
|
||||
const response = await fetch('/api/studies', {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) throw new Error('Failed to fetch studies');
|
||||
const data = await response.json();
|
||||
|
||||
const studiesWithDates = (data.data || []).map((study: any) => ({
|
||||
...study,
|
||||
createdAt: new Date(study.createdAt),
|
||||
updatedAt: study.updatedAt ? new Date(study.updatedAt) : null,
|
||||
}));
|
||||
|
||||
setStudies(studiesWithDates);
|
||||
|
||||
if (studiesWithDates.length === 1 && !activeStudy) {
|
||||
setActiveStudy(studiesWithDates[0]);
|
||||
router.push(`/dashboard/studies/${studiesWithDates[0].id}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching studies:', error);
|
||||
setError(error instanceof Error ? error.message : 'Failed to load studies');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [router]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchStudies();
|
||||
}, [fetchStudies]);
|
||||
|
||||
useEffect(() => {
|
||||
const studyIdMatch = pathname.match(/\/dashboard\/studies\/(\d+)/);
|
||||
if (studyIdMatch) {
|
||||
const studyId = parseInt(studyIdMatch[1]);
|
||||
const study = studies.find(s => s.id === studyId);
|
||||
if (study && (!activeStudy || activeStudy.id !== study.id)) {
|
||||
setActiveStudy(study);
|
||||
}
|
||||
} else if (!pathname.includes('/studies/new')) {
|
||||
if (activeStudy) {
|
||||
setActiveStudy(null);
|
||||
}
|
||||
}
|
||||
}, [pathname, studies]);
|
||||
|
||||
const value = {
|
||||
activeStudy,
|
||||
setActiveStudy,
|
||||
studies,
|
||||
isLoading,
|
||||
error,
|
||||
refreshStudies: fetchStudies,
|
||||
};
|
||||
|
||||
return (
|
||||
<ActiveStudyContext.Provider value={value}>
|
||||
{children}
|
||||
</ActiveStudyContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useActiveStudy() {
|
||||
const context = useContext(ActiveStudyContext);
|
||||
if (context === undefined) {
|
||||
throw new Error('useActiveStudy must be used within an ActiveStudyProvider');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
import { sql } from '@vercel/postgres';
|
||||
import { config } from 'dotenv';
|
||||
|
||||
// load .env.local
|
||||
config({ path: '.env.local' });
|
||||
|
||||
async function dropAllTables() {
|
||||
try {
|
||||
// Drop tables in order considering foreign key dependencies
|
||||
await sql`
|
||||
DROP TABLE IF EXISTS
|
||||
invitations,
|
||||
user_roles,
|
||||
role_permissions,
|
||||
permissions,
|
||||
roles,
|
||||
participant,
|
||||
study,
|
||||
users
|
||||
CASCADE;
|
||||
`;
|
||||
console.log('All tables dropped successfully');
|
||||
} catch (error) {
|
||||
console.error('Error dropping tables:', error);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
dropAllTables();
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user