Reimplemented outdated code, added encryption keys for each room, added support for profile images, added friend requests via url/qr-code
This commit is contained in:
1 parent
508f17315e
commit
32e4bf8b32
58 files changed
+3270
-362
No files matched your search
@@ -0,0 +1,44 @@
|
||||
"use client";
|
||||
|
||||
export default function AuthError({
|
||||
error,
|
||||
reset,
|
||||
}: {
|
||||
error: Error & { digest?: string };
|
||||
reset: () => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex flex-1 items-center justify-center">
|
||||
<div className="flex flex-col items-center gap-4 text-center">
|
||||
<div className="flex size-12 items-center justify-center rounded-full bg-red-50">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
className="size-6 text-red-500"
|
||||
>
|
||||
<path
|
||||
fillRule="evenodd"
|
||||
d="M18 10a8 8 0 1 1-16 0 8 8 0 0 1 16 0Zm-8-5a.75.75 0 0 1 .75.75v4.5a.75.75 0 0 1-1.5 0v-4.5A.75.75 0 0 1 10 5Zm0 10a1 1 0 1 0 0-2 1 1 0 0 0 0 2Z"
|
||||
clipRule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold text-neutral-900">
|
||||
Something went wrong
|
||||
</h2>
|
||||
<p className="mt-1 text-sm text-neutral-500">
|
||||
{error.message || "An unexpected error occurred."}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={reset}
|
||||
className="rounded-lg bg-neutral-900 px-4 py-2 text-sm font-medium text-white shadow-sm transition hover:bg-neutral-800"
|
||||
>
|
||||
Try again
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { sendFriendRequest, acceptFriend } from "@/utils/friends/friends";
|
||||
import { UUID_REGEX } from "@/utils/validation";
|
||||
|
||||
export type AddFriendState = {
|
||||
success?: boolean;
|
||||
error?: string;
|
||||
} | null;
|
||||
|
||||
export async function addFriendAction(
|
||||
_prevState: AddFriendState,
|
||||
formData: FormData,
|
||||
): Promise<AddFriendState> {
|
||||
const userId = formData.get("userId");
|
||||
if (typeof userId !== "string" || !userId.trim()) {
|
||||
return { error: "User ID is required." };
|
||||
}
|
||||
|
||||
const trimmed = userId.trim();
|
||||
|
||||
if (!UUID_REGEX.test(trimmed)) {
|
||||
return { error: "Please enter a valid user ID (UUID format)." };
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await sendFriendRequest(trimmed);
|
||||
if (result === false) {
|
||||
return { error: "Could not send friend request. It may already exist." };
|
||||
}
|
||||
revalidatePath("/friends");
|
||||
return { success: true };
|
||||
} catch {
|
||||
return { error: "Something went wrong. Please try again." };
|
||||
}
|
||||
}
|
||||
|
||||
export async function acceptRequestAction(senderId: string) {
|
||||
await acceptFriend(senderId);
|
||||
revalidatePath("/friends");
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
"use client";
|
||||
|
||||
import { useActionState } from "react";
|
||||
import { addFriendAction, type AddFriendState } from "./actions";
|
||||
|
||||
const initialState: AddFriendState = null;
|
||||
|
||||
export function AddFriendForm() {
|
||||
const [state, action, pending] = useActionState(addFriendAction, initialState);
|
||||
|
||||
return (
|
||||
<form action={action} className="space-y-3">
|
||||
<label htmlFor="userId" className="block text-sm font-medium text-neutral-700">
|
||||
Add by User ID
|
||||
</label>
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
id="userId"
|
||||
name="userId"
|
||||
type="text"
|
||||
placeholder="e.g. 3b241101-e2bb-..."
|
||||
required
|
||||
className="flex-1 rounded-lg border border-neutral-300 bg-white px-3 py-2 text-sm text-neutral-900 shadow-sm placeholder:text-neutral-400 focus:border-neutral-900 focus:outline-none"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={pending}
|
||||
className="rounded-lg bg-neutral-900 px-4 py-2 text-sm font-medium text-white shadow-sm transition hover:bg-neutral-800 disabled:cursor-not-allowed disabled:bg-neutral-400"
|
||||
>
|
||||
{pending ? "Sending..." : "Add"}
|
||||
</button>
|
||||
</div>
|
||||
{state?.error && (
|
||||
<p className="text-sm text-red-600">{state.error}</p>
|
||||
)}
|
||||
{state?.success && (
|
||||
<p className="text-sm text-emerald-600">Friend request sent!</p>
|
||||
)}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
import { createClient } from "@/utils/supabase/server";
|
||||
import { redirect } from "next/navigation";
|
||||
import { sendFriendRequest } from "@/utils/friends/friends";
|
||||
import { UUID_REGEX } from "@/utils/validation";
|
||||
import Link from "next/link";
|
||||
|
||||
type ResultStatus = "success" | "already_friends" | "error";
|
||||
|
||||
export default async function AddFriendPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{ id?: string }>;
|
||||
}) {
|
||||
const { id } = await searchParams;
|
||||
|
||||
// Validate the ID parameter
|
||||
if (!id || !UUID_REGEX.test(id)) {
|
||||
return (
|
||||
<div className="mx-auto max-w-3xl px-6 py-10">
|
||||
<ResultCard
|
||||
status="error"
|
||||
message="Invalid or missing user ID in the link."
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const supabase = await createClient();
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser();
|
||||
|
||||
// Must be authenticated — redirect to login with return URL
|
||||
if (!user) {
|
||||
redirect(`/login?next=%2Ffriends%2Fadd%3Fid%3D${id}`);
|
||||
}
|
||||
|
||||
// Can't add yourself
|
||||
if (user.id === id) {
|
||||
return (
|
||||
<div className="mx-auto max-w-3xl px-6 py-10">
|
||||
<ResultCard
|
||||
status="error"
|
||||
message="You can't send yourself a friend request."
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Look up the target user
|
||||
const { data: targetUser } = await supabase
|
||||
.from("users")
|
||||
.select("id, name")
|
||||
.eq("id", id)
|
||||
.single();
|
||||
|
||||
if (!targetUser) {
|
||||
return (
|
||||
<div className="mx-auto max-w-3xl px-6 py-10">
|
||||
<ResultCard status="error" message="User not found." />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Check if already friends
|
||||
const { data: existing } = await supabase
|
||||
.from("friends")
|
||||
.select("user_id")
|
||||
.eq("user_id", user.id)
|
||||
.eq("friend_id", id)
|
||||
.maybeSingle();
|
||||
|
||||
if (existing) {
|
||||
return (
|
||||
<div className="mx-auto max-w-3xl px-6 py-10">
|
||||
<ResultCard
|
||||
status="already_friends"
|
||||
message={`You are already friends with ${targetUser.name}.`}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Send the friend request
|
||||
let status: ResultStatus;
|
||||
let message: string;
|
||||
|
||||
try {
|
||||
const sent = await sendFriendRequest(id);
|
||||
if (sent === false) {
|
||||
status = "error";
|
||||
message =
|
||||
"Could not send friend request. It may already exist.";
|
||||
} else {
|
||||
status = "success";
|
||||
message = `Friend request sent to ${targetUser.name}!`;
|
||||
}
|
||||
} catch {
|
||||
status = "error";
|
||||
message = "Something went wrong. Please try again.";
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-3xl px-6 py-10">
|
||||
<ResultCard status={status} message={message} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ResultCard({
|
||||
status,
|
||||
message,
|
||||
}: {
|
||||
status: ResultStatus;
|
||||
message: string;
|
||||
}) {
|
||||
const isSuccess = status === "success";
|
||||
const isAlreadyFriends = status === "already_friends";
|
||||
|
||||
return (
|
||||
<div className="rounded-xl border border-neutral-200 bg-white p-8 shadow-sm">
|
||||
<div className="flex flex-col items-center text-center">
|
||||
<div
|
||||
className={`flex size-12 items-center justify-center rounded-full ${
|
||||
isSuccess
|
||||
? "bg-emerald-100"
|
||||
: isAlreadyFriends
|
||||
? "bg-blue-100"
|
||||
: "bg-red-100"
|
||||
}`}
|
||||
>
|
||||
{isSuccess ? (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
className="size-6 text-emerald-600"
|
||||
>
|
||||
<path d="M10 8a3 3 0 1 0 0-6 3 3 0 0 0 0 6ZM3.465 14.493a1.23 1.23 0 0 0 .41 1.412A9.957 9.957 0 0 0 10 18c2.31 0 4.438-.784 6.131-2.1.43-.333.604-.903.408-1.41a7.002 7.002 0 0 0-13.074.003Z" />
|
||||
</svg>
|
||||
) : isAlreadyFriends ? (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
className="size-6 text-blue-600"
|
||||
>
|
||||
<path d="M10 9a3 3 0 1 0 0-6 3 3 0 0 0 0 6ZM6 8a2 2 0 1 1-4 0 2 2 0 0 1 4 0ZM1.49 15.326a.75.75 0 0 0 .41.18 9.957 9.957 0 0 0 2.1.196 9.957 9.957 0 0 0 2.1-.196.75.75 0 0 0 .41-.18 7.002 7.002 0 0 0-5.02 0ZM16.9 15.326a7.002 7.002 0 0 1-5.02 0 .75.75 0 0 1 .41.18 9.957 9.957 0 0 0 4.2 0 .75.75 0 0 1 .41-.18ZM18 8a2 2 0 1 1-4 0 2 2 0 0 1 4 0ZM5.304 16.255A7.025 7.025 0 0 0 10 17.5c1.792 0 3.44-.672 4.696-1.783A5.98 5.98 0 0 0 10 15a5.98 5.98 0 0 0-4.696 1.255Z" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
className="size-6 text-red-600"
|
||||
>
|
||||
<path
|
||||
fillRule="evenodd"
|
||||
d="M18 10a8 8 0 1 1-16 0 8 8 0 0 1 16 0Zm-8-5a.75.75 0 0 1 .75.75v4.5a.75.75 0 0 1-1.5 0v-4.5A.75.75 0 0 1 10 5Zm0 10a1 1 0 1 0 0-2 1 1 0 0 0 0 2Z"
|
||||
clipRule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<h1 className="mt-4 text-lg font-semibold text-neutral-900">
|
||||
{isSuccess
|
||||
? "Request Sent!"
|
||||
: isAlreadyFriends
|
||||
? "Already Friends"
|
||||
: "Something went wrong"}
|
||||
</h1>
|
||||
<p className="mt-2 text-sm text-neutral-600">{message}</p>
|
||||
|
||||
<div className="mt-6 flex gap-3">
|
||||
<Link
|
||||
href="/friends"
|
||||
className="rounded-lg bg-neutral-900 px-4 py-2 text-sm font-medium text-white shadow-sm transition hover:bg-neutral-800"
|
||||
>
|
||||
Back to Friends
|
||||
</Link>
|
||||
<Link
|
||||
href="/rooms"
|
||||
className="rounded-lg border border-neutral-300 px-4 py-2 text-sm font-medium text-neutral-700 transition hover:bg-neutral-50"
|
||||
>
|
||||
Go to Rooms
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import Image from "next/image";
|
||||
|
||||
export interface FriendEntry {
|
||||
friend_id: string;
|
||||
friend_alias: string;
|
||||
avatar_url: string | null;
|
||||
}
|
||||
|
||||
export function FriendsList({ friends }: { friends: FriendEntry[] }) {
|
||||
if (friends.length === 0) {
|
||||
return (
|
||||
<div className="flex flex-col items-center rounded-xl border border-dashed border-neutral-300 py-12">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth={1}
|
||||
className="size-10 text-neutral-300"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M15 19.128a9.38 9.38 0 0 0 2.625.372 9.337 9.337 0 0 0 4.121-.952 4.125 4.125 0 0 0-7.533-2.493M15 19.128v-.003c0-1.113-.285-2.16-.786-3.07M15 19.128v.106A12.318 12.318 0 0 1 8.624 21c-2.331 0-4.512-.645-6.374-1.766l-.001-.109a6.375 6.375 0 0 1 11.964-3.07M12 6.375a3.375 3.375 0 1 1-6.75 0 3.375 3.375 0 0 1 6.75 0Zm8.25 2.25a2.625 2.625 0 1 1-5.25 0 2.625 2.625 0 0 1 5.25 0Z"
|
||||
/>
|
||||
</svg>
|
||||
<p className="mt-3 text-sm text-neutral-400">No friends yet</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h2 className="text-sm font-semibold text-neutral-900">
|
||||
Friends
|
||||
<span className="ml-2 text-xs font-normal text-neutral-500">
|
||||
{friends.length}
|
||||
</span>
|
||||
</h2>
|
||||
<ul className="mt-3 divide-y divide-neutral-100 rounded-xl border border-neutral-200 bg-white">
|
||||
{friends.map((friend) => (
|
||||
<li
|
||||
key={friend.friend_id}
|
||||
className="flex items-center gap-3 px-4 py-3"
|
||||
>
|
||||
{friend.avatar_url ? (
|
||||
<Image
|
||||
src={friend.avatar_url}
|
||||
alt=""
|
||||
width={200}
|
||||
height={200}
|
||||
className="size-16 rounded-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex size-8 items-center justify-center rounded-full bg-neutral-100 text-xs font-medium text-neutral-600">
|
||||
{friend.friend_alias.charAt(0).toUpperCase()}
|
||||
</div>
|
||||
)}
|
||||
<span className="text-sm font-medium text-neutral-900">
|
||||
{friend.friend_alias} - {friend.friend_id}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { createClient } from "@/utils/supabase/server";
|
||||
import { listFriends, listRequests } from "@/utils/friends/friends";
|
||||
import { AddFriendForm } from "./add-friend-form";
|
||||
import { RequestsList, type FriendRequest } from "./requests-list";
|
||||
import { FriendsList, type FriendEntry } from "./friends-list";
|
||||
|
||||
export default async function FriendsPage() {
|
||||
const supabase = await createClient();
|
||||
|
||||
// Fetch incoming friend requests with sender names
|
||||
const rawRequests = await listRequests();
|
||||
let requests: FriendRequest[] = [];
|
||||
|
||||
if (rawRequests && rawRequests.length > 0) {
|
||||
const senderIds = rawRequests.map((r) => r.sender_id);
|
||||
const { data: senders } = await supabase
|
||||
.from("users")
|
||||
.select("id, name")
|
||||
.in("id", senderIds);
|
||||
|
||||
const senderMap = new Map(senders?.map((s) => [s.id, s.name]));
|
||||
|
||||
requests = rawRequests.map((r) => ({
|
||||
id: r.id,
|
||||
sender_id: r.sender_id,
|
||||
sender_name: senderMap.get(r.sender_id) ?? "Unknown",
|
||||
}));
|
||||
}
|
||||
|
||||
// Fetch friends list
|
||||
const rawFriends = await listFriends();
|
||||
const friends: FriendEntry[] = rawFriends ?? [];
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-3xl px-6 py-10">
|
||||
<h1 className="text-2xl font-semibold text-neutral-900">Friends</h1>
|
||||
<p className="mt-1 text-sm text-neutral-500">
|
||||
Manage your friends and requests.
|
||||
</p>
|
||||
|
||||
<div className="mt-8 space-y-8">
|
||||
{/* Add friend */}
|
||||
<div className="rounded-xl border border-neutral-200 bg-white p-5 shadow-sm">
|
||||
<AddFriendForm />
|
||||
</div>
|
||||
|
||||
{/* Incoming requests */}
|
||||
<RequestsList requests={requests} />
|
||||
|
||||
{/* Friends list */}
|
||||
<FriendsList friends={friends} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
"use client";
|
||||
|
||||
import { useTransition } from "react";
|
||||
import { acceptRequestAction } from "./actions";
|
||||
|
||||
export interface FriendRequest {
|
||||
id: string;
|
||||
sender_id: string;
|
||||
sender_name: string;
|
||||
}
|
||||
|
||||
export function RequestsList({ requests }: { requests: FriendRequest[] }) {
|
||||
if (requests.length === 0) return null;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h2 className="text-sm font-semibold text-neutral-900">
|
||||
Incoming Requests
|
||||
<span className="ml-2 inline-flex size-5 items-center justify-center rounded-full bg-neutral-900 text-xs text-white">
|
||||
{requests.length}
|
||||
</span>
|
||||
</h2>
|
||||
<ul className="mt-3 divide-y divide-neutral-100 rounded-xl border border-neutral-200 bg-white">
|
||||
{requests.map((req) => (
|
||||
<RequestItem key={req.id} req={req} />
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function RequestItem({ req }: { req: FriendRequest }) {
|
||||
const [pending, startTransition] = useTransition();
|
||||
|
||||
return (
|
||||
<li className="flex items-center justify-between px-4 py-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex size-8 items-center justify-center rounded-full bg-neutral-100 text-xs font-medium text-neutral-600">
|
||||
{req.sender_name.charAt(0).toUpperCase()}
|
||||
</div>
|
||||
<span className="text-sm font-medium text-neutral-900">
|
||||
{req.sender_name}
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
disabled={pending}
|
||||
onClick={() => startTransition(() => acceptRequestAction(req.sender_id))}
|
||||
className="rounded-lg bg-neutral-900 px-3 py-1.5 text-xs font-medium text-white transition hover:bg-neutral-800 disabled:cursor-not-allowed disabled:bg-neutral-400"
|
||||
>
|
||||
{pending ? "Accepting..." : "Accept"}
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { createClient } from "@/utils/supabase/server";
|
||||
import { Sidebar } from "./sidebar";
|
||||
import { getSignedAvatarUrl } from "@/utils/assets/avatars";
|
||||
|
||||
export default async function AuthLayout({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const supabase = await createClient();
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser();
|
||||
|
||||
let displayName = "User";
|
||||
let avatarURL = "";
|
||||
|
||||
if (user) {
|
||||
const { data } = await supabase
|
||||
.from("users")
|
||||
.select("name, id, avatar_url")
|
||||
.eq("id", user.id)
|
||||
.single();
|
||||
if (data?.name) displayName = data.name;
|
||||
if (data?.id) {
|
||||
const fetchedAvatarUrl = await getSignedAvatarUrl(data.id);
|
||||
if (fetchedAvatarUrl) {
|
||||
avatarURL = fetchedAvatarUrl;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-screen bg-neutral-50">
|
||||
<Sidebar
|
||||
displayName={displayName}
|
||||
email={user?.email ?? ""}
|
||||
avatarUrl={avatarURL}
|
||||
/>
|
||||
<main className="flex-1 overflow-y-auto">{children}</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
export default function AuthLoading() {
|
||||
return (
|
||||
<div className="flex flex-1 items-center justify-center">
|
||||
<div className="flex flex-col items-center gap-3">
|
||||
<div className="size-8 animate-spin rounded-full border-2 border-neutral-300 border-t-neutral-900" />
|
||||
<p className="text-sm text-neutral-500">Loading...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { createClient } from "@/utils/supabase/server";
|
||||
|
||||
export type UpdateNameState = { error: string } | { success: true } | null;
|
||||
|
||||
export async function updateNameAction(
|
||||
_prevState: UpdateNameState,
|
||||
formData: FormData,
|
||||
): Promise<UpdateNameState> {
|
||||
const name = formData.get("name");
|
||||
if (typeof name !== "string" || !name.trim()) {
|
||||
return { error: "Name cannot be empty." };
|
||||
}
|
||||
|
||||
const trimmed = name.trim();
|
||||
if (trimmed.length > 50) {
|
||||
return { error: "Name must be 50 characters or less." };
|
||||
}
|
||||
|
||||
const supabase = await createClient();
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser();
|
||||
if (!user) return { error: "Not authenticated" };
|
||||
|
||||
const { error } = await supabase
|
||||
.from("users")
|
||||
.update({ name: trimmed })
|
||||
.eq("id", user.id);
|
||||
|
||||
if (error) {
|
||||
return { error: error.message };
|
||||
}
|
||||
|
||||
// Update friend_alias in all friends rows where this user is the friend
|
||||
// so that other users see the new display name
|
||||
await supabase
|
||||
.from("friends")
|
||||
.update({ friend_alias: trimmed })
|
||||
.eq("friend_id", user.id);
|
||||
|
||||
revalidatePath("/profile");
|
||||
revalidatePath("/friends");
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
export type UploadAvatarState = { error: string } | { success: true } | null;
|
||||
|
||||
export async function uploadAvatarAction(
|
||||
_prevState: UploadAvatarState,
|
||||
formData: FormData,
|
||||
): Promise<UploadAvatarState> {
|
||||
const file = formData.get("avatar");
|
||||
if (!(file instanceof File) || file.size === 0) {
|
||||
return { error: "Please select an image file." };
|
||||
}
|
||||
|
||||
// Validate file type
|
||||
if (file.type !== "image/png" && file.type !== "image/jpeg") {
|
||||
return { error: "Only PNG and JPG images are allowed." };
|
||||
}
|
||||
|
||||
// Validate file size (2MB)
|
||||
if (file.size > 2 * 1024 * 1024) {
|
||||
return { error: "Image must be smaller than 2MB." };
|
||||
}
|
||||
|
||||
const supabase = await createClient();
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser();
|
||||
if (!user) return { error: "Not authenticated" };
|
||||
|
||||
const arrayBuffer = await file.arrayBuffer();
|
||||
const filePath = `${user.id}/avatar`;
|
||||
|
||||
const { error: uploadError } = await supabase.storage
|
||||
.from("avatars")
|
||||
.upload(filePath, arrayBuffer, {
|
||||
contentType: file.type,
|
||||
upsert: true,
|
||||
});
|
||||
|
||||
if (uploadError) {
|
||||
return { error: uploadError.message };
|
||||
}
|
||||
|
||||
// Store the storage path — signed URLs are generated on read
|
||||
const avatarPath = filePath;
|
||||
|
||||
// Update user's avatar_url with the storage path
|
||||
const { error: updateError } = await supabase
|
||||
.from("users")
|
||||
.update({ avatar_url: avatarPath })
|
||||
.eq("id", user.id);
|
||||
|
||||
if (updateError) {
|
||||
return { error: updateError.message };
|
||||
}
|
||||
|
||||
revalidatePath("/profile");
|
||||
revalidatePath("/friends");
|
||||
revalidatePath("/rooms");
|
||||
return { success: true };
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
"use client";
|
||||
|
||||
import { useActionState, useRef } from "react";
|
||||
import { uploadAvatarAction, type UploadAvatarState } from "./actions";
|
||||
import Image from "next/image";
|
||||
|
||||
const initialState: UploadAvatarState = null;
|
||||
|
||||
export function AvatarUpload({ avatarUrl }: { avatarUrl: string | null }) {
|
||||
const [state, action, pending] = useActionState(
|
||||
uploadAvatarAction,
|
||||
initialState,
|
||||
);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const handleClick = () => {
|
||||
inputRef.current?.click();
|
||||
};
|
||||
|
||||
const handleChange = () => {
|
||||
const file = inputRef.current?.files?.[0];
|
||||
if (!file) return;
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append("avatar", file);
|
||||
|
||||
// Submit via the form's requestSubmit to trigger the action
|
||||
const form = inputRef.current?.closest("form");
|
||||
if (form) {
|
||||
form.requestSubmit();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<form action={action} className="inline-block">
|
||||
<input
|
||||
ref={inputRef}
|
||||
name="avatar"
|
||||
type="file"
|
||||
accept="image/png,image/jpeg,image/jpg"
|
||||
className="hidden"
|
||||
onChange={handleChange}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleClick}
|
||||
disabled={pending}
|
||||
className="group relative"
|
||||
>
|
||||
{avatarUrl ? (
|
||||
<Image
|
||||
src={avatarUrl}
|
||||
alt=""
|
||||
width={200}
|
||||
height={200}
|
||||
className="size-20 rounded-full border-4 border-white object-cover shadow-md transition group-hover:opacity-80"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex size-20 items-center justify-center rounded-full border-4 border-white bg-neutral-900 text-2xl font-semibold text-white shadow-md transition group-hover:bg-neutral-700">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
className="size-6"
|
||||
>
|
||||
<path d="M10 8a3 3 0 1 0 0-6 3 3 0 0 0 0 6ZM3.465 14.493a1.23 1.23 0 0 0 .41 1.412A9.957 9.957 0 0 0 10 18c2.31 0 4.438-.784 6.131-2.1.43-.333.604-.903.408-1.41a7.002 7.002 0 0 0-13.074.003Z" />
|
||||
</svg>
|
||||
</div>
|
||||
)}
|
||||
{pending && (
|
||||
<div className="absolute inset-0 flex items-center justify-center rounded-full bg-black/30">
|
||||
<div className="size-5 animate-spin rounded-full border-2 border-white border-t-transparent" />
|
||||
</div>
|
||||
)}
|
||||
</button>
|
||||
{state && "error" in state && (
|
||||
<p className="mt-2 text-center text-xs text-red-600">{state.error}</p>
|
||||
)}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
useActionState,
|
||||
useRef,
|
||||
useEffect,
|
||||
useState,
|
||||
useCallback,
|
||||
} from "react";
|
||||
import { updateNameAction, type UpdateNameState } from "./actions";
|
||||
|
||||
const initialState: UpdateNameState = null;
|
||||
|
||||
export function EditableName({ currentName }: { currentName: string }) {
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [state, action, pending] = useActionState(
|
||||
updateNameAction,
|
||||
initialState,
|
||||
);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
// Focus input when entering edit mode
|
||||
useEffect(() => {
|
||||
if (editing) {
|
||||
inputRef.current?.focus();
|
||||
inputRef.current?.select();
|
||||
}
|
||||
}, [editing]);
|
||||
|
||||
const handleEdit = useCallback(() => setEditing(true), []);
|
||||
|
||||
if (!editing) {
|
||||
return (
|
||||
<div className="mt-3 flex items-center gap-3">
|
||||
<h2 className="text-xl font-semibold text-neutral-900">
|
||||
{currentName}
|
||||
</h2>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleEdit}
|
||||
className="rounded-md px-2 py-1 text-xs font-medium text-neutral-500 transition hover:bg-neutral-100 hover:text-neutral-900"
|
||||
>
|
||||
Edit
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<form action={action} className="mt-3">
|
||||
<div className="flex items-start gap-2">
|
||||
<input
|
||||
ref={inputRef}
|
||||
name="name"
|
||||
type="text"
|
||||
defaultValue={currentName}
|
||||
required
|
||||
maxLength={50}
|
||||
className="w-64 rounded-lg border border-neutral-300 bg-white px-3 py-1.5 text-lg font-semibold text-neutral-900 shadow-sm focus:border-neutral-900 focus:outline-none"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={pending}
|
||||
className="rounded-lg bg-neutral-900 px-3 py-1.5 text-sm font-medium text-white shadow-sm transition hover:bg-neutral-800 disabled:cursor-not-allowed disabled:bg-neutral-400"
|
||||
>
|
||||
{pending ? "..." : "Save"}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setEditing(false)}
|
||||
className="rounded-lg border border-neutral-300 px-3 py-1.5 text-sm font-medium text-neutral-700 transition hover:bg-neutral-50"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
{state && "error" in state && (
|
||||
<p className="mt-1 text-xs text-red-600">{state.error}</p>
|
||||
)}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
import { createClient } from "@/utils/supabase/server";
|
||||
import { redirect } from "next/navigation";
|
||||
import { headers } from "next/headers";
|
||||
import type { Profile } from "@/types/profile";
|
||||
import { getSignedAvatarUrl } from "@/utils/assets/avatars";
|
||||
import { EditableName } from "./editable-name";
|
||||
import { ShareProfileButton } from "./share-profile";
|
||||
import { AvatarUpload } from "./avatar-upload";
|
||||
|
||||
export default async function ProfilePage() {
|
||||
const supabase = await createClient();
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser();
|
||||
|
||||
if (!user) return redirect("/login");
|
||||
|
||||
const { data: profile } = await supabase
|
||||
.from("users")
|
||||
.select("*")
|
||||
.eq("id", user.id)
|
||||
.single<Profile>();
|
||||
|
||||
if (!profile) {
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center">
|
||||
<p className="text-neutral-500">Profile not found.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Generate a signed URL for the user's own avatar
|
||||
const avatarUrl = profile.avatar_url
|
||||
? await getSignedAvatarUrl(profile.id)
|
||||
: null;
|
||||
|
||||
const memberSince = new Date(profile.created_at).toLocaleDateString("en-US", {
|
||||
year: "numeric",
|
||||
month: "long",
|
||||
day: "numeric",
|
||||
});
|
||||
|
||||
// Build the full share URL for the QR code
|
||||
const requestHeaders = await headers();
|
||||
const host = requestHeaders.get("host") ?? "localhost:3000";
|
||||
const protocol = requestHeaders.get("x-forwarded-proto") ?? "https";
|
||||
const basePath = process.env.BASE_PATH ?? "";
|
||||
const shareUrl = `${protocol}://${host}${basePath}/friends/add?id=${profile.id}`;
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-3xl px-6 py-10">
|
||||
{/* Header */}
|
||||
<h1 className="text-2xl font-semibold text-neutral-900">Profile</h1>
|
||||
<p className="mt-1 text-sm text-neutral-500">
|
||||
Manage your account information.
|
||||
</p>
|
||||
|
||||
{/* Profile Card */}
|
||||
<div className="mt-8 rounded-xl border border-neutral-200 bg-white shadow-sm">
|
||||
{/* Banner area */}
|
||||
<div className="h-28 rounded-t-xl bg-linear-to-br from-neutral-800 to-neutral-600" />
|
||||
|
||||
{/* Avatar + name */}
|
||||
<div className="relative px-6 pb-6">
|
||||
<AvatarUpload avatarUrl={avatarUrl} />
|
||||
|
||||
<EditableName key={profile.name} currentName={profile.name} />
|
||||
<div className="mt-3 flex items-center gap-3">
|
||||
<p className="text-sm text-neutral-500">{profile.email}</p>
|
||||
<ShareProfileButton userId={profile.id} shareUrl={shareUrl} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Details */}
|
||||
<div className="mt-6 space-y-4">
|
||||
<div className="rounded-xl border border-neutral-200 bg-white shadow-sm">
|
||||
<div className="border-b border-neutral-100 px-6 py-4">
|
||||
<h3 className="text-sm font-semibold text-neutral-900">
|
||||
Account Details
|
||||
</h3>
|
||||
</div>
|
||||
<dl className="divide-y divide-neutral-100">
|
||||
<DetailRow label="User ID" value={profile.id} mono />
|
||||
<DetailRow label="Display Name" value={profile.name} />
|
||||
<DetailRow label="Email" value={profile.email} />
|
||||
<DetailRow label="Member Since" value={memberSince} />
|
||||
<DetailRow
|
||||
label="Identity Verified"
|
||||
value={profile.has_identity ? "Yes" : "No"}
|
||||
badge={profile.has_identity ? "green" : "yellow"}
|
||||
/>
|
||||
<DetailRow
|
||||
label="Encryption Keys"
|
||||
value={
|
||||
profile.private_key_enc && profile.public_key_dec
|
||||
? "Set up"
|
||||
: "Not configured"
|
||||
}
|
||||
badge={
|
||||
profile.private_key_enc && profile.public_key_dec
|
||||
? "green"
|
||||
: "yellow"
|
||||
}
|
||||
/>
|
||||
</dl>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DetailRow({
|
||||
label,
|
||||
value,
|
||||
mono,
|
||||
badge,
|
||||
}: {
|
||||
label: string;
|
||||
value: string;
|
||||
mono?: boolean;
|
||||
badge?: "green" | "yellow";
|
||||
}) {
|
||||
return (
|
||||
<div className="flex items-center justify-between px-6 py-3.5">
|
||||
<dt className="text-sm text-neutral-500">{label}</dt>
|
||||
<dd>
|
||||
{badge ? (
|
||||
<span
|
||||
className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${
|
||||
badge === "green"
|
||||
? "bg-emerald-50 text-emerald-700"
|
||||
: "bg-amber-50 text-amber-700"
|
||||
}`}
|
||||
>
|
||||
{value}
|
||||
</span>
|
||||
) : (
|
||||
<span
|
||||
className={`text-sm text-neutral-900 ${mono ? "font-mono text-xs" : ""}`}
|
||||
>
|
||||
{value}
|
||||
</span>
|
||||
)}
|
||||
</dd>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useCallback } from "react";
|
||||
import { QRCodeSVG } from "qrcode.react";
|
||||
|
||||
export function ShareProfileButton({ userId, shareUrl }: { userId: string; shareUrl: string }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [copied, setCopied] = useState(false);
|
||||
|
||||
const handleCopy = useCallback(() => {
|
||||
navigator.clipboard.writeText(shareUrl).then(() => {
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
});
|
||||
}, [shareUrl]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen(true)}
|
||||
className="rounded-lg bg-neutral-900 px-4 py-2 text-sm font-medium text-white shadow-sm transition hover:bg-neutral-800"
|
||||
>
|
||||
Share Profile
|
||||
</button>
|
||||
|
||||
{open && (
|
||||
<>
|
||||
{/* Backdrop */}
|
||||
<div
|
||||
className="fixed inset-0 z-40 bg-black/40"
|
||||
onClick={() => setOpen(false)}
|
||||
/>
|
||||
|
||||
{/* Modal */}
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center p-4">
|
||||
<div className="w-full max-w-sm rounded-2xl border border-neutral-200 bg-white p-6 shadow-xl">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-lg font-semibold text-neutral-900">
|
||||
Share Profile
|
||||
</h2>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen(false)}
|
||||
className="flex size-8 items-center justify-center rounded-lg text-neutral-400 transition hover:bg-neutral-100 hover:text-neutral-600"
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
className="size-5"
|
||||
>
|
||||
<path d="M6.28 5.22a.75.75 0 0 0-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 1 0 1.06 1.06L10 11.06l3.72 3.72a.75.75 0 1 0 1.06-1.06L11.06 10l3.72-3.72a.75.75 0 0 0-1.06-1.06L10 8.94 6.28 5.22Z" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<p className="mt-2 text-sm text-neutral-500">
|
||||
Scan this QR code or share the link to add you as a friend.
|
||||
</p>
|
||||
|
||||
{/* QR Code */}
|
||||
<div className="mt-5 flex justify-center rounded-xl border border-neutral-100 bg-white p-4">
|
||||
<QRCodeSVG
|
||||
value={shareUrl}
|
||||
size={200}
|
||||
level="M"
|
||||
includeMargin={false}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Link + Copy */}
|
||||
<div className="mt-4 flex items-center gap-2">
|
||||
<input
|
||||
type="text"
|
||||
readOnly
|
||||
value={shareUrl}
|
||||
className="flex-1 rounded-lg border border-neutral-200 bg-neutral-50 px-3 py-2 text-xs font-mono text-neutral-600 focus:outline-none"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleCopy}
|
||||
className="shrink-0 rounded-lg border border-neutral-200 px-3 py-2 text-xs font-medium text-neutral-700 transition hover:bg-neutral-100"
|
||||
>
|
||||
{copied ? "Copied!" : "Copy"}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* User ID reference */}
|
||||
<p className="mt-3 text-center text-xs text-neutral-400">
|
||||
User ID: {userId}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { sendMessage, decryptIncomingMessage } from "@/utils/rooms/messages";
|
||||
|
||||
export type SendMessageState = { error: string } | { messageId: string } | null;
|
||||
|
||||
export async function sendMessageAction(
|
||||
roomId: string,
|
||||
_prevState: SendMessageState,
|
||||
formData: FormData,
|
||||
): Promise<SendMessageState> {
|
||||
const value = formData.get("message");
|
||||
if (typeof value !== "string" || !value.trim()) {
|
||||
return { error: "Message cannot be empty." };
|
||||
}
|
||||
|
||||
const result = await sendMessage(roomId, value.trim());
|
||||
if (result.error) {
|
||||
return { error: result.error };
|
||||
}
|
||||
|
||||
revalidatePath(`/rooms/${roomId}`);
|
||||
return { messageId: result.messageId };
|
||||
}
|
||||
|
||||
export async function decryptMessageAction(
|
||||
roomId: string,
|
||||
encryptedValue: string,
|
||||
iv: string,
|
||||
authTag: string,
|
||||
): Promise<{ plaintext: string } | { error: string }> {
|
||||
return decryptIncomingMessage(roomId, encryptedValue, iv, authTag);
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
useActionState,
|
||||
useRef,
|
||||
useEffect,
|
||||
useState,
|
||||
useCallback,
|
||||
useMemo,
|
||||
} from "react";
|
||||
import Image from "next/image";
|
||||
import { createClient } from "@/utils/supabase/client";
|
||||
import type { Message } from "@/types/chat";
|
||||
import {
|
||||
sendMessageAction,
|
||||
decryptMessageAction,
|
||||
type SendMessageState,
|
||||
} from "./actions";
|
||||
import type { MemberInfo } from "./member-map";
|
||||
|
||||
const initialState: SendMessageState = null;
|
||||
|
||||
// Prefix for temporary optimistic IDs
|
||||
const OPTIMISTIC_PREFIX = "optimistic-";
|
||||
|
||||
export function Chat({
|
||||
roomId,
|
||||
initialMessages,
|
||||
currentUserId,
|
||||
memberMap,
|
||||
}: {
|
||||
roomId: string;
|
||||
initialMessages: Message[];
|
||||
currentUserId: string;
|
||||
memberMap: Map<string, MemberInfo>;
|
||||
}) {
|
||||
const boundAction = sendMessageAction.bind(null, roomId);
|
||||
const [state, action, pending] = useActionState(boundAction, initialState);
|
||||
const formRef = useRef<HTMLFormElement>(null);
|
||||
const bottomRef = useRef<HTMLDivElement>(null);
|
||||
const optimisticCounter = useRef(0);
|
||||
|
||||
const [localMessages, setLocalMessages] = useState<Message[]>([]);
|
||||
|
||||
// Merge server messages (prop) with local messages (optimistic + realtime)
|
||||
// Server messages that match local optimistic ones by user+value are replaced
|
||||
// by the local version (which may have a real ID from realtime confirmation)
|
||||
const messages = useMemo(() => {
|
||||
const serverIds = new Set(initialMessages.map((m) => m.id));
|
||||
const optimisticConfirmed = new Set<string>();
|
||||
|
||||
for (const local of localMessages) {
|
||||
if (!local.id.startsWith(OPTIMISTIC_PREFIX) && !serverIds.has(local.id)) {
|
||||
const match = initialMessages.find(
|
||||
(s) => s.user_id === local.user_id && s.value === local.value,
|
||||
);
|
||||
if (match) optimisticConfirmed.add(match.id);
|
||||
}
|
||||
}
|
||||
|
||||
const serverFiltered = initialMessages.filter(
|
||||
(m) => !optimisticConfirmed.has(m.id),
|
||||
);
|
||||
|
||||
const localFiltered = localMessages.filter((m) => {
|
||||
if (serverIds.has(m.id)) return false;
|
||||
if (m.id.startsWith(OPTIMISTIC_PREFIX)) {
|
||||
const serverValues = new Set(
|
||||
initialMessages
|
||||
.filter((s) => s.user_id === m.user_id)
|
||||
.map((s) => s.value),
|
||||
);
|
||||
if (serverValues.has(m.value)) return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
const merged = [...serverFiltered, ...localFiltered];
|
||||
merged.sort(
|
||||
(a, b) =>
|
||||
new Date(b.created_at).getTime() - new Date(a.created_at).getTime(),
|
||||
);
|
||||
return merged;
|
||||
}, [initialMessages, localMessages]);
|
||||
|
||||
const scrollToBottom = useCallback(() => {
|
||||
bottomRef.current?.scrollIntoView({ behavior: "smooth" });
|
||||
}, []);
|
||||
|
||||
const messageCount = messages.length;
|
||||
|
||||
useEffect(() => {
|
||||
scrollToBottom();
|
||||
}, [messageCount, scrollToBottom]);
|
||||
|
||||
// Clear input after successful send
|
||||
useEffect(() => {
|
||||
if (state !== null && !("error" in state) && !pending) {
|
||||
formRef.current?.reset();
|
||||
}
|
||||
}, [state, pending]);
|
||||
|
||||
const handleAction = useCallback(
|
||||
(formData: FormData) => {
|
||||
const value = formData.get("message");
|
||||
if (typeof value === "string" && value.trim()) {
|
||||
const tempId = `${OPTIMISTIC_PREFIX}${++optimisticCounter.current}`;
|
||||
|
||||
const optimisticMsg: Message = {
|
||||
id: tempId,
|
||||
value: value.trim(),
|
||||
created_at: new Date().toISOString(),
|
||||
user_id: currentUserId,
|
||||
room_id: roomId,
|
||||
user: {
|
||||
name: memberMap.get(currentUserId)?.name ?? "You",
|
||||
avatar_url: memberMap.get(currentUserId)?.avatar_url ?? null,
|
||||
},
|
||||
};
|
||||
|
||||
setLocalMessages((prev) => [optimisticMsg, ...prev]);
|
||||
}
|
||||
action(formData);
|
||||
},
|
||||
[action, currentUserId, roomId, memberMap],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const supabase = createClient();
|
||||
|
||||
const channel = supabase
|
||||
.channel(`room-messages:${roomId}`)
|
||||
.on(
|
||||
"postgres_changes",
|
||||
{
|
||||
event: "INSERT",
|
||||
schema: "public",
|
||||
table: "messages",
|
||||
filter: `room_id=eq.${roomId}`,
|
||||
},
|
||||
(payload: { new: Record<string, string> }) => {
|
||||
const realId = payload.new.id;
|
||||
const realUserId = payload.new.user_id;
|
||||
|
||||
if (realUserId === currentUserId) {
|
||||
// Own message confirmed by server — swap optimistic ID → real ID
|
||||
setLocalMessages((prev) => {
|
||||
if (prev.some((m) => m.id === realId)) return prev;
|
||||
|
||||
const optimisticIdx = prev.findIndex(
|
||||
(m) =>
|
||||
m.id.startsWith(OPTIMISTIC_PREFIX) &&
|
||||
m.user_id === currentUserId,
|
||||
);
|
||||
|
||||
if (optimisticIdx !== -1) {
|
||||
const updated = [...prev];
|
||||
updated[optimisticIdx] = {
|
||||
...updated[optimisticIdx],
|
||||
id: realId,
|
||||
created_at: payload.new.created_at,
|
||||
};
|
||||
return updated;
|
||||
}
|
||||
|
||||
return prev;
|
||||
});
|
||||
} else {
|
||||
// Other user's message — decrypt via server action
|
||||
void decryptMessageAction(
|
||||
roomId,
|
||||
payload.new.value,
|
||||
payload.new.iv ?? "",
|
||||
payload.new.auth_tag ?? "",
|
||||
).then((result) => {
|
||||
if ("plaintext" in result) {
|
||||
const msg: Message = {
|
||||
id: realId,
|
||||
value: result.plaintext,
|
||||
created_at: payload.new.created_at,
|
||||
user_id: realUserId,
|
||||
room_id: payload.new.room_id,
|
||||
user: {
|
||||
name: memberMap.get(realUserId)?.name ?? "Unknown",
|
||||
avatar_url: memberMap.get(realUserId)?.avatar_url ?? null,
|
||||
},
|
||||
};
|
||||
setLocalMessages((prev) => {
|
||||
if (prev.some((m) => m.id === realId)) return prev;
|
||||
return [msg, ...prev];
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
},
|
||||
)
|
||||
.subscribe();
|
||||
|
||||
return () => {
|
||||
void supabase.removeChannel(channel);
|
||||
};
|
||||
}, [roomId, memberMap, currentUserId]);
|
||||
|
||||
const displayMessages = [...messages].reverse();
|
||||
|
||||
return (
|
||||
<div className=" rounded-xl border border-neutral-200 bg-white shadow-sm">
|
||||
{/* Messages area */}
|
||||
<div className="h-[calc(100vh-20rem)] overflow-y-auto p-4">
|
||||
{displayMessages.length === 0 ? (
|
||||
<div className="flex h-full items-center justify-center">
|
||||
<p className="text-sm text-neutral-400">
|
||||
No messages yet. Start the conversation!
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{displayMessages.map((msg) => {
|
||||
const isOwn = msg.user_id === currentUserId;
|
||||
const isPending = msg.id.startsWith(OPTIMISTIC_PREFIX);
|
||||
return (
|
||||
<div
|
||||
key={msg.id}
|
||||
className={`flex ${isOwn ? "justify-end" : "justify-start"}`}
|
||||
>
|
||||
<div
|
||||
className={`max-w-[75%] rounded-2xl px-4 py-2.5 transition-opacity ${
|
||||
isOwn
|
||||
? "bg-neutral-900 text-white"
|
||||
: "bg-neutral-100 text-neutral-900"
|
||||
} ${isPending ? "opacity-60" : "opacity-100"}`}
|
||||
>
|
||||
{!isOwn && (
|
||||
<div className="mb-1 flex items-center gap-2">
|
||||
<Avatar
|
||||
name={msg.user?.name ?? "Unknown"}
|
||||
avatarUrl={msg.user?.avatar_url ?? null}
|
||||
size="md"
|
||||
/>
|
||||
<span className="text-xs font-semibold text-neutral-500">
|
||||
{msg.user?.name ?? "Unknown"}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<p className="text-sm whitespace-pre-wrap wrap-break-words">
|
||||
{msg.value}
|
||||
</p>
|
||||
<p className="mt-1 text-right text-[10px] text-neutral-400">
|
||||
{isPending ? "Sending..." : formatTime(msg.created_at)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
<div ref={bottomRef} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Send bar */}
|
||||
<div className="border-t border-neutral-200 p-3">
|
||||
<form ref={formRef} action={handleAction} className="flex gap-2">
|
||||
<input
|
||||
name="message"
|
||||
type="text"
|
||||
placeholder="Type a message..."
|
||||
required
|
||||
autoComplete="off"
|
||||
className="flex-1 rounded-lg border border-neutral-300 bg-white px-3 py-2 text-sm text-neutral-900 shadow-sm placeholder:text-neutral-400 focus:border-neutral-900 focus:outline-none"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={pending}
|
||||
className="rounded-lg bg-neutral-900 px-4 py-2 text-sm font-medium text-white shadow-sm transition hover:bg-neutral-800 disabled:cursor-not-allowed disabled:bg-neutral-400"
|
||||
>
|
||||
{pending ? "Sending..." : "Send"}
|
||||
</button>
|
||||
</form>
|
||||
{state && "error" in state && (
|
||||
<p className="mt-2 text-xs text-red-600">{state.error}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function formatTime(isoString: string): string {
|
||||
const date = new Date(isoString);
|
||||
return date.toLocaleTimeString("en-US", {
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
});
|
||||
}
|
||||
|
||||
function Avatar({
|
||||
name,
|
||||
avatarUrl,
|
||||
size = "md",
|
||||
}: {
|
||||
name: string;
|
||||
avatarUrl: string | null;
|
||||
size?: "sm" | "md";
|
||||
}) {
|
||||
const sizeClass = size === "sm" ? "size-5" : "size-8";
|
||||
const textSize = size === "sm" ? "text-[10px]" : "text-xs";
|
||||
|
||||
if (avatarUrl) {
|
||||
return (
|
||||
<Image
|
||||
src={avatarUrl}
|
||||
alt=""
|
||||
width={200}
|
||||
height={200}
|
||||
className={`${sizeClass} shrink-0 rounded-full object-cover`}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`flex ${sizeClass} shrink-0 items-center justify-center rounded-full bg-neutral-200 font-medium text-neutral-600 ${textSize}`}
|
||||
>
|
||||
{name.charAt(0).toUpperCase()}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
export default function RoomDetailLoading() {
|
||||
return (
|
||||
<div className="flex h-full flex-col">
|
||||
{/* Header skeleton */}
|
||||
<div className="flex items-center gap-3 border-b border-neutral-200 bg-white px-6 py-3">
|
||||
<div className="size-8 animate-pulse rounded-lg bg-neutral-200" />
|
||||
<div className="space-y-2">
|
||||
<div className="h-4 w-32 animate-pulse rounded bg-neutral-200" />
|
||||
<div className="h-3 w-20 animate-pulse rounded bg-neutral-200" />
|
||||
</div>
|
||||
</div>
|
||||
{/* Chat area skeleton */}
|
||||
<div className="flex flex-1 items-center justify-center">
|
||||
<div className="flex flex-col items-center gap-3">
|
||||
<div className="size-8 animate-spin rounded-full border-2 border-neutral-300 border-t-neutral-900" />
|
||||
<p className="text-sm text-neutral-500">Loading room...</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { MemberEntry } from "./members-list";
|
||||
|
||||
export interface MemberInfo {
|
||||
name: string;
|
||||
avatar_url: string | null;
|
||||
}
|
||||
|
||||
export function buildMemberMap(
|
||||
members: MemberEntry[],
|
||||
): Map<string, MemberInfo> {
|
||||
const map = new Map<string, MemberInfo>();
|
||||
for (const m of members) {
|
||||
map.set(m.user_id, { name: m.name, avatar_url: m.avatar_url });
|
||||
}
|
||||
return map;
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import Image from "next/image";
|
||||
|
||||
export interface MemberEntry {
|
||||
user_id: string;
|
||||
name: string;
|
||||
avatar_url: string | null;
|
||||
}
|
||||
|
||||
export function MembersList({
|
||||
members,
|
||||
currentUserId,
|
||||
onRemoveMember,
|
||||
disableActions,
|
||||
}: {
|
||||
members: MemberEntry[];
|
||||
currentUserId?: string;
|
||||
onRemoveMember?: (userId: string) => void;
|
||||
disableActions?: boolean;
|
||||
}) {
|
||||
if (members.length === 0) return null;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h2 className="text-sm font-semibold text-neutral-900">
|
||||
Members
|
||||
<span className="ml-2 text-xs font-normal text-neutral-500">
|
||||
{members.length}
|
||||
</span>
|
||||
</h2>
|
||||
<ul className="mt-3 divide-y divide-neutral-100 rounded-xl border border-neutral-200 bg-white">
|
||||
{members.map((member) => {
|
||||
const isSelf = member.user_id === currentUserId;
|
||||
|
||||
return (
|
||||
<li
|
||||
key={member.user_id}
|
||||
className="flex items-center gap-3 px-4 py-3"
|
||||
>
|
||||
{member.avatar_url ? (
|
||||
<Image
|
||||
src={member.avatar_url}
|
||||
alt=""
|
||||
width={200}
|
||||
height={200}
|
||||
className="size-8 rounded-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex size-8 items-center justify-center rounded-full bg-neutral-100 text-xs font-medium text-neutral-600">
|
||||
{member.name.charAt(0).toUpperCase()}
|
||||
</div>
|
||||
)}
|
||||
<span className="flex-1 text-sm font-medium text-neutral-900">
|
||||
{member.name}
|
||||
{isSelf && (
|
||||
<span className="ml-1.5 text-xs font-normal text-neutral-400">
|
||||
(you)
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
{!isSelf && onRemoveMember && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onRemoveMember(member.user_id)}
|
||||
disabled={disableActions}
|
||||
className="shrink-0 rounded-md px-2 py-1 text-xs text-neutral-400 transition hover:bg-red-50 hover:text-red-600 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
title={`Remove ${member.name}`}
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
className="size-4"
|
||||
>
|
||||
<path d="M6.28 5.22a.75.75 0 0 0-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 1 0 1.06 1.06L10 11.06l3.72 3.72a.75.75 0 1 0 1.06-1.06L11.06 10l3.72-3.72a.75.75 0 0 0-1.06-1.06L10 8.94 6.28 5.22Z" />
|
||||
</svg>
|
||||
</button>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { createClient } from "@/utils/supabase/server";
|
||||
import { listMembers } from "@/utils/rooms/rooms";
|
||||
import { getMessages } from "@/utils/rooms/messages";
|
||||
import { notFound } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import { Chat } from "./chat";
|
||||
import { RoomSettings } from "./room-settings";
|
||||
import { buildMemberMap } from "./member-map";
|
||||
|
||||
export default async function RoomDetailPage({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ id: string }>;
|
||||
}) {
|
||||
const { id } = await params;
|
||||
const supabase = await createClient();
|
||||
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser();
|
||||
if (!user) return notFound();
|
||||
|
||||
const { data: membership } = await supabase
|
||||
.from("rooms_users")
|
||||
.select("room_id")
|
||||
.eq("room_id", id)
|
||||
.eq("user_id", user.id)
|
||||
.single();
|
||||
|
||||
if (!membership) return notFound();
|
||||
|
||||
const { data: room } = await supabase
|
||||
.from("rooms")
|
||||
.select("id, name, created_at")
|
||||
.eq("id", id)
|
||||
.single();
|
||||
|
||||
if (!room) return notFound();
|
||||
|
||||
const [members, { messages }] = await Promise.all([
|
||||
listMembers(id),
|
||||
getMessages(id),
|
||||
]);
|
||||
|
||||
return (
|
||||
<div className="flex h-full flex-col">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between border-b border-neutral-200 bg-white px-6 py-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<Link
|
||||
href="/rooms"
|
||||
className="flex size-8 items-center justify-center rounded-lg text-neutral-500 transition hover:bg-neutral-100 hover:text-neutral-900"
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
className="size-5"
|
||||
>
|
||||
<path
|
||||
fillRule="evenodd"
|
||||
d="M17 10a.75.75 0 0 1-.75.75H5.612l4.158 3.96a.75.75 0 0 1-1.04 1.08l-5.5-5.25a.75.75 0 0 1 0-1.08l5.5-5.25a.75.75 0 1 1 1.04 1.08L5.612 9.25H16.25A.75.75 0 0 1 17 10Z"
|
||||
clipRule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
</Link>
|
||||
<div>
|
||||
<h1 className="text-base font-semibold text-neutral-900">
|
||||
{room.name}
|
||||
</h1>
|
||||
<p className="text-xs text-neutral-500">
|
||||
{members.length} {members.length === 1 ? "member" : "members"}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<RoomSettings roomId={id} members={members} currentUserId={user.id} />
|
||||
</div>
|
||||
|
||||
{/* Chat */}
|
||||
<div className="flex-1 overflow-hidden">
|
||||
<Chat
|
||||
roomId={id}
|
||||
initialMessages={messages}
|
||||
currentUserId={user.id}
|
||||
memberMap={buildMemberMap(members)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useTransition } from "react";
|
||||
import type { MemberEntry } from "./members-list";
|
||||
import { MembersList } from "./members-list";
|
||||
import { AddMemberForm } from "../add-member-form";
|
||||
import { deleteRoomAction, removeMemberAction } from "../actions";
|
||||
|
||||
export function RoomSettings({
|
||||
roomId,
|
||||
members,
|
||||
currentUserId,
|
||||
}: {
|
||||
roomId: string;
|
||||
members: MemberEntry[];
|
||||
currentUserId: string;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
const [removeError, setRemoveError] = useState<string | null>(null);
|
||||
const [isPending, startTransition] = useTransition();
|
||||
|
||||
const handleDeleteRoom = () => {
|
||||
if (
|
||||
!confirm(
|
||||
"Are you sure you want to delete this room? This cannot be undone.",
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
setDeleting(true);
|
||||
startTransition(() => {
|
||||
deleteRoomAction(roomId);
|
||||
});
|
||||
};
|
||||
|
||||
const handleRemoveMember = (userId: string) => {
|
||||
setRemoveError(null);
|
||||
startTransition(async () => {
|
||||
const result = await removeMemberAction(roomId, userId);
|
||||
if (result.error) {
|
||||
setRemoveError(result.error);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
<button
|
||||
onClick={() => setOpen(!open)}
|
||||
aria-label="Room settings"
|
||||
className="flex size-8 items-center justify-center rounded-lg text-neutral-500 transition hover:bg-neutral-100 hover:text-neutral-900"
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
className="size-5"
|
||||
>
|
||||
<path
|
||||
fillRule="evenodd"
|
||||
d="M2 4.75A.75.75 0 0 1 2.75 4h14.5a.75.75 0 0 1 0 1.5H2.75A.75.75 0 0 1 2 4.75ZM2 10a.75.75 0 0 1 .75-.75h14.5a.75.75 0 0 1 0 1.5H2.75A.75.75 0 0 1 2 10Zm0 5.25a.75.75 0 0 1 .75-.75h14.5a.75.75 0 0 1 0 1.5H2.75a.75.75 0 0 1-.75-.75Z"
|
||||
clipRule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
{open && (
|
||||
<>
|
||||
{/* Backdrop */}
|
||||
<div className="fixed inset-0 z-40" onClick={() => setOpen(false)} />
|
||||
{/* Panel */}
|
||||
<div className="absolute right-0 top-full z-50 mt-2 w-80 rounded-xl border border-neutral-200 bg-white p-5 shadow-lg">
|
||||
<h2 className="text-sm font-semibold text-neutral-900">
|
||||
Room Settings
|
||||
</h2>
|
||||
|
||||
{removeError && (
|
||||
<p className="mt-2 text-xs text-red-600">{removeError}</p>
|
||||
)}
|
||||
|
||||
<div className="mt-4 space-y-5">
|
||||
<AddMemberForm roomId={roomId} />
|
||||
<MembersList
|
||||
members={members}
|
||||
currentUserId={currentUserId}
|
||||
onRemoveMember={handleRemoveMember}
|
||||
disableActions={isPending}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Danger zone */}
|
||||
<div className="mt-5 border-t border-neutral-100 pt-4">
|
||||
<button
|
||||
onClick={handleDeleteRoom}
|
||||
disabled={deleting}
|
||||
className="w-full rounded-lg border border-red-200 bg-white px-3 py-2 text-sm font-medium text-red-600 transition hover:bg-red-50 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
{deleting ? "Deleting..." : "Delete Room"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
import {
|
||||
createRoom,
|
||||
addMember,
|
||||
deleteRoom,
|
||||
removeMember,
|
||||
} from "@/utils/rooms/rooms";
|
||||
import { UUID_REGEX } from "@/utils/validation";
|
||||
|
||||
export type CreateRoomState = {
|
||||
error?: string;
|
||||
} | null;
|
||||
|
||||
export async function createRoomAction(
|
||||
_prevState: CreateRoomState,
|
||||
formData: FormData,
|
||||
): Promise<CreateRoomState> {
|
||||
const name = formData.get("name");
|
||||
if (typeof name !== "string" || !name.trim()) {
|
||||
return { error: "Room name is required." };
|
||||
}
|
||||
|
||||
const result = await createRoom(name.trim());
|
||||
if (result.error) {
|
||||
return { error: result.error };
|
||||
}
|
||||
|
||||
revalidatePath("/rooms");
|
||||
redirect(`/rooms/${result.roomId}`);
|
||||
}
|
||||
|
||||
export type AddMemberState = {
|
||||
success?: boolean;
|
||||
error?: string;
|
||||
} | null;
|
||||
|
||||
export async function addMemberAction(
|
||||
roomId: string,
|
||||
_prevState: AddMemberState,
|
||||
formData: FormData,
|
||||
): Promise<AddMemberState> {
|
||||
const userId = formData.get("userId");
|
||||
if (typeof userId !== "string" || !userId.trim()) {
|
||||
return { error: "User ID is required." };
|
||||
}
|
||||
|
||||
const trimmed = userId.trim();
|
||||
if (!UUID_REGEX.test(trimmed)) {
|
||||
return { error: "Please enter a valid user ID (UUID format)." };
|
||||
}
|
||||
|
||||
const result = await addMember(roomId, trimmed);
|
||||
if (result.error) {
|
||||
return { error: result.error };
|
||||
}
|
||||
|
||||
revalidatePath("/rooms");
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
export async function deleteRoomAction(roomId: string) {
|
||||
const result = await deleteRoom(roomId);
|
||||
if (result.error) {
|
||||
return { error: result.error };
|
||||
}
|
||||
|
||||
revalidatePath("/rooms");
|
||||
redirect("/rooms");
|
||||
}
|
||||
|
||||
export async function removeMemberAction(roomId: string, userId: string) {
|
||||
const result = await removeMember(roomId, userId);
|
||||
if (result.error) {
|
||||
return { error: result.error };
|
||||
}
|
||||
|
||||
revalidatePath(`/rooms/${roomId}`);
|
||||
return { success: true };
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
"use client";
|
||||
|
||||
import { useActionState } from "react";
|
||||
import { addMemberAction, type AddMemberState } from "./actions";
|
||||
|
||||
const initialState: AddMemberState = null;
|
||||
|
||||
export function AddMemberForm({ roomId }: { roomId: string }) {
|
||||
const boundAction = addMemberAction.bind(null, roomId);
|
||||
const [state, action, pending] = useActionState(boundAction, initialState);
|
||||
|
||||
return (
|
||||
<form action={action} className="space-y-3">
|
||||
<label
|
||||
htmlFor="addMemberId"
|
||||
className="block text-sm font-medium text-neutral-700"
|
||||
>
|
||||
Add Member
|
||||
</label>
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
id="addMemberId"
|
||||
name="userId"
|
||||
type="text"
|
||||
placeholder="User ID (UUID)"
|
||||
required
|
||||
className="flex-1 rounded-lg border border-neutral-300 bg-white px-3 py-2 text-sm text-neutral-900 shadow-sm placeholder:text-neutral-400 focus:border-neutral-900 focus:outline-none"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={pending}
|
||||
className="rounded-lg bg-neutral-900 px-4 py-2 text-sm font-medium text-white shadow-sm transition hover:bg-neutral-800 disabled:cursor-not-allowed disabled:bg-neutral-400"
|
||||
>
|
||||
{pending ? "Adding..." : "Add"}
|
||||
</button>
|
||||
</div>
|
||||
{state?.error && <p className="text-sm text-red-600">{state.error}</p>}
|
||||
{state?.success && (
|
||||
<p className="text-sm text-emerald-600">Member added!</p>
|
||||
)}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
"use client";
|
||||
|
||||
import { useActionState } from "react";
|
||||
import { createRoomAction, type CreateRoomState } from "./actions";
|
||||
|
||||
const initialState: CreateRoomState = null;
|
||||
|
||||
export function CreateRoomForm() {
|
||||
const [state, action, pending] = useActionState(
|
||||
createRoomAction,
|
||||
initialState,
|
||||
);
|
||||
|
||||
return (
|
||||
<form action={action} className="space-y-3">
|
||||
<label
|
||||
htmlFor="roomName"
|
||||
className="block text-sm font-medium text-neutral-700"
|
||||
>
|
||||
Create a Room
|
||||
</label>
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
id="roomName"
|
||||
name="name"
|
||||
type="text"
|
||||
placeholder="Room name"
|
||||
required
|
||||
className="flex-1 rounded-lg border border-neutral-300 bg-white px-3 py-2 text-sm text-neutral-900 shadow-sm placeholder:text-neutral-400 focus:border-neutral-900 focus:outline-none"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={pending}
|
||||
className="rounded-lg bg-neutral-900 px-4 py-2 text-sm font-medium text-white shadow-sm transition hover:bg-neutral-800 disabled:cursor-not-allowed disabled:bg-neutral-400"
|
||||
>
|
||||
{pending ? "Creating..." : "Create"}
|
||||
</button>
|
||||
</div>
|
||||
{state?.error && <p className="text-sm text-red-600">{state.error}</p>}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { listRooms } from "@/utils/rooms/rooms";
|
||||
import { CreateRoomForm } from "./create-room-form";
|
||||
import { RoomsList, type RoomEntry } from "./rooms-list";
|
||||
|
||||
export default async function RoomsPage() {
|
||||
const rawRooms = await listRooms();
|
||||
const rooms: RoomEntry[] = rawRooms ?? [];
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-3xl px-6 py-10">
|
||||
<h1 className="text-2xl font-semibold text-neutral-900">Rooms</h1>
|
||||
<p className="mt-1 text-sm text-neutral-500">
|
||||
Your conversations will appear here.
|
||||
</p>
|
||||
|
||||
<div className="mt-8 space-y-8">
|
||||
{/* Create room */}
|
||||
<div className="rounded-xl border border-neutral-200 bg-white p-5 shadow-sm">
|
||||
<CreateRoomForm />
|
||||
</div>
|
||||
|
||||
{/* Rooms list */}
|
||||
<RoomsList rooms={rooms} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import Link from "next/link";
|
||||
|
||||
export interface RoomEntry {
|
||||
id: string;
|
||||
name: string;
|
||||
created_at: string;
|
||||
member_count: number;
|
||||
}
|
||||
|
||||
export function RoomsList({ rooms }: { rooms: RoomEntry[] }) {
|
||||
if (rooms.length === 0) {
|
||||
return (
|
||||
<div className="flex flex-col items-center rounded-xl border border-dashed border-neutral-300 py-12">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth={1}
|
||||
className="size-10 text-neutral-300"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M7.5 8.25h9m-9 3H12m-9.75 1.51c0 1.6 1.123 2.994 2.707 3.227 1.087.16 2.185.283 3.293.369V21l4.076-4.076a1.526 1.526 0 0 1 1.037-.443 48.282 48.282 0 0 0 5.68-.494c1.584-.233 2.707-1.626 2.707-3.228V6.741c0-1.602-1.123-2.995-2.707-3.228A48.394 48.394 0 0 0 12 3c-2.392 0-4.744.175-7.043.513C3.373 3.746 2.25 5.14 2.25 6.741v6.018Z"
|
||||
/>
|
||||
</svg>
|
||||
<p className="mt-3 text-sm text-neutral-400">No rooms yet</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h2 className="text-sm font-semibold text-neutral-900">
|
||||
Your Rooms
|
||||
<span className="ml-2 text-xs font-normal text-neutral-500">
|
||||
{rooms.length}
|
||||
</span>
|
||||
</h2>
|
||||
<ul className="mt-3 space-y-2">
|
||||
{rooms.map((room) => (
|
||||
<li key={room.id}>
|
||||
<Link
|
||||
href={`/rooms/${room.id}`}
|
||||
className="flex items-center justify-between rounded-xl border border-neutral-200 bg-white px-4 py-3 shadow-sm transition hover:border-neutral-300"
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-sm font-medium text-neutral-900">
|
||||
{room.name}
|
||||
</p>
|
||||
<p className="mt-0.5 text-xs text-neutral-500">
|
||||
{room.member_count}{" "}
|
||||
{room.member_count === 1 ? "member" : "members"}
|
||||
</p>
|
||||
</div>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
className="size-5 text-neutral-400"
|
||||
>
|
||||
<path
|
||||
fillRule="evenodd"
|
||||
d="M8.22 5.22a.75.75 0 0 1 1.06 0l4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.75.75 0 0 1-1.06-1.06L11.94 10 8.22 6.28a.75.75 0 0 1 0-1.06Z"
|
||||
clipRule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { signOut } from "@/utils/profile/profile";
|
||||
import Image from "next/image";
|
||||
|
||||
const navItems = [
|
||||
{
|
||||
label: "Rooms",
|
||||
href: "/rooms",
|
||||
icon: (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth={1.5}
|
||||
className="size-5"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M7.5 8.25h9m-9 3H12m-9.75 1.51c0 1.6 1.123 2.994 2.707 3.227 1.087.16 2.185.283 3.293.369V21l4.076-4.076a1.526 1.526 0 0 1 1.037-.443 48.282 48.282 0 0 0 5.68-.494c1.584-.233 2.707-1.626 2.707-3.228V6.741c0-1.602-1.123-2.995-2.707-3.228A48.394 48.394 0 0 0 12 3c-2.392 0-4.744.175-7.043.513C3.373 3.746 2.25 5.14 2.25 6.741v6.018Z"
|
||||
/>
|
||||
</svg>
|
||||
),
|
||||
},
|
||||
{
|
||||
label: "Friends",
|
||||
href: "/friends",
|
||||
icon: (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth={1.5}
|
||||
className="size-5"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M15 19.128a9.38 9.38 0 0 0 2.625.372 9.337 9.337 0 0 0 4.121-.952 4.125 4.125 0 0 0-7.533-2.493M15 19.128v-.003c0-1.113-.285-2.16-.786-3.07M15 19.128v.106A12.318 12.318 0 0 1 8.624 21c-2.331 0-4.512-.645-6.374-1.766l-.001-.109a6.375 6.375 0 0 1 11.964-3.07M12 6.375a3.375 3.375 0 1 1-6.75 0 3.375 3.375 0 0 1 6.75 0Zm8.25 2.25a2.625 2.625 0 1 1-5.25 0 2.625 2.625 0 0 1 5.25 0Z"
|
||||
/>
|
||||
</svg>
|
||||
),
|
||||
},
|
||||
{
|
||||
label: "Profile",
|
||||
href: "/profile",
|
||||
icon: (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth={1.5}
|
||||
className="size-5"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M15.75 6a3.75 3.75 0 1 1-7.5 0 3.75 3.75 0 0 1 7.5 0ZM4.501 20.118a7.5 7.5 0 0 1 14.998 0A17.933 17.933 0 0 1 12 21.75c-2.676 0-5.216-.584-7.499-1.632Z"
|
||||
/>
|
||||
</svg>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
export function Sidebar({
|
||||
displayName,
|
||||
email,
|
||||
avatarUrl,
|
||||
}: {
|
||||
displayName: string;
|
||||
email: string;
|
||||
avatarUrl: string;
|
||||
}) {
|
||||
const pathname = usePathname();
|
||||
return (
|
||||
<aside className="flex w-64 flex-col border-r border-neutral-200 bg-white">
|
||||
{/* Brand */}
|
||||
<div className="flex h-16 items-center gap-2 border-b border-neutral-200 px-6">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="currentColor"
|
||||
className="size-6 text-neutral-900"
|
||||
>
|
||||
<path
|
||||
fillRule="evenodd"
|
||||
d="M4.848 2.771A49.144 49.144 0 0 1 12 2.25c2.43 0 4.817.178 7.152.52 1.978.292 3.348 2.024 3.348 3.97v6.02c0 1.946-1.37 3.678-3.348 3.97a48.901 48.901 0 0 1-3.476.383.39.39 0 0 0-.297.17l-2.755 4.133a.75.75 0 0 1-1.248 0l-2.755-4.133a.39.39 0 0 0-.297-.17 48.9 48.9 0 0 1-3.476-.384c-1.978-.29-3.348-2.024-3.348-3.97V6.741c0-1.946 1.37-3.68 3.348-3.97ZM6.75 8.25a.75.75 0 0 1 .75-.75h9a.75.75 0 0 1 0 1.5h-9a.75.75 0 0 1-.75-.75Zm.75 2.25a.75.75 0 0 0 0 1.5H12a.75.75 0 0 0 0-1.5H7.5Z"
|
||||
clipRule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
<span className="text-lg font-semibold tracking-tight">Fastchat</span>
|
||||
</div>
|
||||
|
||||
{/* Navigation */}
|
||||
<nav aria-label="Main navigation" className="flex-1 space-y-1 px-3 py-4">
|
||||
{navItems.map((item) => {
|
||||
const active = pathname === item.href;
|
||||
return (
|
||||
<Link
|
||||
key={item.href}
|
||||
href={item.href}
|
||||
className={`flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-colors ${
|
||||
active
|
||||
? "bg-neutral-100 text-neutral-900"
|
||||
: "text-neutral-600 hover:bg-neutral-50 hover:text-neutral-900"
|
||||
}`}
|
||||
>
|
||||
{item.icon}
|
||||
{item.label}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
|
||||
{/* User section */}
|
||||
<div className="border-t border-neutral-200 p-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex size-9 items-center justify-center rounded-full bg-neutral-900 text-sm font-medium text-white">
|
||||
<Image
|
||||
src={avatarUrl}
|
||||
alt=""
|
||||
width={200}
|
||||
height={200}
|
||||
className="size-9 rounded-full object-cover"
|
||||
/>
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate text-sm font-medium text-neutral-900">
|
||||
{displayName}
|
||||
</p>
|
||||
<p className="truncate text-xs text-neutral-500">{email}</p>
|
||||
</div>
|
||||
</div>
|
||||
<form action={signOut}>
|
||||
<button
|
||||
type="submit"
|
||||
className="mt-3 flex w-full items-center gap-2 rounded-lg px-3 py-2 text-sm text-neutral-600 transition-colors hover:bg-neutral-50 hover:text-neutral-900"
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth={1.5}
|
||||
className="size-4"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M15.75 9V5.25A2.25 2.25 0 0 0 13.5 3h-6a2.25 2.25 0 0 0-2.25 2.25v13.5A2.25 2.25 0 0 0 7.5 21h6a2.25 2.25 0 0 0 2.25-2.25V15m3 0 3-3m0 0-3-3m3 3H9"
|
||||
/>
|
||||
</svg>
|
||||
Sign out
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
+9
-16
@@ -1,26 +1,19 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
:root {
|
||||
--background: #ffffff;
|
||||
--foreground: #171717;
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--font-sans: var(--font-geist-sans);
|
||||
--font-mono: var(--font-geist-mono);
|
||||
--background: #ffffff;
|
||||
--foreground: #171717;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--background: #0a0a0a;
|
||||
--foreground: #ededed;
|
||||
}
|
||||
:root {
|
||||
--background: #0a0a0a;
|
||||
--foreground: #ededed;
|
||||
}
|
||||
}
|
||||
|
||||
body {
|
||||
background: var(--background);
|
||||
color: var(--foreground);
|
||||
font-family: Arial, Helvetica, sans-serif;
|
||||
background: var(--background);
|
||||
color: var(--foreground);
|
||||
font-family: Arial, Helvetica, sans-serif;
|
||||
}
|
||||
+2
-2
@@ -13,8 +13,8 @@ const geistMono = Geist_Mono({
|
||||
});
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Create Next App",
|
||||
description: "Generated by create next app",
|
||||
title: "Fastchat",
|
||||
description: "A real-time encrypted chat application",
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
"use server";
|
||||
|
||||
import { redirect } from "next/navigation";
|
||||
import { login } from "@/utils/authentication/signin";
|
||||
|
||||
export type LoginState = {
|
||||
error?: string;
|
||||
} | null;
|
||||
|
||||
export async function loginAction(
|
||||
_prevState: LoginState,
|
||||
formData: FormData,
|
||||
): Promise<LoginState> {
|
||||
const email = formData.get("email");
|
||||
const password = formData.get("password");
|
||||
const next = formData.get("next");
|
||||
|
||||
if (typeof email !== "string" || typeof password !== "string") {
|
||||
return { error: "Email and password are required." };
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await login(email, password);
|
||||
if (result?.error) {
|
||||
return { error: result.error.message ?? "Login failed." };
|
||||
}
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Login failed.";
|
||||
return { error: message };
|
||||
}
|
||||
|
||||
const redirectTo =
|
||||
typeof next === "string" && next.startsWith("/") ? next : "/profile";
|
||||
redirect(redirectTo);
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useActionState } from "react";
|
||||
import { loginAction, type LoginState } from "./actions";
|
||||
|
||||
const initialState: LoginState = null;
|
||||
|
||||
export default function LoginForm({ next }: { next?: string }) {
|
||||
const [state, action, pending] = useActionState(loginAction, initialState);
|
||||
|
||||
return (
|
||||
<div className="w-full max-w-md space-y-6">
|
||||
<div className="space-y-1">
|
||||
<h1 className="text-2xl font-semibold">Log in</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Sign in to start chatting with your friends.
|
||||
</p>
|
||||
</div>
|
||||
<form action={action} className="space-y-4">
|
||||
{next && <input type="hidden" name="next" value={next} />}
|
||||
<div className="space-y-2">
|
||||
<label htmlFor="email" className="text-sm font-medium">
|
||||
Email
|
||||
</label>
|
||||
<input
|
||||
id="email"
|
||||
name="email"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
required
|
||||
className="w-full rounded-md border border-neutral-300 bg-white px-3 py-2 text-sm text-neutral-900 shadow-sm focus:border-neutral-900 focus:outline-none"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label htmlFor="password" className="text-sm font-medium">
|
||||
Password
|
||||
</label>
|
||||
<input
|
||||
id="password"
|
||||
name="password"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
required
|
||||
className="w-full rounded-md border border-neutral-300 bg-white px-3 py-2 text-sm text-neutral-900 shadow-sm focus:border-neutral-900 focus:outline-none"
|
||||
/>
|
||||
</div>
|
||||
{state?.error ? (
|
||||
<p className="text-sm text-red-600">{state.error}</p>
|
||||
) : null}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={pending}
|
||||
className="w-full rounded-md bg-neutral-900 px-4 py-2 text-sm font-medium text-white shadow-sm transition disabled:cursor-not-allowed disabled:bg-neutral-400"
|
||||
>
|
||||
{pending ? "Logging in..." : "Log in"}
|
||||
</button>
|
||||
</form>
|
||||
<p className="text-sm text-neutral-600">
|
||||
Don't have an account?{" "}
|
||||
<Link
|
||||
className="font-medium text-neutral-900 hover:underline"
|
||||
href="/register"
|
||||
>
|
||||
Register
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import LoginForm from "./login-form";
|
||||
|
||||
export default async function LoginPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{ next?: string }>;
|
||||
}) {
|
||||
const { next } = await searchParams;
|
||||
return (
|
||||
<main className="flex min-h-screen items-center justify-center bg-neutral-50 px-6 py-12">
|
||||
<LoginForm next={next} />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
+2
-99
@@ -1,102 +1,5 @@
|
||||
import Image from "next/image";
|
||||
import changeBasePath from "@/utils/assets/basepath";
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
export default function Home() {
|
||||
return (
|
||||
<div className="grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20 font-sans">
|
||||
<main className="flex flex-col gap-8 row-start-2 items-center sm:items-start">
|
||||
<Image
|
||||
className="dark:invert"
|
||||
src={changeBasePath("/next.svg")}
|
||||
alt="Next.js logo"
|
||||
width={180}
|
||||
height={38}
|
||||
priority
|
||||
/>
|
||||
<ol className="list-inside list-decimal text-sm text-center sm:text-left font-(family-name:--font-geist-mono)">
|
||||
<li className="mb-2">
|
||||
Get started by editing{" "}
|
||||
<code className="bg-black/0.5 dark:bg-white/6 px-1 py-0.5 rounded font-semibold">
|
||||
app/page.tsx
|
||||
</code>
|
||||
.
|
||||
</li>
|
||||
<li>Save and see your changes instantly.</li>
|
||||
</ol>
|
||||
|
||||
<div className="flex gap-4 items-center flex-col sm:flex-row">
|
||||
<a
|
||||
className="rounded-full border border-solid border-transparent transition-colors flex items-center justify-center bg-foreground text-background gap-2 hover:bg-[#383838] dark:hover:bg-[#ccc] text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5"
|
||||
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<Image
|
||||
className="dark:invert"
|
||||
src={changeBasePath("/vercel.svg")}
|
||||
alt="Vercel logomark"
|
||||
width={20}
|
||||
height={20}
|
||||
/>
|
||||
Deploy now
|
||||
</a>
|
||||
<a
|
||||
className="rounded-full border border-solid border-black/.08 dark:border-white/[.145] transition-colors flex items-center justify-center hover:bg-[#f2f2f2] dark:hover:bg-[#1a1a1a] hover:border-transparent text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5 sm:min-w-44"
|
||||
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
Read our docs
|
||||
</a>
|
||||
</div>
|
||||
</main>
|
||||
<footer className="row-start-3 flex gap-6 flex-wrap items-center justify-center">
|
||||
<a
|
||||
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
|
||||
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<Image
|
||||
aria-hidden
|
||||
src={changeBasePath("/file.svg")}
|
||||
alt="File icon"
|
||||
width={16}
|
||||
height={16}
|
||||
/>
|
||||
Learn
|
||||
</a>
|
||||
<a
|
||||
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
|
||||
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<Image
|
||||
aria-hidden
|
||||
src={changeBasePath("/window.svg")}
|
||||
alt="Window icon"
|
||||
width={16}
|
||||
height={16}
|
||||
/>
|
||||
Examples
|
||||
</a>
|
||||
<a
|
||||
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
|
||||
href="https://nextjs.org?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<Image
|
||||
aria-hidden
|
||||
src={changeBasePath("/globe.svg")}
|
||||
alt="Globe icon"
|
||||
width={16}
|
||||
height={16}
|
||||
/>
|
||||
Go to nextjs.org →
|
||||
</a>
|
||||
</footer>
|
||||
</div>
|
||||
);
|
||||
redirect("/profile");
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
"use server";
|
||||
|
||||
import { signup } from "@/utils/authentication/register";
|
||||
|
||||
export type RegisterState = {
|
||||
error?: string;
|
||||
} | null;
|
||||
|
||||
export async function registerAction(
|
||||
_prevState: RegisterState,
|
||||
formData: FormData,
|
||||
): Promise<RegisterState> {
|
||||
const email = formData.get("email");
|
||||
const password = formData.get("password");
|
||||
|
||||
if (typeof email !== "string" || typeof password !== "string") {
|
||||
return { error: "Email and password are required." };
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await signup(email, password);
|
||||
if (result?.error) {
|
||||
return { error: result.error.message ?? "Registration failed." };
|
||||
}
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Registration failed.";
|
||||
return { error: message };
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import RegisterForm from "./register-form";
|
||||
|
||||
export default function RegisterPage() {
|
||||
return (
|
||||
<main className="flex min-h-screen items-center justify-center bg-neutral-50 px-6 py-12">
|
||||
<RegisterForm />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useActionState } from "react";
|
||||
import { registerAction, type RegisterState } from "./actions";
|
||||
|
||||
const initialState: RegisterState = null;
|
||||
|
||||
export default function RegisterForm() {
|
||||
const [state, action, pending] = useActionState(
|
||||
registerAction,
|
||||
initialState,
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="w-full max-w-md space-y-6">
|
||||
<div className="space-y-1">
|
||||
<h1 className="text-2xl font-semibold">Create an account</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Sign up to start chatting with your friends.
|
||||
</p>
|
||||
</div>
|
||||
<form action={action} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<label htmlFor="email" className="text-sm font-medium">
|
||||
Email
|
||||
</label>
|
||||
<input
|
||||
id="email"
|
||||
name="email"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
required
|
||||
className="w-full rounded-md border border-neutral-300 bg-white px-3 py-2 text-sm text-neutral-900 shadow-sm focus:border-neutral-900 focus:outline-none"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label htmlFor="password" className="text-sm font-medium">
|
||||
Password
|
||||
</label>
|
||||
<input
|
||||
id="password"
|
||||
name="password"
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
required
|
||||
className="w-full rounded-md border border-neutral-300 bg-white px-3 py-2 text-sm text-neutral-900 shadow-sm focus:border-neutral-900 focus:outline-none"
|
||||
/>
|
||||
</div>
|
||||
{state?.error ? (
|
||||
<p className="text-sm text-red-600">{state.error}</p>
|
||||
) : null}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={pending}
|
||||
className="w-full rounded-md bg-neutral-900 px-4 py-2 text-sm font-medium text-white shadow-sm transition disabled:cursor-not-allowed disabled:bg-neutral-400"
|
||||
>
|
||||
{pending ? "Creating account..." : "Register"}
|
||||
</button>
|
||||
</form>
|
||||
<p className="text-sm text-neutral-600">
|
||||
Already have an account?{" "}
|
||||
<Link className="font-medium text-neutral-900 hover:underline" href="/login">
|
||||
Log in
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user