Files

327 lines
10 KiB
TypeScript

"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,
}: Readonly<{
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 () => {
supabase.removeChannel(channel);
};
}, [roomId, memberMap, currentUserId]);
const displayMessages = [...messages].reverse();
return (
<div className="flex min-h-0 flex-1 flex-col border-t-1 border-neutral-200 bg-white shadow-sm">
{/* Messages area */}
<div className="flex-1 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",
}: Readonly<{
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>
);
}